restful规范:
根据method不同做不同的操作
method:
get
post
delete
put
www.cmdb.com/api/v1/asset?page=2&per_page=100
rest_framework进行认证
from django.shortcuts import render,HttpResponse # Create your views here. from rest_framework.views import APIView from rest_framework import exceptions import json class MyAuthentication(object): def authenticate(self,request): token = request._request.GET.get('token') if not token: raise exceptions.AuthenticationFailed('用户认证失败') return("sb",None) def authenticate_header(self,val): pass class Asset(APIView): authentication_classes = [MyAuthentication,] def get(self,request,*args,**kwargs): self.dispatch print(request.user) ret = { "code":200, "msg":"认证成功" } return HttpResponse(json.dumps(ret))
认证framework源码流程图
全局配置,局部配置
- 全局配置(settings,py中配置) 列表里面是认证类的路径
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASS":['api.utils,auth.FirstAuthtication','api.utils'] }
- 局部配置(每个需要认证的类中加上静态字段)
authentication_classes = []
- 匿名用户
自己写认证类的时候,必须继承BaseAuthentication
from rest_framework.authentication import BaseAuthentication
类中其实就两方法
- authenticate
三种返回值
- None 下一认证来执行
- raise exceptions.AuthenticationFailed()
- (元素1,元素2) request.user request.auth
- authenticate_header
认证源码流程:
dispatch
封装request
获取自定义的认证类,列表生成式创建对象
inital
perform_authenticate
request.user 循环认证对象