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
最终的目录结构
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
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 自定义权限管理系统详解(通过中间件认证)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]