Blueprint initialization, can I run a function before first request to blueprint

和自甴很熟 提交于 2019-12-06 23:23:59

问题


Is it possible to run a function before the first request to a specific blueprint?

@my_blueprint.before_first_request
def init_my_blueprint():
    print 'yes'

Currently this will yield the following error:

AttributeError: 'Blueprint' object has no attribute 'before_first_request'

回答1:


The Blueprint equivalent is called @Blueprint.before_app_first_request:

@my_blueprint.before_app_first_request
def init_my_blueprint():
    print('yes')

The name reflects that it is called before any request, not just a request specific to this blueprint.

There is no hook for running code for just the first request to be handled by your blueprint. You can simulate that with a @Blueprint.before_request handler that tests if it has been run yet:

from threading import Lock

my_blueprint._before_request_lock = Lock()
my_blueprint._got_first_request = False

@my_blueprint.before_request
def init_my_blueprint():
    if my_blueprint._got_first_request:
        return
    with my_blueprint._before_request_lock:
        if my_blueprint._got_first_request:
            return

        # first request, execute what you need.
        print('yes')

        # mark first request handled *last*
        my_blueprint._got_first_request = True

This mimics what Flask does here; locking is needed as separate threads could race to the post to be first.



来源:https://stackoverflow.com/questions/27386038/blueprint-initialization-can-i-run-a-function-before-first-request-to-blueprint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!