【发布时间】:2017-05-20 06:21:11
【问题描述】:
我正在尝试将before_first_request 功能添加到我的Flask 应用程序的特定Blueprint。下面你可以看到我有两个Blueprints,public 和 admin。
我试过这个但没有成功:https://stackoverflow.com/a/27401269/7077556
这仅适用于向应用程序发出的第一个请求,来自其他设备的任何其他请求和第一个请求之后的 ip 都不会由此“自定义”before_first_request 处理。
我想为客户向公众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')
【问题讨论】: