Django 自定义权限管理系统详解(通过中间件认证)


Posted in Python onMarch 11, 2020

1. 创建工程文件, 修改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-(^prn7wpnph3w#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作严格匹配
SAFE_URL = [
  '/login/',
]

2. 根目录创建apps文件夹(python包文件夹),创建应用system, 把应用放入到apps文件夹中

python manage.py startapp system, 在setting中的INSTALLED_APPS中添加对应的app

最终的目录结构

Django 自定义权限管理系统详解(通过中间件认证)

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):
  '''
  权限
  '''
  title = models.CharField(max_length=32, unique=True)
  url = models.CharField(max_length=128, unique=True)
  menu = models.ForeignKey("Menu", null=True, blank=True)
  # 定义菜单间的自引用关系
  # 权限url 在 菜单下;菜单可以有父级菜单;还要支持用户创建菜单,因此需要定义parent字段(parent_id)
  # blank=True 意味着在后台管理中填写可以为空,根菜单没有父级菜单
 
  def __str__(self):
    # 显示带菜单前缀的权限
    return '{menu}---{permission}'.format(menu=self.menu, permission=self.title)
 
class Role(models.Model):
  '''
  角色:绑定权限
  '''
  title = models.CharField(max_length=32, unique=True)
  # 定义角色和权限的多对多关系
  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)
  # 定义用户和角色的多对多关系
  roles = models.ManyToManyField("Role")
 
  def __str__(self):
    return '{username}---{phone}' \
        ''.format(username=self.username, phone=self.phone)

4. 数据库迁移

执行 python manage.py makemigrations system

执行python manage.py migrate system

Django 自定义权限管理系统详解(通过中间件认证)

5. 建立userService.py文件(文件位置看上图目录),代码如下:

from ..models import Menu
 
def init_user_permission(request, user):
  '''
  查询出用户的所有权限,进行分类写入session进行保存
  :param request:
  :param user:
  :return:
  '''
  # 查询出用户的所有权限
  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作严格匹配
SAFE_URL = [
  '/login/',
]

以上这篇Django 自定义权限管理系统详解(通过中间件认证)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python开发的小球完全弹性碰撞游戏代码
Oct 15 Python
python 实现tar文件压缩解压的实例详解
Aug 20 Python
python自动登录12306并自动点击验证码完成登录的实现源代码
Apr 25 Python
mac 安装python网络请求包requests方法
Jun 13 Python
通过python顺序修改文件名字的方法
Jul 11 Python
python保存文件方法小结
Jul 27 Python
python使用xlrd和xlwt读写Excel文件的实例代码
Sep 05 Python
django项目登录中使用图片验证码的实现方法
Aug 15 Python
关于pandas的离散化,面元划分详解
Nov 22 Python
Python机器学习之底层实现KNN
Jun 20 Python
分享提高 Python 代码的可读性的技巧
Mar 03 Python
Django框架中模型的用法
Jun 10 Python
Django User 模块之 AbstractUser 扩展详解
Mar 11 #Python
pygame实现飞机大战
Mar 11 #Python
Django框架models使用group by详解
Mar 11 #Python
python检查目录文件权限并修改目录文件权限的操作
Mar 11 #Python
python 链接sqlserver 写接口实例
Mar 11 #Python
浅谈Python中range与Numpy中arange的比较
Mar 11 #Python
python读取当前目录下的CSV文件数据
Mar 11 #Python
You might like
header()函数使用说明
2006/11/23 PHP
用PHP进行MySQL删除记录操作代码
2008/06/07 PHP
PHP微信开发之二维码生成类
2015/06/26 PHP
详解PHP的Yii框架中扩展的安装与使用
2016/04/01 PHP
PHP文件上传类实例详解
2016/04/08 PHP
PHP生成制作验证码的简单实例
2016/06/12 PHP
详解PHP中的序列化、反序列化操作
2017/03/21 PHP
PHP 面向对象程序设计之类属性与类常量实现方法分析
2020/04/13 PHP
php实现的证件照换底色功能示例【人像抠图/换背景图】
2020/05/29 PHP
javascript之典型高阶函数应用介绍二
2013/01/10 Javascript
jquery1.9 下检测浏览器类型和版本的方法
2013/12/26 Javascript
JavaScript Length 属性的总结
2015/11/02 Javascript
跟我学习javascript的Date对象
2015/11/19 Javascript
vue中用H5实现文件上传的方法实例代码
2017/05/27 Javascript
Scala解析Json字符串的实例详解
2017/10/11 Javascript
旺旺在线客服代码 旺旺客服代码生成器
2018/01/09 Javascript
11行JS代码制作二维码生成功能
2018/03/09 Javascript
vue3.0中使用postcss-pxtorem的具体方法
2019/11/20 Javascript
js与jquery获取input输入框中的值实例讲解
2020/02/27 jQuery
Linux下使用python调用top命令获得CPU利用率
2015/03/10 Python
基于python元祖与字典与集合的粗浅认识
2017/08/23 Python
python文件操作之批量修改文件后缀名的方法
2018/08/10 Python
用python生成(动态彩色)二维码的方法(使用myqr库实现)
2019/06/24 Python
python basemap 画出经纬度并标定的实例
2019/07/09 Python
pandas DataFrame 警告(SettingWithCopyWarning)的解决
2019/07/23 Python
使用tensorflow显示pb模型的所有网络结点方式
2020/01/23 Python
详解用Pytest+Allure生成漂亮的HTML图形化测试报告
2020/03/31 Python
浅谈Python中os模块及shutil模块的常规操作
2020/04/03 Python
python实现最短路径的实例方法
2020/07/19 Python
Python自动登录QQ的实现示例
2020/08/28 Python
Python tempfile模块生成临时文件和临时目录
2020/09/30 Python
网络编辑职责
2014/03/01 职场文书
银行优秀员工事迹材料
2014/05/29 职场文书
银行求职信
2014/05/31 职场文书
班级文化建设标语
2014/06/23 职场文书
羊脂球读书笔记
2015/06/30 职场文书