前言
前一章,我們已經(jīng)說明了django 是如何從 django 框架處理,走到 rest_framework 的處理的,這一章就要看一下,走到 rest_framework 框架后,調(diào)用的 dispatch 函數(shù),到底做了什么東西,這里要揭曉了。
APIView
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 = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
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
dispatch 函數(shù)中,先是將 request 對象更換為 rest_framework中的 Request 對象,又做了一個initial初始化操作,然后從 request 的 method 方法,來查找對應(yīng)的處理函數(shù),最后再返回 reponse。這里我們有兩個注意點(diǎn),一個是我們都有哪些方法,這些方法是怎么賦值的?這個問題,我們將跟 Router 那一章最后的 method map 問題,一起探討明白;二是我們調(diào)用這個方法,又走到了哪些流程,我們將在第六章、method 講解清楚后,繼續(xù)我們這個流程的分析。
http 方法所對應(yīng)的函數(shù)處理
如果你去第六章看了 method 的詳解,那么你應(yīng)該清楚了,默認(rèn)情況下,http 方法所對應(yīng)的函數(shù)處理是固定的,某個 url,比如get 方法,對應(yīng)了 list 函數(shù),post 方法,對應(yīng)了create 函數(shù)。我們看一下 list 函數(shù)以及 create 函數(shù)都做了什么。
我們在 views.py 與 viewset.py 中,去找 list 函數(shù),create 函數(shù),但是這里貌似并未提供這些函數(shù),沒辦法,我只能繼續(xù),找例子中,我用的是哪些類
class UserViewSet(ModelViewSet):
好,那我們?nèi)フ?ModelViewSet
在 viewset解讀處