本文介绍了烧瓶蓝色打印before_first_request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在第一次请求特定的蓝图之前运行一个函数?

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

目前这将产生以下错误:

pre $ AttributeError:'Blueprint'对象没有属性'before_first_request'


解决方案

Blueprint相当于:

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

该名称反映它在任何请求之前调用,而不仅仅是特定于此蓝图的请求。



对于仅仅运行代码没有任何钩子首先要求你的蓝图处理。您可以使用测试它是否已经运行:

  from线程导入锁定

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:
返回
with my_blueprint._before_request_lock:
if my_blueprint._got_first_request:
return
my_blueprint._got_first_request = True

#first请求,执行你所需要的。
print'yes'

这个模拟Flask在这里的功能。锁定是必要的,因为单独的线程可以争先恐后。


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'
解决方案

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 
        my_blueprint._got_first_request = True

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

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

这篇关于烧瓶蓝色打印before_first_request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:43