gpt4 book ai didi

python - Flask - 蓝图 - 在第一次请求之前?

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:12 29 4
gpt4 key购买 nike

我正在尝试将 before_first_request 功能添加到我的 Flask 应用程序的特定 Blueprint 中。您可以在下面看到我有两个蓝图:public 和 admin。

我已经尝试过,但没有成功:https://stackoverflow.com/a/27401269/7077556

这只适用于向应用程序发出的第一个请求,第一个请求之后来自其他设备和 IP 的任何其他请求都不会由此“自定义”before_first_request 处理。

我想仅针对客户端向公共(public)蓝图发出的第一个请求运行一个函数。

我该怎么做?提前致谢

这是我正在使用的代码:

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')

最佳答案

蓝图实例的

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')

关于python - Flask - 蓝图 - 在第一次请求之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078800/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com