问题描述
是否可以在对特定 blueprint
的首次请求之前运行功能?
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'
推荐答案
该蓝图等效项称为 @ Blueprint.before_app_first_request
:
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.
对于要由您的蓝图处理的第一个请求,没有钩子来运行代码.您可以使用 @ Blueprint.before_request
处理程序进行模拟a>测试它是否已经运行:
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
这模仿了Flask在这里所做的事情;需要锁定,因为单独的线程可以争先获得职位.
This mimics what Flask does here; locking is needed as separate threads could race to the post to be first.
这篇关于蓝图初始化,我可以在第一次请求蓝图之前运行一个函数吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!