Python 学习笔记(十五)--Django REST Framework之Request
第一步部分Request
1.引入方式
from rest_framework.request import Request
2.类的属性和方法
3. 查看下初始方法
""" Wrapper allowing to enhance a standard `HttpRequest` instance. Kwargs: - request(HttpRequest). The original request instance. - parsers(list/tuple). The parsers to use for parsing the request content. - authenticators(list/tuple). The authenticators used to try authenticating the request's user. """ def __init__(self, request, parsers=None, authenticators=None, negotiator=None, parser_context=None): assert isinstance(request, HttpRequest), ( 'The `request` argument must be an instance of ' '`django.http.HttpRequest`, not `{}.{}`.' .format(request.__class__.__module__, request.__class__.__name__) ) ## 二次封装request,将原生request作为drf request对象的_request属性。 self._request = request self.parsers = parsers or () self.authenticators = authenticators or () self.negotiator = negotiator or self._default_negotiator() self.parser_context = parser_context self._data = Empty self._files = Empty self._full_data = Empty self._content_type = Empty self._stream = Empty if self.parser_context is None: self.parser_context = {} self.parser_context['request'] = self self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET force_user = getattr(request, '_force_auth_user', None) force_token = getattr(request, '_force_auth_token', None) if force_user is not None or force_token is not None: forced_auth = ForcedAuthentication(force_user, force_token) self.authenticators = (forced_auth,)
只要继承了APIView,视图类中的request对象,都是经过二次封装的新request对象了,而老的request对象对应的是新request._request。
4. 获取属性方法
def __getattr__(self, attr): """ If an attribute does not exist on this instance, then we also attempt to proxy it to the underlying HttpRequest object. """ try: return getattr(self._request, attr) ##通过类对象的反射获取属性和方法。保证了使用新request的方式和老的一样。 except AttributeError: return self.__getattribute__(attr)
5.request对象data方法(需要特别注意:data其实是个方法,可不是属性)
@property def data(self): if not _hasattr(self, '_full_data'): self._load_data_and_files() return self._full_data ##是一个字典,post请求不管使用什么编码,传过来的数据,都在request.data里;get请求过来的数据,有两种获取方式:
## 一是通过request.get获取;还有一种方式query_params()获取
在初始化时,作了声明
self._data = Empty
还需要注意的时,Empty是一个类
class Empty: """ Placeholder for unset attributes. Cannot use `None`, as that may be a valid value. """ pass
在此补充下,前面提到的query_params的定义
@property def query_params(self): ##用于获取get请求,地址中的参数 """ More semantically correct name for request.GET. """ return self._request.GET
第二部分 dispatch 中的initial
方法所处的位置,请参照《Python 学习笔记(十四)--Django REST Framework中ViewSets 与APIView》的介绍
可按照以下关键字在上文中搜素。
###三大认证模块 self.initial(request, *args, **kwargs)
方法的定义
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) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted
##认证组件:检验用户--游客、合法用户、非法用户
##游客:代表校验通过,直接进入下一步校验(权限校验)
##合法用户:代表校验通过,用户存储在request.user中,再进行下一步校验(权限校验)
##非法用户:代表校验失败,抛出异常,返回403权限异常结果。 self.perform_authentication(request)
##权限组件:校验用户权限--必须登录、所有用户、登入只读游客自读、自定义用户角色
##认证通过,可以进入下一步校验(频率认证)
##认证失败,报错异常,返回403权限异常结果 self.check_permissions(request)
##频率组件:限制视图接口被访问的频率次数--限制条件(IP、id、、唯一键)、频率周期时间(s、m、h)、频率次数(3/s)
##没有达到限制次数:正常访问接口
##达到限制次数:限制时间内不能访问,限制时间到达后,可以重新访问。 self.check_throttles(request)