how to run the code before the app.run() in flask?

别说谁变了你拦得住时间么 提交于 2019-12-10 15:14:54

问题


I'm new on flask.I configured a server with flask+gunicorn.

the code file called test.py like this:

from flask import Flask
app = Flask(__name__)

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

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

run it using:gunicorn -b 0.0.0.0:8080 test:app

I got a mistake:NameError: name 'aa' is not defined.

I want some codes like variable aa runing before gunicorn.

How to do that?


回答1:


Put in a small block just before your @app.route and you dont need the last block in the question

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



回答2:


Just declare aa outside of "__main__", in the global scope of the file.

from flask import Flask
app = Flask(__name__)

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

aa = "hello"

if __name__ == '__main__':
    app.run()

The code in the if __name__ == '__main__': block executes only if the Python code is run as a script, e.g., from the command line. Gunicorn imports the file, so in that case the code in __main__ will not be executed.


Note that if it is your intention to modify the value of aa then different requests can produce different results depending on how many requests each gunicorn worker process has handled. e.g.:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def test():
    global counter
    counter += 1
    return "{} world! {}".format('aa', counter)

counter = 0

if __name__ == '__main__':
    app.run()

Run the above script with more than one worker (gunicorn -w 2 ...) and make several requests to the URL. You should see that the counter is not always contiguous.



来源:https://stackoverflow.com/questions/50249681/how-to-run-the-code-before-the-app-run-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!