Django之自定义权限
官方解释
Custom permissions¶
To create custom permissions for a given model object, use the permissions model Meta attribute.
This example Task model creates three custom permissions, i.e., actions users can or cannot do with Task instances, specific to your application:
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)
The only thing this does is create those extra permissions when you run manage.py migrate (the function that creates permissions is connected to the post_migrate signal). Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application (viewing tasks, changing the status of tasks, closing tasks.) Continuing the above example, the following checks if a user may view tasks:
user.has_perm('app.view_task')
项目实战
定义权限字典
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=64)
school = models.ForeignKey('School') def __unicode__(self):
return self.name # 设置3个权限字段,拥有权限者可操作此表(在admin中授权用户)
class Meta:
permissions = (
('view_customer_list',u"查看客户列表"), # 权限字段名称及其解释
('view_customer_info',u"查看客户详情"),
('edit_own_customer_info',u"修改客户信息"),
)
在APP下新建permissions.py,用于权限匹配控制
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'Kongzhagen' from django.core.urlresolvers import resolve
from django.shortcuts import render,redirect # 3个权限字段对应三个URL规则,匹配后可操作
perm_dic = {
'view_customer_list':['customer_list','GET',[]], # 权限字段名称(models表中定义),URL别名,GET方法,请求参数
'view_customer_info':['customer_detail','GET',[]],
'edit_own_customer_info':['customer_detail','POST',['qq','name']], # GET为查询,POST提交数据
} def perm_check(*args, **kwargs):
request = args[0]
# 反向解析request中url
url_resovle_obj = resolve(request.path_info)
current_url_namespace = url_resovle_obj.url_name
print "url namespace:",current_url_namespace
matched_flag = False
matched_perm_key = None
# 如果正确反解析出了url且其在权限字典中
if current_url_namespace is not None:
print "find perm item ..."
for perm_key in perm_dic:
perm_val = perm_dic[perm_key]
if len(perm_val) == 3:
url_namespace,request_method,request_args = perm_val
# 如果request中的url、get方法与权限列表中相同
if url_namespace == current_url_namespace:
if request.method == request_method:
# 如果权限列表中无请求参数,此时已可以确定找到了权限规则
if not request_args:
matched_flag = True
matched_perm_key = perm_key
print 'matched perm ...'
break
else:
# 如果权限列表中有请求的参数,反射出request中get或post数据
request_method_func = getattr(request,request_method)
# 如果权限列表中所有请求参数都与反射出的参数匹配,则证明权限匹配成功
for request_arg in request_args:
if request_method_func.get(request_arg) is not None:
matched_flag = True
else:
# 一旦有不匹配的情况,则证明权限已经匹配错误,后续无须再做判断
matched_flag = False
print "request arg[%s] not matched" % request_arg
break
# 如果此条规则匹配成功,不需要再做后续其它规则的匹配
if matched_flag == True:
print "--passed permission check --"
matched_perm_key = perm_key
break
else:
# 如果request解析出的url与urls不匹配,放过???
return True
# request请求与权限规则已匹配
if matched_flag == True:
perm_str = 'crm.%s' % matched_perm_key
# 如果用户被授与此权限,返回True,否则返回False
if request.user.has_perm(perm_str):
print "\033[42;1m ------ permission checked -------\033[0m"
return True
else:
print "\033[41;1m ------- no permission --------\033[0m"
print request.user,perm_str
return False
else:
print "\033[41;1m ------ no matched permission ----- \033[0m" def check_permission(func):
def wrapper(*args, **kwargs):
print "--start check perms",args[0]
if not perm_check(*args, **kwargs):
return render(args[0],'crm/403.html')
return func(*args, **kwargs)
return wrapper
修改视图

设置URLS
from django.conf.urls import url
from django.contrib import admin
import views urlpatterns = [
url(r'^$', views.dashboard),
url(r'^customers/$', views.customers, name='customer_list'),
url(r'^customers/(\d+)/$', views.customerInfo, name='customer_detail'),
]
验证
以普通用户登陆customers,查看客户列表

用admin给普通用户授予查看客户列表权限

再次用普通用户查看

自定义权限设置成功。。。
Django之自定义权限的更多相关文章
- django的自定义权限
最近在写发布系统,涉及到权限的控制 参考 黄小墨同学的博客实现了 如下 1:定义一张权限控制的表 [root@localhost app01]# tailf -25 models.py class P ...
- django 增加自定义权限的一个博客,讲的很详细
来自 https://www.cnblogs.com/huangxm/p/5770735.html
- Django(63)drf权限源码分析与自定义权限
前言 上一篇我们分析了认证的源码,一个请求认证通过以后,第二步就是查看权限了,drf默认是允许所有用户访问 权限源码分析 源码入口:APIView.py文件下的initial方法下的check_per ...
- django rest framework权限和认证
Django rest framework之权限 一.Authentication用户认证配置 1.四种验证及官网描述: BasicAuthentication 此身份验证方案使用HTTP基本身份验证 ...
- django自带权限机制
1. Django权限机制概述 权限机制能够约束用户行为,控制页面的显示内容,也能使API更加安全和灵活:用好权限机制,能让系统更加强大和健壮.因此,基于Django的开发,理清Django权限机制是 ...
- Django REST framework - 权限和限制
目录 Django REST framework 权限和限制 (你能干什么) 设置权限的方法 案例 第一步: 定义一个权限类 第二步: 使用 视图级别 全局级别设置 --- 限制 (你一分钟能干多少次 ...
- django 用户与权限管理
django中使用content_type表进行存储app与model的关系.在permission表中设立了name(权限的名字,中英文均可)content_type_id(与content_typ ...
- Django REST framework —— 权限组件源码分析
在上一篇文章中我们已经分析了认证组件源码,我们再来看看权限组件的源码,权限组件相对容易,因为只需要返回True 和False即可 代码 class ShoppingCarView(ViewSetMix ...
- DRF认证、自定义认证和权限、自定义权限
源码分析 """ 1)APIView的dispath(self, request, *args, **kwargs) 2)dispath方法内 self.initial( ...
随机推荐
- 拦截并记录数据库操作-Logging and Intercepting Database Operations
原文:http://msdn.microsoft.com/zh-cn/data/dn469464 Logging and Intercepting Database Operations Starti ...
- 暴力攻击 PHP 脚本 初探
考虑下面的HTML表单: CODE: <form action="http://example.org/login.php" method="POST"& ...
- EF CodeFirst Mirgration
新建类库Models,加入以下三个类: Product: public class Product { /// <summary> /// 编号 /// </summary> ...
- PMP备考指南之第二章:项目运作环境
本文已同步至 GitHub/Gitee/公众号,感兴趣的同学帮忙点波关注~ 第二章:项目运作环境 1. 事业环境因素.组织过程资产 事业环境因素 Enterprise Environmental Fa ...
- Linux命令-用户、用户组、权限
参考资料: http://www.linuxidc.com/Linux/2014-07/104445.htm Linux入门教程:如何手动创建一个Linux用户 http://www.linux ...
- MySQL查询数据表的Auto_Increment(自增id)
1.一般数据表的id都是设置成auto_increment的,所以当插入一条记录后,可以使用下面的命令来获取最新插入记录的id值 select last_insert_id(); 注意:1. 必须是在 ...
- C#的OpenFileDialog的简单用法
1.OpenFileDialog 中文名字叫做 打开文件对话框 OpenFileDialog的效果如图: private void btnSelectFile_Click(object sender, ...
- jenkins-node-pipeline
Jenkins node创建 1.jenkins搭建参考我的另外一篇文章: http://www.cnblogs.com/cuishuai/p/7544775.html 2.搭建完成后登录,选择 ...
- spark报错处理
Spark报错处理 1.问题:org.apache.spark.SparkException: Exception thrown in awaitResult 分析:出现这个情况的原因是spark启动 ...
- elasticsearch的join查询
1.概述 官方文档 https://www.elastic.co/guide/en/elasticsearch/reference/current/joining-queries.html 两种类型的 ...