Django-Rest-Framework源码流程
一
请求到来之后,都要先执行dispatch方法,dispatch方法方法根据请求方式的不同触发get/post/put/delete等方法
注意:APIView中的dispatch方法有很多功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
def dispatch(self, request, *args, **kwargs): """ `.dispatch()` is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. """ self.args = args self.kwargs = kwargs 第一步:对request进行加工(添加数据) request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers
|
二
上面是大致步骤,下面我们来具体分析一下,看每个步骤中都具体干了什么事
对request进行加工(添加数据)
我们看看request里面都添加了那些数据
a
首先 request = self.initialize_request(request, *args, **kwargs)
点进去,会发现:在Request里面多加了四个,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """
|
b
获取认证相关的类的具体
authenticators=self.get_authenticators()
1 2 3 4 5 6
|
def get_authenticators(self): """ Instantiates and returns the list of authenticators that this view can use. """
|
c
查看认证的类:self.authentication_classes
1
|
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
|
d
接着走进api_settings
1
|
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
|
e
导入了类看看类里面具体干了什么
1 2
|
from rest_framework.authentication import SessionAuthentication from rest_framework.authentication import BaseAuthentication
|
f
看到里面有个authenticate方法和authenticate_header方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class BaseAuthentication(object): """ All authentication classes should extend BaseAuthentication. """
def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ raise NotImplementedError(".authenticate() must be overridden.")
def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ pass
|
具体处理认证,从headers里面能获取用户名和密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
class BasicAuthentication(BaseAuthentication): """ HTTP Basic authentication against username/password. """ www_authenticate_realm = 'api'
def authenticate(self, request): """ Returns a `User` if a correct username and password have been supplied using HTTP Basic authentication. Otherwise returns `None`. """ auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'basic': return None
|
g
当然restfulframework默认定义了两个类。我们也可以自定制类,
自己有就用自己的了,自己没有就去找父类的了,
但是里面必须实现authenticate方法,不然会报错。
进行以下操作
- 处理版权信息
- 认证
- 权限
- 请求用户进行访问频率的限制
我们主要来看一下认证流程:
a
首先 self.initial(request, *args, **kwargs)可以看到做了以下操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs)
|
b
我们先来看认证,self.perform_authentication(request)
具体干了什么,按住ctrl点击进去
1 2 3 4 5 6 7 8 9
|
def perform_authentication(self, request): """ Perform authentication on the incoming request.
Note that if you override this and simply 'pass', then authentication will instead be performed lazily, the first time either `request.user` or `request.auth` is accessed. """ request.user
|
c
那么我们可以从视图里面导入一下Request,找到request对象的user方法
1
|
from rest_framework.views import Request
|
1 2 3 4 5 6 7 8 9 10
|
@property def user(self): """ Returns the user associated with the current request, as authenticated by the authentication classes provided to the request. """ if not hasattr(self, '_user'): with wrap_attributeerrors(): self._authenticate()
|
d
执行self._authenticate() 开始用户认证,
如果验证成功后返回元组: (用户,用户Token)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
def _authenticate(self): """ Attempt to authenticate the request using each authentication instance in turn. """
|
e
在user_auth_tuple = authenticator.authenticate(self) 进行验证,
如果验证成功,执行类里的authenticatie方法
f
如果用户没有认证成功:self._not_authenticated()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
def _not_authenticated(self): """ Set authenticator, user & authtoken representing an unauthenticated request.
Defaults are None, AnonymousUser & None. """
|
执行get/post/delete等方法
对返回结果在进行加工