from rest_framework.permissions import BasePermission
from apps.user.models import User,Role,UrlInfo
第一种方法#
class SylPermissions1(BasePermission):
message="当前用户没有权限1"
def has_permission(self, request, view):
uid=request.user.id
user_obj=User.objects.filter(id=uid).first()
user_role_obj=user_obj.roles.all()
#获取的方法(GET,POST,PUT,DELETE)
method=request.method
#获取的路由
url = request.path_info
#拼接
print(url+method)
#如果不用判断方法(GET,POST......)下面的if,else不用写
url_obj=UrlInfo.objects.filter(url=url+method).first()
if url_obj:
url_role_obj=url_obj.roles.all() #正向查询roles外键.all()
else:
return False
for i in user_role_obj:
if i in url_role_obj:
return True
return False
#第二种方法
class SylPermissions2(BasePermission):
message="当前用户没有权限2"
def has_permission(self, request, view):
uid=request.user.id
user_obj=User.objects.filter(id=uid).first()
user_role_obj=user_obj.roles.all()
method=request.method
url=request.path_info
m_urls=url+method
for i in user_role_obj:
role_obj=i.urlsinfo.all() #反向查询,url表里related_name="urlsinfo"
for j in role_obj:
if j.url == m_urls:
return True
return False