点击查看代码
源码解析:
# 请求函数内的request,*args, **kwargs传给父类APIView内的dispatch()函数
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
# request,*args, **kwargs传给self.initialize_request(request, *args, **kwargs)进行封装
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
def initialize_request(self, request, *args, **kwargs):
parser_context = self.get_parser_context(request)
# 将request传给类Request()
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
点击查看代码
class Request:
def __init__(self, request, parsers=None, authenticators=None,
negotiator=None, parser_context=None):
assert isinstance(request, HttpRequest), (
.format(request.__class__.__module__, request.__class__.__name__)
)
# 原装的request封装为self._request
self._request = request
点击查看代码
# __getattr__当调用的对象的属性不存在时触发
# __getattribute__无论调用对象的属性是否存在,都会执行该函数
class HttpRequest(object):
def __init__(self):
pass
def f1(self):
print('f1')
def f2(self):
print('f2')
class Request(object):
def __init__(self, req, m):
self._request = req # 此处见源码解析
self.m = m
print(self.args)
print(self.kwargs)
def __getattr__(self, item): # 2.Request中不存在f1, 执行__getattr__
try: # 3.如果HttpRequest中存在f1,继续执行
return getattr(self._request, item)
except AttributeError:
return self.__getattribute__(item)
# 3.如果HttpRequest中不存在f1,继续在Request中寻找f1,没有则报错
httprequest = HttpRequest()
httprequest.f1()
httprequest.f2()
# 将实例化对象httprequest以参数形式传给Request()
request = Request(httprequest, 123)
request._request.f1() # 此处见源码解析
request.f1() # 1. 函数开始执行
点击查看代码
结果:
f1
f2
f1
f1