pyC*_*hon 9 flask flask-script
是否可以在第一次请求之前运行一个函数blueprint?
@my_blueprint.before_first_request
def init_my_blueprint():
print 'yes'
Run Code Online (Sandbox Code Playgroud)
目前,这将产生以下错误:
AttributeError: 'Blueprint' object has no attribute 'before_first_request'
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 11
蓝图等价物称为@Blueprint.before_app_first_request:
@my_blueprint.before_app_first_request
def init_my_blueprint():
print('yes')
Run Code Online (Sandbox Code Playgroud)
该名称反映了它在任何请求之前被调用,而不仅仅是特定于此蓝图的请求.
没有用于运行代码的钩子,只需要您的蓝图处理第一个请求.您可以使用一个@Blueprint.before_request处理程序来测试它是否已经运行:
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
Run Code Online (Sandbox Code Playgroud)
这模仿了Flask在这里做的事情; 需要锁定,因为单独的线程可能首先竞争到帖子.
| 归档时间: |
|
| 查看次数: |
3661 次 |
| 最近记录: |