Django Middleware
這里說(shuō)的是 Django 1.8.7 的中間件
官方文檔在這里 Middleware | Django documentation | Django
Django——中間件詳解 - 聽(tīng)風(fēng)。 - 博客園
Django中間件 - 讓我們忘了那片海 - 博客園
PS 上面的說(shuō)明經(jīng)常提到視圖 這個(gè)翻譯太糟糕了
process_view 指的就是所請(qǐng)求的方法
在官方文檔中是這么說(shuō)的
process_view(request, view_func, view_args, view_kwargs)
request is an HttpRequest object. view_func is the Python function that Django is about to use. (It’s the actual function object, not the name of the function as a string.) view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view. Neither view_args nor view_kwargs include the first view argument (request).
process_view()
is called just before Django calls the view.
It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won’t bother calling the appropriate view; it’ll apply response middleware to that HttpResponse and return the result.
關(guān)于 return
雖然官方文檔在process_request 中說(shuō)
If it returns an HttpResponse object, Django won’t bother calling any other request, view or exception middleware, or the appropriate view; it’ll apply response middleware to that HttpResponse, and return the result.
但是我的實(shí)驗(yàn)結(jié)果并不一樣 可能是有什么錯(cuò)誤?
如果中間件的注冊(cè)順序是 M1 M2 M3
在 M1 的 request 中 return 了 HTTPResponse
M2 M3 的 request view 都不會(huì)執(zhí)行 直接到了 response 階段 逐步向上返回 response (也就是說(shuō)在 M1 之后的中間件受影響)
在 M1 的 view 中 return 了 HTTPResponse
M2 M3的 request會(huì)執(zhí)行 view不會(huì)執(zhí)行 response 都執(zhí)行
response 一直都會(huì)執(zhí)行的
Unlike the process_request() and process_view() methods, the process_response() method is always called, even if the process_request() and process_view() methods of the same middleware class were skipped (because an earlier middleware method returned an HttpResponse)
PS 關(guān)于 django 驗(yàn)證 csrf 的合法性
django 是拿POST 請(qǐng)求體中的 csrf 值和 cookie 中的 csrf 值做比較
在 middleware 的 csrf.py中有這么一段
if not _compare_salted_tokens(request_csrf_token, csrf_token):
csrf_token 是cookie 中的 token request_csrf_token 是請(qǐng)求體中的 token