Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 379
XiaXuehai Avatar asked May 09 '18 09:05

XiaXuehai


1 Answers

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'
like image 125
Vipluv Avatar answered Sep 18 '22 02:09

Vipluv