Django Restful Framework (DRF)中类的调用与自定义-- 以 autentication 认证为例

DRF 的 request 对 django 的 request 进行了更一步的封装; 通过获取认证相关的所有类,并实例化,传入request对象(user,auth)

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from goods.serializers import GoodsSerializer
from rest_framework.exceptions import APIException
# Create your views here.
from goods.models import Goods class MyAuthentication(object):
def authenticate(self,request):
token = request.query_params.get('token')
if token == 'abc':
return ('aaa','bbb')
raise APIException('认证失败') class GoodsListView(APIView):
authentication_classes = [MyAuthentication,]
def get(self,request,*args,**kwargs):
print(request.user,request.auth)
goods = Goods.objects.all()
goods_serializer = GoodsSerializer(goods,many=True)
return Response(goods_serializer.data)

Django -- DRF 认证流程-LMLPHP

Django -- DRF 认证流程-LMLPHP

Django -- DRF 认证流程-LMLPHP

Django -- DRF 认证流程-LMLPHP

Django -- DRF 认证流程-LMLPHP

Django -- DRF 认证流程-LMLPHP

Django -- DRF 认证流程-LMLPHP

登录时不需要 认证,登录之后的访问都需要 进行 登录用户身份的确认。

可以全局添加认证,然后把登录,或者主页等不需要 登录的视图,设置为 authentication_classes= []
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES":[],
# "UNAUTHENTICATED_USER":lambda :'匿名用户',
"UNAUTHENTICATED_USER":None,
# "UNAUTHENTICATED_TOKEN":lambda :'没有验证信息',
"UNAUTHENTICATED_TOKEN":None, }
    def authenticate_header(self, request):
return 'Basic realm="%s"' % 'api

Django -- DRF 认证流程-LMLPHP

05-22 00:48