认证
# 自定义.Authtication
class MyAuthtication(BaseAuthentication):
def authenticate(self, request):
# 此处最好根据请求方法,动态获取方法里的Token
token = request._request.Get.get('token')
token_obj = UserToken.objects.filter(token=token).first()
if not token_obj:
raise AuthenticationFailed("认证失败")
return token_obj.user, token_obj.token
# views.py
class AuthView(APIView):
authentication_classes = [MyAuthtication]
def post(self, request, *arg, **kwarg):
ret = {'state_code':1000, 'msg':None}
try:
user = request._request.POST.get("username")
pwd = request._request.POST.get("pwd")
obj = UserInfo.objects.filter(username=user, password= pwd)
if not obj:
ret = {'state_code':1001, 'msg':'用户名或密码错误'}
else:
token = 'xxxxxxx'# token
UserToken.object.update_or_create(user=obj, defaults = {"token":token})
except Exception as e:
ret = {'state_code':1002, 'msg':'请求异常'}
return JsonResponse(ret)
权限
视图做权限
class OrderView(APIVIew):
authentication_classes = [MyAuthtication] # 认证已登录
def get(self, request, *arg, **args):
ret = {"state_code":1001, "msg":"数据请求成功","data":ORDER_DICT}
if request.user.user_type != '3'
ret = {"state_code":1001, "msg":"无权查看","data":[]}
return Response(status = 200,data=ret)
中间件做权限
class MiddlewareMixin(object):
"""
__call__ 方法会先调用 self.process_request(request),
接着执行self.get_response(request) ,
然后调用 self.process_response(request, response)
"""
def __init__(self, get_response=None):
self.get_response = get_response
super(MiddlewareMixin, self).__init__()
def __call__(self, request):
response = None
if hasattr(self, 'process_request'):
response = self.process_request(request)
if not response:
response = self.get_response(request)
if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response
class RbacMiddleware(MiddlewareMixin):
"""
自定义的中间件必须继承自MiddlewareMixin,代码如上
"""
def process_request(self, request):
return None
def process_response(self, request, response):
return response
DRF做权限
# permissions
from rest_framework.permissions import BasePermission
class MyPermission(object):
message = "兄弟,又到了需要充钱的时候!好开心啊!" # 自定义 消息返回
def has_permission(self, request, view):
if request.user.user_type != '3':
return False
return True
# permissions
class OrderView(APIVIew):
authentication_classes = [MyAuthtication] # 认证已登录
def get(self, request, *arg, **args):
ret = {"state_code":1001, "msg":"数据请求成功","data":ORDER_DICT}
if request.user.user_type != '3'
ret = {"state_code":1001, "msg":"无权查看","data":[]}
return Response(status = 200,data=ret)
限流