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?
- 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.
- 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.
- 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.
- 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.)
上下文原理
The introduction of class RequestContext
flask._request_ctx_stack
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)