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.
a
? Thata
is indeed undefined.. – Aldousaa
? – Jemison