2018-01-13 Flask上下文

Reason:
The main reason for the application’s context existence is that in the past a bunch of functionality was attached to the request context for lack of a better solution. Since one of the pillars of Flask’s design is that you can have more than one application in the same Python process.

So how does the code find the “right” application? In the past we recommended passing applications around explicitly, but that caused issues with libraries that were not designed with that in mind.

A common workaround for that problem was to use the current_app proxy later on, which was bound to the current request’s application reference. Since creating such a request context is an unnecessarily expensive operation in case there is no request around, the application context was introduced.

What happens if an error occurs in Flask during request processing?

  1. Before each request, before_request() functions are executed. If one of these functions return a response, the other functions are no longer called. In any case however the return value is treated as a replacement for the view's return value.
  2. If the before_request() did not return a response, the regular request handling kicks in and the view function that was matched has the chance to return a response.
  3. The return value of the view is then converted into an actual response object and handed over to the after_request() functions which has the chance to return a response.
  4. At the end of the request the teardown_request() functions are executed.
    This always happens, even in case of an unhandled exception down the road or if a before-request handler was not executed yet or at all(for example in test environments sometimes you might want to not execute before-request callbacks.)

上下文原理


image.png

The introduction of class RequestContext

image.png

flask._request_ctx_stack

image.png

partial 的應用

from functools import partial

def f1(a,b):
    print(a+b)

# f1(1,2)
new_func = partial(f1,12)    ######partial 對函數f1進行一次封裝 12是第一個參數
new_func(2)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。