!!token参考:RESTful API---认证代码,自定义认证
一、认证(补充的一个点)
认证请求头

1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from rest_framework.views import APIView 4 from rest_framework.response import Response 5 from rest_framework.authentication import BaseAuthentication 6 from rest_framework.permissions import BasePermission 7 8 from rest_framework.request import Request 9 from rest_framework import exceptions 10 11 token_list = [ 12 'sfsfss123kuf3j123', 13 'asijnfowerkkf9812', 14 ] 15 16 17 class TestAuthentication(BaseAuthentication): 18 def authenticate(self, request): 19 """ 20 用户认证,如果验证成功后返回元组: (用户,用户Token) 21 :param request: 22 :return: 23 None,表示跳过该验证; 24 如果跳过了所有认证,默认用户和Token和使用配置文件进行设置 25 self._authenticator = None 26 if api_settings.UNAUTHENTICATED_USER: 27 self.user = api_settings.UNAUTHENTICATED_USER() # 默认值为:匿名用户 28 else: 29 self.user = None 30 31 if api_settings.UNAUTHENTICATED_TOKEN: 32 self.auth = api_settings.UNAUTHENTICATED_TOKEN()# 默认值为:None 33 else: 34 self.auth = None 35 (user,token)表示验证通过并设置用户名和Token; 36 AuthenticationFailed异常 37 """ 38 val = request.query_params.get('token') 39 if val not in token_list: 40 raise exceptions.AuthenticationFailed("用户认证失败") 41 42 return ('登录用户', '用户token') 43 44 def authenticate_header(self, request): 45 """ 46 Return a string to be used as the value of the `WWW-Authenticate` 47 header in a `401 Unauthenticated` response, or `None` if the 48 authentication scheme should return `403 Permission Denied` responses. 49 """ 50 pass 51 52 53 class TestPermission(BasePermission): 54 message = "权限验证失败" 55 56 def has_permission(self, request, view): 57 """ 58 判断是否有权限访问当前请求 59 Return `True` if permission is granted, `False` otherwise. 60 :param request: 61 :param view: 62 :return: True有权限;False无权限 63 """ 64 if request.user == "管理员": 65 return True 66 67 # GenericAPIView中get_object时调用 68 def has_object_permission(self, request, view, obj): 69 """ 70 视图继承GenericAPIView,并在其中使用get_object时获取对象时,触发单独对象权限验证 71 Return `True` if permission is granted, `False` otherwise. 72 :param request: 73 :param view: 74 :param obj: 75 :return: True有权限;False无权限 76 """ 77 if request.user == "管理员": 78 return True 79 80 81 class TestView(APIView): 82 # 认证的动作是由request.user触发 83 authentication_classes = [TestAuthentication, ] 84 85 # 权限 86 # 循环执行所有的权限 87 permission_classes = [TestPermission, ] 88 89 def get(self, request, *args, **kwargs): 90 # self.dispatch 91 print(request.user) 92 print(request.auth) 93 return Response('GET请求,响应内容') 94 95 def post(self, request, *args, **kwargs): 96 return Response('POST请求,响应内容') 97 98 def put(self, request, *args, **kwargs): 99 return Response('PUT请求,响应内容')

1 # 2 class MyAuthtication(BasicAuthentication): 3 def authenticate(self, request): 4 token = request.query_params.get('token') #注意是没有GET的,用query_params表示 5 if token == 'zxxzzxzc': 6 return ('uuuuuu','afsdsgdf') #返回user,auth 7 # raise AuthenticationFailed('认证错误') #只要抛出认证错误这样的异常就会去执行下面的函数 8 raise APIException('认证错误') 9 def authenticate_header(self, request): #认证不成功的时候执行 10 return 'Basic reala="api"' 11 12 class UserView(APIView): 13 authentication_classes = [MyAuthtication,] 14 def get(self,request,*args,**kwargs): 15 print(request.user) 16 print(request.auth) 17 return Response('用户列表')
二、权限
1、需求:Host是匿名用户和用户都能访问 #匿名用户的request.user = none;User只有注册用户能访问

1 from app03 import views 2 from django.conf.urls import url 3 urlpatterns = [ 4 # django rest framework 5 url('^auth/', views.AuthView.as_view()), 6 url(r'^hosts/', views.HostView.as_view()), 7 url(r'^users/', views.UsersView.as_view()), 8 url(r'^salary/', views.SalaryView.as_view()), 9 ]

1 class SalaryView(APIView): 2 '''用户能访问''' 3 message ='无权访问' 4 authentication_classes = [MyAuthentication,] #验证是不是用户 5 permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限 6 def get(self,request): 7 return Response('薪资列表') 8 9 def permission_denied(self, request, message=None): 10 """ 11 If request is not permitted, determine what kind of exception to raise. 12 """ 13 if request.authenticators and not request.successful_authenticator: 14 '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' 15 raise exceptions.NotAuthenticated(detail='无权访问') 16 raise exceptions.PermissionDenied(detail=message)

1 from django.shortcuts import render 2 from rest_framework.views import APIView #继承的view 3 from rest_framework.response import Response #友好的返回 4 from rest_framework.authentication import BaseAuthentication #认证的类 5 from rest_framework.authentication import BasicAuthentication 6 from rest_framework.permissions import BasePermission 7 from app01 import models 8 from rest_framework import exceptions 9 from rest_framework.permissions import AllowAny #权限在这个类里面 10 from rest_framework.throttling import BaseThrottle,SimpleRateThrottle 11 # Create your views here. 12 # +++++++++++++++认证类和权限类======================== 13 class MyAuthentication(BaseAuthentication): 14 def authenticate(self, request): 15 token = request.query_params.get('token') 16 obj = models.UserInfo.objects.filter(token=token).first() 17 if obj : #如果认证成功,返回用户名和auth 18 return (obj.username,obj) 19 return None #如果没有认证成功就不处理,进行下一步 20 21 def authenticate_header(self, request): 22 pass 23 24 class MyPermission(BasePermission): 25 message = '无权访问' 26 def has_permission(self,request,view): #has_permission里面的self是view视图对象 27 if request.user: 28 return True #如果不是匿名用户就说明有权限 29 return False #否则无权限 30 31 class AdminPermission(BasePermission): 32 message = '无权访问' 33 def has_permission(self, request, view): # has_permission里面的self是view视图对象 34 if request.user=='haiyun': 35 return True # 返回True表示有权限 36 return False #返回False表示无权限 37 38 # +++++++++++++++++++++++++++ 39 class AuthView(APIView): 40 authentication_classes = [] #认证页面不需要认证 41 42 def get(self,request): 43 self.dispatch 44 return '认证列表' 45 46 class HostView(APIView): 47 '''需求: 48 Host是匿名用户和用户都能访问 #匿名用户的request.user = none 49 User只有注册用户能访问 50 ''' 51 authentication_classes = [MyAuthentication,] 52 permission_classes = [] #都能访问就没必要设置权限了 53 def get(self,request): 54 print(request.user) 55 print(request.auth) 56 print(111111) 57 return Response('主机列表') 58 59 class UsersView(APIView): 60 '''用户能访问,request.user里面有值''' 61 authentication_classes = [MyAuthentication,] 62 permission_classes = [MyPermission,AdminPermission] 63 def get(self,request): 64 print(request.user,'111111111') 65 return Response('用户列表') 66 67 def permission_denied(self, request, message=None): 68 """ 69 If request is not permitted, determine what kind of exception to raise. 70 """ 71 if request.authenticators and not request.successful_authenticator: 72 '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' 73 raise exceptions.NotAuthenticated(detail='无权访问22222') 74 raise exceptions.PermissionDenied(detail=message) 75 76 77 class SalaryView(APIView): 78 '''用户能访问''' 79 message ='无权访问' 80 authentication_classes = [MyAuthentication,] #验证是不是用户 81 permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限 82 def get(self,request): 83 return Response('薪资列表') 84 85 def permission_denied(self, request, message=None): 86 """ 87 If request is not permitted, determine what kind of exception to raise. 88 """ 89 if request.authenticators and not request.successful_authenticator: 90 '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' 91 raise exceptions.NotAuthenticated(detail='无权访问') 92 raise exceptions.PermissionDenied(detail=message)
如果遇上这样的,还可以自定制,参考源码
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(): #循环每一个permission对象,调用has_permission #如果False,则抛出异常 #True 说明有权访问 if not permission.has_permission(request, self): self.permission_denied( request, message=getattr(permission, 'message', None) )
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: '''如果没有通过认证,并且权限中return False了,就会报下面的这个异常了''' raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied(detail=message)
那么我们可以重写permission_denied这个方法,如下:

2. 全局使用
上述操作中均是对单独视图进行特殊配置,如果想要对全局进行配置,则需要再配置文件中写入即可。


三、限流(限制一定时间内每个用户的访问次数,eg:限制每个用户每分钟访问上限为20次)
1、为什么要限流呢?
答:
- - 第一点:爬虫,反爬
- - 第二点:控制 API 访问次数
- - 登录用户的用户名可以做标识
- 匿名用户可以参考 ip,但是 ip可以加代理。.
只要你想爬,早晚有一天可以爬。
2、限制访问频率源码分析

1 self.check_throttles(request)

1 def check_throttles(self, request): 2 """ 3 Check if request should be throttled. 4 Raises an appropriate exception if the request is throttled. 5 """ 6 for throttle in self.get_throttles(): 7 #循环每一个throttle对象,执行allow_request方法 8 # allow_request: 9 #返回False,说明限制访问频率 10 #返回True,说明不限制,通行 11 if not throttle.allow_request(request, self): 12 self.throttled(request, throttle.wait()) 13 #throttle.wait()表示还要等多少秒就能访问了






下面来看看最简单的从源码中分析的示例,这只是举例说明了一下


3、需求:对匿名用户进行限制,每个用户一分钟允许访问10次(只针对用户来说)
a、基于用户IP限制访问频率
流程分析:
- 先获取用户信息,如果是匿名用户,获取IP。如果不是匿名用户就可以获取用户名。
- 获取匿名用户IP,在request里面获取,比如IP= 1.1.1.1。
- 吧获取到的IP添加到到recode字典里面,需要在添加之前先限制一下。
- 如果时间间隔大于60秒,说明时间久远了,就把那个时间给剔除 了pop。在timelist列表里面现在留的是有效的访问时间段。
- 然后判断他的访问次数超过了10次没有,如果超过了时间就return False。
- 美中不足的是时间是固定的,我们改变他为动态的:列表里面最开始进来的时间和当前的时间进行比较,看需要等多久。
具体实现:


b、用resetframework内部的限制访问频率(利于Django缓存)
源码分析:
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle #限制访问频率


请求一进来会先执行SimpleRateThrottle这个类的构造方法





代码实现:

记得在settings里面配置

4、对匿名用户进行限制,每个用户1分钟允许访问5次,对于登录的普通用户1分钟访问10次,VIP用户一分钟访问20次
- 比如首页可以匿名访问
- #先认证,只有认证了才知道是不是匿名的,
- #权限登录成功之后才能访问, ,index页面就不需要权限了
- If request.user #判断登录了没有


四、总结
1、认证:就是检查用户是否存在;如果存在返回(request.user,request.auth);不存在request.user/request.auth=None
2、权限:进行职责的划分
3、限制访问频率
认证 - 类:authenticate/authenticate_header ##验证不成功的时候执行的 - 返回值: - return None, - return (user,auth), - raise 异常 - 配置: - 视图: class IndexView(APIView): authentication_classes = [MyAuthentication,] - 全局: REST_FRAMEWORK = { 'UNAUTHENTICATED_USER': None, 'UNAUTHENTICATED_TOKEN': None, "DEFAULT_AUTHENTICATION_CLASSES": [ # "app02.utils.MyAuthentication", ], } 权限 - 类:has_permission/has_object_permission - 返回值: - True、#有权限 - False、#无权限 - exceptions.PermissionDenied(detail="错误信息") #异常自己随意,想抛就抛,错误信息自己指定 - 配置: - 视图: class IndexView(APIView): permission_classes = [MyPermission,] - 全局: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ # "app02.utils.MyAuthentication", ], } 限流 - 类:allow_request/wait PS: scope = "wdp_user" - 返回值:
return True、#不限制
return False #限制 - 配置: - 视图: class IndexView(APIView): throttle_classes=[AnonThrottle,UserThrottle,] def get(self,request,*args,**kwargs): self.dispatch return Response('访问首页') - 全局 REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":[ ], 'DEFAULT_THROTTLE_RATES':{ 'wdp_anon':'5/minute', 'wdp_user':'10/minute', } }
下一篇:解析、序列化
http://www.cnblogs.com/jiangshanduojiao/p/9070289.html
posted on 2018-05-16 11:20 myworldworld 阅读(455) 评论(0) 收藏 举报