Restframework
- DjangoRestframework 主要使用 APIView 类,其 APIView 实质是对 View 进行继承加工了更多功能
- 请求进来 APIView() 首先执行 self.dispatch() 方法,此方法对 原有 request 进行了再次封装
一、 基于 FBV 视图函数
* 全站使用 csrf 认证
'django.middleware.csrf.CsrfViewMiddleware', # 全站使用csrf认证
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # 该函数无需认证
def users(request):
user_list = ['alex','oldboy']
return HttpResponse(json.dumps((user_list)))
* 全站不使用 csrf 认证
#'django.middleware.csrf.CsrfViewMiddleware', # 全站不使用csrf认证
from django.views.decorators.csrf import csrf_exempt
@csrf_protect # 该函数需认证
def users(request):
user_list = ['alex','oldboy']
return HttpResponse(json.dumps((user_list)))
二、基于 CBV 的视图函数
CBV csrf 时需要使用
- @method_decorator(csrf_exempt)
- 在dispatch()方法中(单独方法无效)
方式一:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
class StudentsView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(StudentsView,self).dispatch(request, *args, **kwargs)
方式二:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt,name='dispatch')
class StudentsView(View):
def get(self,request,*args,**kwargs):
print('get方法')
return HttpResponse('GET')
一、认证(有些API需要用户登录成功之后才能访问;有些无需登录就能访问)
* 内置认证类
1. 认证类,必须继承:from rest_framework.authentication import BaseAuthentication
2. 其他认证类:BasicAuthentication
* 使用:
继承 BaseAuthentication; 必须实现:authenticate()和 authenticate_header()方法
- 创建类:继承 BaseAuthentication;
from rest_framework.authentication import BaseAuthentication
class Authtication(BaseAuthentication):
def authenticate(self,request):
token = request._request.GET.get('token')
token_obj = models.UserToken.objects.filter(token=token).first()
if not token_obj:
raise exceptions.AuthenticationFailed('用户认证失败')
return (token_obj.user, token_obj)
def authenticate_header(self, request):
return 'Basic realm="api"'
- 返回值:
- None,我不管了,下一认证来执行。
- raise exceptions.AuthenticationFailed('用户认证失败') # from rest_framework import exceptions
- (元素1,元素2) # 元素1赋值给request.user; 元素2赋值给request.auth
- 局部使用
class UserInfoView(APIView):
""" 订单相关业务 """
authentication_classes = [自定义认证类1,自定义认证类2]
def get(self,request,*args,**kwargs):
print(request.user)
return HttpResponse('用户信息')
- 全局使用:
REST_FRAMEWORK = {
# 全局使用的认证类
"DEFAULT_AUTHENTICATION_CLASSES":[
'api.utils.auth.自定义认证类1', 'api.utils.auth.自定义认证类2',],
# "UNAUTHENTICATED_USER":lambda :"匿名用户",
"UNAUTHENTICATED_USER":None, # 匿名,request.user = None
"UNAUTHENTICATED_TOKEN":None, # 匿名,request.auth = None
}
案例:
auth.py
class Authtication(BaseAuthentication):
def authenticate(self,request):
token = request._request.GET.get('token')
token_obj