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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容