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.)

上下文原理


2018-01-13 Flask上下文_第1张图片
image.png

The introduction of class RequestContext

2018-01-13 Flask上下文_第2张图片
image.png

flask._request_ctx_stack

2018-01-13 Flask上下文_第3张图片
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)

你可能感兴趣的:(2018-01-13 Flask上下文)