烧瓶 - 蓝图 - 首次申请之前?

时间:2017-05-19 20:51:35

标签: python flask

我正在尝试将before_first_request功能添加到BlueprintFlask应用的特定Blueprints。您可以在下方看到我有两个before_first_request,公开和管理员。

我试过这个但没有成功:https://stackoverflow.com/a/27401269/7077556

这仅适用于对应用程序发出的第一个请求,来自其他设备和ip之后的任何其他请求,此后第一个请求不会由此" custom"处理。 Blueprint

我想仅针对客户向公众from flask import Flask, Blueprint application = Flask(__name__) # PUBLIC Blueprint public = Blueprint('public', __name__, static_url_path='/public', static_folder='static', template_folder='templates') # ADMIN Blueprint admin = Blueprint('admin', __name__, static_url_path='/admin', static_folder='static', template_folder='templates') # Before First Request To Public BP from threading import Lock public._before_request_lock = Lock() public._got_first_request = False @public.before_request def init_public_bp(): if public._got_first_request: return else: with public._before_request_lock: public._got_first_request = True print('THIS IS THE FIRST REQUEST!') # Do more stuff here... # PUBLIC ROUTE @public.route("/") def public_index(): return 'Hello World!' # ADMIN ROUTE @admin.route('/') def admin_index(): return 'Admin Area!' # Register PUBLIC Blueprint application.register_blueprint(public) # Register ADMIN Blueprint application.register_blueprint(admin, url_prefix='/admin') if __name__ == "__main__": application.run(host='0.0.0.0') 发出的第一个请求运行一个函数。

我该怎么做?提前致谢

这是我正在使用的代码:

>>> a,b=2,3
>>> c,d=3,2
>>> def f(x,y): print(x,y)

1 个答案:

答案 0 :(得分:1)

蓝图实例的

before_request不是装饰者。它只是一个实例方法,它在请求之前调用函数。你应该以这种方式使用它:

from __future__ import print_function
from flask import Flask, Blueprint

application = Flask(__name__)

# PUBLIC Blueprint
public = Blueprint('public', __name__, static_url_path='/public', static_folder='static', template_folder='templates')

# ADMIN Blueprint
admin = Blueprint('admin', __name__, static_url_path='/admin', static_folder='static', template_folder='templates')


# Before First Request To Public BP
from threading import Lock
public._before_request_lock = Lock()
public._got_first_request = False

def init_public_bp():
    if public._got_first_request:
        return  # or pass
    with public._before_request_lock:
        public._got_first_request = True
        print('THIS IS THE FIRST REQUEST!')
        # Do more stuff here...
public.before_request(init_public_bp)


# PUBLIC ROUTE
@public.route("/")
def public_index():
    return 'Hello World!'

# ADMIN ROUTE
@admin.route('/')
def admin_index():
    return 'Admin Area!'

# Register PUBLIC Blueprint
application.register_blueprint(public)
# Register ADMIN Blueprint
application.register_blueprint(admin, url_prefix='/admin')

if __name__ == "__main__":
    application.run(host='0.0.0.0')