您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Django自定義權(quán)限管理系統(tǒng)的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Django自定義權(quán)限管理系統(tǒng)的示例分析”這篇文章吧。
1. 創(chuàng)建工程文件, 修改setting.py文件
django-admin.py startproject project_name
特別是在 windows 上,如果報錯,嘗試用 django-admin 代替 django-admin.py 試試
setting.py 最終的配置文件
import os import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,os.path.join(BASE_DIR,"apps")) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!g%gzw+-t8*+c2irzcm=r_#*x$q^(x-(^prn7wpnph4w#j$1gl' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.system', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'libs.middleware.permission.permissionMiddleware' ] ROOT_URLCONF = 'iFactory.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'iFactory.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "iFactory", 'USER': "postgres", 'PASSWORD': "postgres", 'HOST': "127.0.0.1", 'PORT': "5432", 'CONN_MAX_AGE': 5, } } # Password validation # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'zh_Hans' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # Session setting SESSION_COOKIE_AGE = 30 * 60 SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # session_permisson_key SESSION_PERMISSION_URL_KEY = "perUrl" SESSION_MENU_KEY = "menu" MENU_ALL = "menuAll" MENU_PERMISSON = "menuPer" # permisson LOGIN_URL = '/login/' REGEX_URL = r'^{url}$' # url作嚴(yán)格匹配 SAFE_URL = [ '/login/', ]
2. 根目錄創(chuàng)建apps文件夾(python包文件夾),創(chuàng)建應(yīng)用system, 把應(yīng)用放入到apps文件夾中
python manage.py startapp system, 在setting中的INSTALLED_APPS中添加對應(yīng)的app
最終的目錄結(jié)構(gòu)
3. 修改system/model.py 文件
#-*-coding:utf-8-*- from django.db import models # Create your models here. class Menu(models.Model): ''' 菜單 ''' title = models.CharField(max_length=32, unique=True) parent = models.ForeignKey("Menu", null=True, blank=True) def __str__(self): # 顯示層級菜單 title_list = [self.title] p = self.parent while p: title_list.insert(0, p.title) p = p.parent return '-'.join(title_list) class Permission(models.Model): ''' 權(quán)限 ''' title = models.CharField(max_length=32, unique=True) url = models.CharField(max_length=128, unique=True) menu = models.ForeignKey("Menu", null=True, blank=True) # 定義菜單間的自引用關(guān)系 # 權(quán)限url 在 菜單下;菜單可以有父級菜單;還要支持用戶創(chuàng)建菜單,因此需要定義parent字段(parent_id) # blank=True 意味著在后臺管理中填寫可以為空,根菜單沒有父級菜單 def __str__(self): # 顯示帶菜單前綴的權(quán)限 return '{menu}---{permission}'.format(menu=self.menu, permission=self.title) class Role(models.Model): ''' 角色:綁定權(quán)限 ''' title = models.CharField(max_length=32, unique=True) # 定義角色和權(quán)限的多對多關(guān)系 permissions = models.ManyToManyField("Permission") def __str__(self): return self.title class User(models.Model): ''' 用戶 -- 角色劃分 ''' username = models.CharField(max_length=32) password = models.CharField(max_length=32) phone = models.CharField(max_length=11) email = models.EmailField() is_admin = models.BooleanField(default=False) is_push_email = models.BooleanField(default=True) is_push_phone = models.BooleanField(default=True) # create_datetime = models.DateTimeField(auto_now_add=True) # 定義用戶和角色的多對多關(guān)系 roles = models.ManyToManyField("Role") def __str__(self): return '{username}---{phone}' \ ''.format(username=self.username, phone=self.phone)
4. 數(shù)據(jù)庫遷移
執(zhí)行 python manage.py makemigrations system
執(zhí)行python manage.py migrate system
5. 建立userService.py文件(文件位置看上圖目錄),代碼如下:
from ..models import Menu def init_user_permission(request, user): ''' 查詢出用戶的所有權(quán)限,進(jìn)行分類寫入session進(jìn)行保存 :param request: :param user: :return: ''' # 查詢出用戶的所有權(quán)限 permisson_item_list = user.roles.values('permissons__title', 'permissons__url', 'permissons__menu_id' ).distinct() permisson_url_list = [] permisson_menu_list = [] all_menu_list = list(Menu.objects.values("id", "title", "parent_id")) for permission_item in permisson_item_list: permisson_url_list.append(permission_item["permissons__url"]) if permission_item["permissons__menu__id"]: temp = { "title": permission_item["permissons__title"], "url": permission_item["permissons__url"], "menu_id": permission_item["permissons__menu_id"] } permisson_menu_list.append(temp) # 寫入session from django.conf import settings request.session[settings.SESSION_PERMISSION_URL_KEY] = permisson_url_list request.session[settings.SESSION_MENU_KEY] = { settings.MENU_ALL: all_menu_list, settings.MENU_PERMISSON: permisson_menu_list, }
6. 建立views_user.py 文件:
#-*-coding:utf-8-*- from django.shortcuts import render from django.http import JsonResponse, HttpResponse from apps.system.services import userService from apps.system.models import User def user_login(request): ''' 用戶登錄 :param request: :return: ''' if request.method == "GET": return render(request, "login.html") else: res = {} username = request.POST.get("username") password = request.POST.get("password") user = User.objects.filter(username=username, password=password).first() if not user: res["status"]= "false" else: userService.init_user_permission(request, user) return JsonResponse(res)
注意: 以上的setting.py 增加的配置:
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'libs.middleware.permission.permissionMiddleware' ]
# Session setting SESSION_COOKIE_AGE = 30 * 60 SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # session_permisson_key SESSION_PERMISSION_URL_KEY = "perUrl" SESSION_MENU_KEY = "menu" MENU_ALL = "menuAll" MENU_PERMISSON = "menuPer" # permisson LOGIN_URL = '/login/' REGEX_URL = r'^{url}$' # url作嚴(yán)格匹配 SAFE_URL = [ '/login/', ]
以上是“Django自定義權(quán)限管理系統(tǒng)的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。