从FBV到CBV三(权限)
丛FBC到CBV三(权限)
span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }.cm-searching {background: #ffa; background: rgba(255, 255, 0, .4);}.cm-force-border { padding-right: .1px; }@media print { .CodeMirror div.CodeMirror-cursors {visibility: hidden;}}.cm-tab-wrap-hack:after { content: ""; }span.CodeMirror-selectedtext { background: none; }.CodeMirror-activeline-background, .CodeMirror-selected {transition: visibility 0ms 100ms;}.CodeMirror-blur .CodeMirror-activeline-background, .CodeMirror-blur .CodeMirror-selected {visibility:hidden;}.CodeMirror-blur .CodeMirror-matchingbracket {color:inherit !important;outline:none !important;text-decoration:none !important;}.CodeMirror-sizer {min-height:auto !important;}
-->
li {list-style-type:decimal;}.wiz-editor-body ol.wiz-list-level2 > li {list-style-type:lower-latin;}.wiz-editor-body ol.wiz-list-level3 > li {list-style-type:lower-roman;}.wiz-editor-body li.wiz-list-align-style {list-style-position: inside; margin-left: -1em;}.wiz-editor-body blockquote {padding: 0 12px;}.wiz-editor-body blockquote > :first-child {margin-top:0;}.wiz-editor-body blockquote > :last-child {margin-bottom:0;}.wiz-editor-body img {border:0;max-width:100%;height:auto !important;margin:2px 0;}.wiz-editor-body table {border-collapse:collapse;border:1px solid #bbbbbb;}.wiz-editor-body td,.wiz-editor-body th {padding:4px 8px;border-collapse:collapse;border:1px solid #bbbbbb;min-height:28px;word-break:break-word;box-sizing: border-box;}.wiz-editor-body td > div:first-child {margin-top:0;}.wiz-editor-body td > div:last-child {margin-bottom:0;}.wiz-editor-body img.wiz-svg-image {box-shadow:1px 1px 4px #E8E8E8;}.wiz-hide {display:none !important;}
-->
权限
准备数据表
用户组(group) | |
id | group_name |
1 | usual |
2 | vip |
3 | svip |
4 | admin |
用户(user) | |||
id | username | password | group_id |
1 | Joshua | 123 | 1 |
2 | William | 123 | 2 |
3 | Daniel | 123 | 3 |
4 | Michael | 123 | 4 |
创建项目及app:
# -*- coding:utf-8 -*-
from django.db import models
class Group(models.Model):
id = models.AutoField(primary_key=True)
group_name = models.CharField(max_length=40)
class Meta:
db_table = 'group'
class User(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=40,unique=True)
password = models.CharField(max_length=40)
group_id = models.ForeignKey(Group, default=1)
class Meta:
db_table = 'user'
from django.http.response import JsonResponse
from rest_framework.views import APIView
from permissions.models import User, Group
class Users(APIView):
def get(self, request):
users = User.objects.all().values()
return JsonResponse(list(users), safe=False)
class Groups(APIView):
def get(self, request):
groups = Group.objects.all().values()
return JsonResponse(list(groups), safe=False)
from django.conf.urls import url
from django.contrib import admin
from permissions.views import Users, Groups
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/$', Users.as_view(), name='user'),
url(r'^group/$', Groups.as_view(), name='group'),
]
会员项目(member_programs) | |
id | program_name |
1 | 书法长卷 |
2 | 书法碑帖 |
3 | 墓志塔铭 |
4 | 兰亭集序 |
class MemberProgram(models.Model):
id = models.AutoField(primary_key=True)
program_name = models.CharField(max_length=100)
class Meta:
db_table = 'member_program'
from django.conf.urls import url
from permissions.views import Users, Groups, MemberPrograms
urlpatterns = [
url(r'^user/$', Users.as_view(), name='user'),
url(r'^group/$', Groups.as_view(), name='group'),
url(r'^program/$', MemberPrograms.as_view(), name='program'),
]
class MemberPrograms(APIView):
def get(self, request):
programs = MemberProgram.objects.all().values()
return JsonResponse(list(programs), safe=False)
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
name = request._request.GET.get('username')
print(name)
return (name, None)
class MemberPrograms(APIView):
authentication_classes = [MyAuthentication, ]
def get(self, request):
if not request.user: # 没有用户身份,不允许访问
ret = {'code': 1002, 'error': '权限被拒'}
return JsonResponse(ret)
username = request.user
try:
group_name = User.objects.get(username=username).group.group_name
except User.DoesNotExist: # 用户身份不存在,返回错误信息
ret = {'code': 1003, 'error': '用户不存在'}
return JsonResponse(ret)
if group_name == 'usual': # 是普通用户,没有权限
ret = {'code': 1002, 'error': '权限被拒'}
return JsonResponse(ret)
programs = MemberProgram.objects.all().values() # 用户权限满足条件 返回接口信息
return JsonResponse(list(programs), safe=False)
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import PermissionDenied
lass MyAuthentication(BaseAuthentication):
def authenticate(self, request):
name = request._request.GET.get('username')
print(name)
return (name, None)
class MyPermission(BasePermission):
def has_permission(self, request, view):
if not request.user:
raise PermissionDenied('权限被拒')
username = request.user
try:
group_name = User.objects.get(username=username).group.group_name
except User.DoesNotExist:
raise PermissionDenied('用户不存在')
if group_name == 'usual':
raise PermissionDenied('权限被拒')
return True
class MemberPrograms(APIView):
authentication_classes = [MyAuthentication, ]
permission_classes = [MyPermission, ]
def get(self, request):
programs = MemberProgram.objects.all().values()
return JsonResponse(list(programs), safe=False)
x
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
# 身份验证
self.perform_authentication(request)
# 权限验证
self.check_permissions(request)
self.check_throttles(request)
x
def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_permissions(): # 1
if not permission.has_permission(request, self): # 2
self.permission_denied( # 3
request, message=getattr(permission, 'message', None)
)
第一步: self.get_permissions:
x
def get_permissions(self):
"""
Instantiates and returns the list of permissions that this view requires.
"""
return [permission() for permission in self.permission_classes]
self.permission_classes 就是我们定义的permissions,默认是从seeting.py配置文件中找,如果我们的view中制定了这一项,就使用view中的permission,而不用配置文件中的
permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
x
def permission_denied(self, request, message=None):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if request.authenticators and not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=message)
message = '需要会员用户才能访问'
def has_permission(self, request, view):
if not request.user:
return False
username = request.user
try:
group_name = User.objects.get(username=username).group.group_name
except User.DoesNotExist:
return False
if group_name == 'usual':
return False
return True
x
class MyPermission(BasePermission):
message = '需要会员用户才能访问'
def has_permission(self, request, view):
if not request.user:
return False
username = request.user
try:
group_name = User.objects.get(username=username).group.group_name
except User.DoesNotExist:
return False
if group_name == 'usual':
return False
return True
从FBV到CBV三(权限)的更多相关文章
- 一、虚拟环境.二、路由配置主页与404.三、2.x路由分发.四、伪静态.五、request对象.六、FBV与CBV.七、文件上传.
一.虚拟环境 ''' 解决版本共存 1. 用pycharm选择File点击NewProject然后选择virtualenv创建一个纯净环境 2. 打开下载的目录将venv文件夹下的所有文件(纯净的环境 ...
- python 视图 (FBV、CBV ) 、Request 和Response对象 、路由系统
一.FBV和CBV1.基于函数的view,就叫FBV(Function Based View) 示例: def add_book(request): pub_obj=models.Publisher. ...
- django请求生命周期,FBV和CBV,ORM拾遗,Git
一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...
- Django之FBV与CBV
一.FBV与CBV FBV(function based views),即基于函数的视图:CBV(class based views),即基于类的视图,也是基于对象的视图.当看到这个解释时,我是很萌的 ...
- python 全栈开发,Day84(django请求生命周期,FBV和CBV,ORM拾遗,Git)
一.django 请求生命周期 流程图: 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post, ...
- django基础 -- 4. 模板语言 过滤器 模板继承 FBV 和CBV 装饰器 组件
一.语法 两种特殊符号(语法): {{ }}和 {% %} 变量相关的用{{}},逻辑相关的用{%%}. 二.变量 1. 可直接用 {{ 变量名 }} (可调用字符串, 数字 ,列表,字典,对象等) ...
- Django FBV和CBV -
一.FBV和CBV 在Python菜鸟之路:Django 路由.模板.Model(ORM)一节中,已经介绍了几种路由的写法及对应关系,那种写法可以称之为FBV: function base view ...
- django基础之FBV与CBV,ajax序列化补充,Form表单
目录: FBV与CBV ajax序列化补充 Form表单(一) 一.FBV与CBV 1.什么是FBV.CBV? django书写view时,支持两种格式写法,FBV(function bases vi ...
- Python菜鸟之路:Django 路由补充1:FBV和CBV - 补充2:url默认参数
一.FBV和CBV 在Python菜鸟之路:Django 路由.模板.Model(ORM)一节中,已经介绍了几种路由的写法及对应关系,那种写法可以称之为FBV: function base view ...
随机推荐
- Linux自动输入密码登录用户
每次进去Linux系统,都有切换root用户,输入密码很麻烦,所以就写了一个小脚本,自动输入密码,登录到root用户, 1,首先检查一些是否安装了expect root@wuzs:/home/wuzs ...
- SSH2配置
Ubuntu14.04配置openSSH-server时报错,很有可能是因为如下的报错原因 这个问题大概应该是你的/etc/apt/的源有问题,但大概可以这么解决:1.sudo apt-get pur ...
- 利用java执行shell脚本
BPMN中存在由系统执行的脚本任务,shell脚本任务也是该系统任务脚本中的一种,利用的也是由java执行shell脚本. 代码中的ProcessBuilder类,为java.lang.Process ...
- 1.Spring项目启动时,加载相关初始化配置
Spring项目启动时,会加载一些常用的配置: 1.加载spring上下文 SpringApplicationContextUtils.initApplicationContext(event.get ...
- python常见报错
1.Pycharm No module named requests 的解决方法 pip install requests 然后重启pycharm
- ubuntu 设置qt程序开机启动
1.建立一个桌面文件,forklift-app.desktop Name填写程序的名字 Exec执行程序的路径 [Desktop Entry] Version=1.0 Name=forklift-ap ...
- 英特尔® 图形性能分析器 2019 R1 版本
了解并下载全新英特尔® 图形性能分析器 2019 R1 版本.新版本新增了 DX11 和 Vulkan 多帧流捕获模式,可以在“帧和图形跟踪分析器”中分析 Vulkan 应用.此外,帧分析器还添加了 ...
- Linux常用命令详解(1)
基础命令: ls man pwd cd mkdir echo touch cp mv rm rmdir cat more less head tail clear poweroff reboot 命令 ...
- 记一次 Vultr配置
这里不想排版,因为心情复杂. 第一次搞这个VPS,真的是很气人,由于中英文的关系我一开始就误操作了,让VPS一直挂载着Ubuntu18.10,所以系统一直是在光盘的引导界面,这个问题知道我注册后的四个 ...
- finereport 填报 单元格 JS 触发 提交SQL 事件
var location = this.options.location; var cr = FR.cellStr2ColumnRow(location); var col = cr.col; var ...