Day 30 Xadmin+RBAC+Cache+Signal

Day 30 Xadmin+RBAC+Cache+Signal

RBAC is built in Django, and I created six tables by myself, so everyone likes to use Django for background management

1. PBAC-role-based access control

1. What is PBAC

RBAC: Role-Based Access Control
In RBAC, permissions are associated with roles, and users get the permissions of these roles by becoming members of appropriate roles. This greatly simplifies the management of permissions. In this way, the management is hierarchical, and the authority is assigned to the role , and the role is assigned to the user . The authority design is very clear and easy to manage.

2. Application

RBAC-Role-Based Access Control
Django's Auth component uses the authentication rule is RBAC

  • 1) The system (CRM system) that specializes in personnel authority management is used internally by the company, so the data volume is below 10w, and the general efficiency requirements are not very high.
  • Regular projects with a large number of users will be divided into two types of users: foreground users (three major authentications) and background users (managed by BRAC)
  • Conclusion: Django projects with no special requirements can directly use the six tables of Auth component permissions. There is no need to customize the six tables, and there is no need to disconnect the table relationship. You may need to customize the User table.

3. Front and back permission control

  1. The operation of each table by the background user is completed by the background project. We can directly use the admin background project (built in Django)
  2. Later, you can also use the xadmin framework to do background user rights management
  3. How to deal with the authority management of front-end users
    • The definition of the view class bunch of data interfaces, different login whether the user can access the view class , can on behalf of the privileged, not on behalf of an unprivileged user rights front desk three authentication framework drf

4. Built-in six tables

  • auth_user: user table, extended
  • auth_group: role table (group table)
  • auth_permission: permission table
  • auth_user_groups: intermediate table of users to roles
  • auth_group_permissions: an intermediate table of roles to permissions
  • auth_user_user_permissions: intermediate table of user permissions (this table is optional, but forFiner granularity, So it was established)

5. How to add

method one

image-20201117160117004

Way two

# views.py

from django.contrib.auth.admin import Group


# 这里导入的都是表名大写

def index(request):
    # 和正常的创建方式没有区别
    Group.objects.create(name="歪比歪比")
    
    
# Group源码
class Group(models.Model):
    # 两个字段 以及关系
    name = models.CharField(_('name'), max_length=150, unique=True)
    permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('permissions'),
        blank=True,
    )
    objects = GroupManager()
    class Meta:
        verbose_name = _('group')
        verbose_name_plural = _('groups')
    def __str__(self):
        return self.name
    def natural_key(self):
        return (self.name,)

Second, the use of Xadmin

1 Django has a built-in admin, some people think it is ugly, the function is not powerful enough, this group of people wrote a called xadmin, to replace admin

1. Installation

Install the latest version of xadmin through the following command

区分1.x和2.x
    	-1.x :pip3 install xadmin
        -2.x :pip3 install git+git://github.com/sshwsfc/xadmin.git@django2
               pip3 install https://codeload.github.com/sshwsfc/xadmin/zip/django2

2. Use

  • Register the following applications in the configuration file

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # 把apps目录设置环境变量中的导包路径
    sys.path.append( os.path.join(BASE_DIR,"luffy/apps") )
    
    
    INSTALLED_APPS = [
        ...
        'xadmin',
        'crispy_forms',
        'reversion',
        ...
    ]
    
    # 修改使用中文界面
    LANGUAGE_CODE = 'zh-hans'
    # 时区这边好像不区分大小写 都可以
    TIME_ZONE = 'asia/shanghai'
    
    USE_TZ = False
    
  • Perform routing configuration

    import xadmin
    xadmin.autodiscover()
    from xadmin.plugins import xversion
    xversion.register_models()
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('xadmin/',xadmin.site.urls)
        
    ]
    
  • Perform data migration, otherwise an error will be reported and the table cannot be found

    manage.py makemigrations
    manage.py migrate
    
  • If you have logged in as a super user before, he will automatically log in

3. Beautify

from django.contrib import admin

from app01 import models
from django.contrib.auth.admin import UserAdmin as UAdmin

# Register your models here.
admin.site.register(models.Book)
admin.site.register(models.Author)
admin.site.register(models.Publish)

import xadmin
from xadmin import views
from app01 import models


class BaseSetting():
    """xadmin的基本配置"""
    enable_themes = True  # 开启主题切换功能
    use_bootswatch = True


class GlobalSettings():
    """xadmin的全局配置"""
    site_title = "这是标题"  # 设置站点标题
    site_footer = "这是尾巴"  # 设置站点的页脚
    # menu_style = "accordion"  # 设置菜单折叠


# 这里的注册方法和默认的不一样,相当于把参数一和参数二关联起来
# 然后执行
xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSettings)


class BookClass():
    # 该表展示的字段
    list_display = ['id', 'name', 'price', 'publish']
    # 按照这些字段搜索
    search_fields = ['id', 'name']
    # 按哪些字段过滤
    list_filter = ['is_delete']
    
    # 可以把数据导出成excel,json,xml格式
    list_export = ('xls', 'xml', 'json')
    # list_export设置为None来禁用数据导出功能
    list_export_fields = ('id', 'name', 'price')
    # 内置绘图功能
    data_charts = {
    
    
        "order_amount": {
    
    
            'title': '图书和价格表',
            "x-field": "price",
            "y-field": ('publish',),
            "order": ('id',)
        },
        
    }


xadmin.site.register(models.Book, BookClass)
xadmin.site.register(models.Publish)
xadmin.site.register(models.Author)


image-20201117164759564

Three, Django cache

1. Django provides 6 caching methods

  • Development and debugging
  • RAM
  • file
  • database
  • Memcache cache (python-memcached module)
  • Memcache cache (pylibmc module)

1342004-20180708105938925-1930173957

2. Configuration

File cache (the website is relatively small, and there is no money, you can use the form of files)

    CACHES = {
    
    
     'default': {
    
    
      'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', #指定缓存使用的引擎
      'LOCATION': r'E:\cache',        #指定缓存的路径
      'TIMEOUT':300,              #缓存超时时间(默认为300秒,None表示永不过期)
      'OPTIONS':{
    
    
       'MAX_ENTRIES': 300,            # 最大缓存记录的数量(默认300)
       'CULL_FREQUENCY': 3,           # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
      }
     }   
}

3. Use (cache granularity)

3.1 Single page cache

@cache_page(5)  # 设置缓存时间 超过时间重新加载
def index(request):
    ctime = time.time()
    return render(request, 'index.html', {
    
    "time": ctime})

Note: I commented out the setting here and it can be used as usual

3.2 Local cache (a certain location in the page cache)

# index.html 中
# 缓存十秒钟 唯一变量名
{
    
    % load cache %}
{
    
    % cache 10 '唯一名 用作标记' %}
    {
    
    {
    
     time }}
{
    
    % endcache %}

image-20201117191059338

3.3 The whole site cache (two middleware)

# 在setting中配置
#直接copy

‘django.middleware.cache.UpdateCacheMiddleware’, #第一,重写了process_response
    '。。。',
    ‘django.middleware.cache.FetchFromCacheMiddleware’, #最后,重写了process_requset

# 缓存过期时间
    CACHE_MIDDLEWARE_SECONDS=5

3.4 Use of cache after separation of front and back ends

from django.core.cache import cache


class BookView(APIView):
    
    def get(self, request, *args, **kwargs):
        cache_data = cache.get('cache_book_list')
        if cache_data:  # 如果有值说明,已经缓存了  直接返回就好了
            print('我已经缓存了!')
            return Response(cache_data)
        else:
            print('我还没缓存')
            books = models.Book.objects.all()
            ser = serializer.BookSerializer(books, many=True)
            # 源码中暂时找不到相关参数使用,可以理解为
            # 缓存标志(通过这个判断是否缓存了)
            # ser.data 缓存的数据
            # 100缓存过期的时间
            cache.set('cache_book_list', ser.data, 100)
            return Response(ser.data)

image-20201117193220140

Note: I still comment out the setting here, but the cache file is gone, it is better to add it!

3.5 cache can cache all data types, including custom classes (pickle)

Four, django signal

Signals can be understood in simple terms. When we have many things to do, it is usually messy. We don't know what we have done. Signals are just a sign . I started doing something , and then I finished it !

1342004-20180708114317159-1449518127

  • We can record as log

  • Signals are also more flexible than middleware

Django built-in signals

CopyModel signals
    pre_init                    # django的modal执行其构造方法前,自动触发
    post_init                   # django的modal执行其构造方法后,自动触发
    pre_save                    # django的modal对象保存前,自动触发
    post_save                   # django的modal对象保存后,自动触发
    pre_delete                  # django的modal对象删除前,自动触发
    post_delete                 # django的modal对象删除后,自动触发
    m2m_changed                 # django的modal中使用m2m字段操作第三张表(add,remove,clear)前后,自动触发
    class_prepared              # 程序启动时,检测已注册的app中modal类,对于每一个类,自动触发
Management signals
    pre_migrate                 # 执行migrate命令前,自动触发
    post_migrate                # 执行migrate命令后,自动触发
Request/response signals
    request_started             # 请求到来前,自动触发
    request_finished            # 请求结束后,自动触发
    got_request_exception       # 请求异常后,自动触发
Test signals
    setting_changed             # 使用test测试修改配置文件时,自动触发
    template_rendered           # 使用test测试渲染模板时,自动触发
Database Wrappers
    connection_created          # 创建数据库连接时,自动触发

Use of Django signals

method one

Import built-in signals

# 请求来了的信号
from django.core.signals import request_started

# 2 创建一个函数
def start_signal(sender, **kwargs):
    print(sender)
    print(kwargs)
    print('请求来了,我被标记了!')


# 3 跟内置信号绑定
request_started.connect(start_signal)

Way two

 from django.core.signals import request_started,request_finished
        from django.dispatch import receiver
        @receiver(request_finished)  # 内置信号pre_save和my_callback函数绑定了
        def my_callback(sender, **kwargs):
            print("请zzou了,走了我")
  4 信号的应用场景:
		-记录日志(对象创建就写入日志)
    	-解耦合

Guess you like

Origin blog.csdn.net/A1L__/article/details/109755363