出现的原因
基于django实现的APi很多功能都是自己开发,这时候djangorestframework就给我们提供了方便,直接基于它来返回数据,总之原理一样的,就是给一个接口也就是url,让前端的人请求url获取数据,在页面上显示出来,这样也达到前后端分离的效果。
认证
应用:主要用token验证 url中as_view里面调用dispatch方法
局部使用
全局使用
- settings
#注册认证类
REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': None,
'UNAUTHENTICATED_TOKEN': None, #将匿名用户设置为None
"DEFAULT_AUTHENTICATION_CLASSES": [
"app01.utils.MyAuthentication",
],
}
- 全局验证
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException
from app02 import models
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token=request.query_params.get('token')
print(token)
obj=models.UserInfo.objects.filter(token=token).first()
print(obj)
if obj:
return (obj.username,obj)
raise APIException('没有通过验证')
全局验证
权限
1,需求:Host是匿名用户和用户都能访问#匿名用户的request.user=none;User只有注册用户能访问
- urls.py
from app03 import views
from django.conf.urls import url
urlpatterns = [
# django rest framework
url('^auth/', views.AuthView.as_view()),
url(r'^hosts/', views.HostView.as_view()),
url(r'^users/', views.UsersView.as_view()),
url(r'^salary/', views.SalaryView.as_view()),
]
urls.py
- 认证和权限配合使用
class SalaryView(APIView):
'''用户能访问'''
message ='无权访问'
authentication_classes = [MyAuthentication,] #验证是不是用户
permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限
def get(self,request):
return Response('薪资列表')
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(detail='无权访问')
raise exceptions.PermissionDenied(detail=message)
- views
from django.shortcuts import render
from rest_framework.views import APIView #继承的view
from rest_framework.response import Response #友好的返回
from rest_framework.authentication import BaseAuthentication #认证的类
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import BasePermission
from app01 import models
from rest_framework import exceptions
from rest_framework.permissions import AllowAny #权限在这个类里面
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle
# Create your views here.
# +++++++++++++++认证类和权限类========================
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request.query_params.get('token')
obj = models.UserInfo.objects.filter(token=token).first()
if obj : #如果认证成功,返回用户名和auth
return (obj.username,obj)
return None #如果没有认证成功就不处理,进行下一步
def authenticate_header(self, request):
pass
class MyPermission(BasePermission):
message = '无权访问'
def has_permission(self,request,view): #has_permission里面的self是view视图对象
if request.user:
return True #如果不是匿名用户就说明有权限
return False #否则无权限
class AdminPermission(BasePermission):
message = '无权访问'
def has_permission(self, request, view): # has_permission里面的self是view视图对象
if request.user=='haiyun':
return True # 返回True表示有权限
return False #返回False表示无权限
# +++++++++++++++++++++++++++
class AuthView(APIView):
authentication_classes = [] #认证页面不需要认证
def get(self,request):
self.dispatch
return '认证列表'
class HostView(APIView):
'''需求:
Host是匿名用户和用户都能访问 #匿名用户的request.user = none
User只有注册用户能访问
'''
authentication_classes = [MyAuthentication,]
permission_classes = [] #都能访问就没必要设置权限了
def get(self,request):
print(request.user)
print(request.auth)
print(111111)
return Response('主机列表')
class UsersView(APIView):
'''用户能访问,request.user里面有值'''
authentication_classes = [MyAuthentication,]
permission_classes = [MyPermission,AdminPermission]
def get(self,request):
print(request.user,'111111111')
return Response('用户列表')
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(detail='无权访问22222')
raise exceptions.PermissionDenied(detail=message)
class SalaryView(APIView):
'''用户能访问'''
message ='无权访问'
authentication_classes = [MyAuthentication,] #验证是不是用户
permission_classes = [MyPermission,AdminPermission,] #再看用户有没有权限,如果有权限在判断有没有管理员的权限
def get(self,request):
return Response('薪资列表')
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(detail='无权访问')
raise exceptions.PermissionDenied(detail=message)
限流
1为什么限流呢?
第一点:爬虫反爬
第二点:控制api访问次数
登录用户的用户名可以做标识
匿名用户可以参考ip,但是ip可以加代理
总结
认证:就是检查用户是否存在;如果存在返回(request.user,request.auth);不存在request.user/request.auth=NONE
权限:进行职责划分
限制访问频率
认证
- 类: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',
}
}
网友评论