django-权限验证场景

1.需要登录才能够访问的验证

from django.contrib.auth.decorators import login_required  # 登录装饰器
# method_decorator 使装饰器装饰在类上面(装饰器的类装饰器?)  login_required 登陆验证,失败跳转
# despatch 类里面有多个方法(get,post).将这些方法都装饰在despatch中,(通过despatch方法确定出get or post 再由login_required装饰)。
@method_decorator(login_required(login_url='/account/login/'), name='dispatch')
class Secret(View):
  def get(self, request):
    return render(request, 'a.html')

2.需要是员工is_staff为1才能访问

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required(login_url='/')  # 不是公司员工则跳转到该路由
class Secret(View):
  def get(self, request):
    return render(request, 'a.html')

3.需要通过验证

def xfz_auth_required(func):
def wrapper(request, *args, **kwargs):
if request.user.is_authenticated: # is_authenticated 是通过login方法登录才有的一个判断方法 。 更详细 https://www.cnblogs.com/tangpg/p/9074418.html       return func(request, *args, **kwargs)
else:
if request.is_ajax():
return restful.params_error(message="请登陆")
return redirect('/account/login')
return wrapper

4.使用django自带的权限管理                            BaseCommand详见:http://www.cnblogs.com/tangpg/p/9428980.html

from django.http import Http404

def xfz_permission_required(model):
''' 该model的所有权都具备才可以验证通过 '''
def decorator(viewfunc):
@wraps(viewfunc)
def _wrapper(request, *args, **kwargs):
content_type = ContentType.objects.get_for_model(model)
permissions = Permission.objects.filter(content_type=content_type)
# has_perms:只能采用字符串的形式判断
# 字符串的形式为:app_label.codename
codenames = [content_type.app_label+'.'+permission.codename for permission in permissions]
print(codenames) # ['course.add_course', 'course.change_course', 'course.delete_course']
# result = 0
# for codename in codenames:
# if request.user.has_perm(codename):
# result+=1
# print(result) ## it's has_perms!!! not has_perm!!!
result = request.user.has_perms(codenames)
if result:
return viewfunc(request, *args, **kwargs)
else:
raise Http404
return _wrapper
return decorator

5.判断是否为superuser

def xfz_superuser_required(viewfunc):
@wraps(viewfunc)
def wrapper(requset, *args, **kwargs):
if requset.user.is_superuser:
return viewfunc(requset, *args, **kwargs)
else:
raise Http404
return wrapper
上一篇:与众不同 windows phone (36) - 8.0 新的瓷贴: FlipTile, CycleTile, IconicTile


下一篇:强制重启N种方法