gpt4 book ai didi

python - 如何在 flask 中的 app.run() 之前运行代码?

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:48 25 4
gpt4 key购买 nike

我是 flask 的新手。我用 flask+gunicorn 配置了一个服务器。

名为 test.py 的代码文件如下所示:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
return aa+"world!"

if __name__ == '__main__':
aa = "hello"
app.run()

使用:gunicorn -b 0.0.0.0:8080 test:app

我得到一个错误:NameError: name 'aa' is not defined.

我想要一些代码,比如变量 aa 在 gunicorn 之前运行。

怎么做?

最佳答案

在您的 @app.route 之前放入一个小块,您不需要问题中的最后一个 block

 @app.before_first_request
def _declareStuff():
global aa
aa='hello'

关于python - 如何在 flask 中的 app.run() 之前运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50249681/

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