Issue
global variables get undefined on re-run of flask app, I have 3 files,
api.py
import trainer
app = Flask(__name__)
@app.route('/start', methods=['POST'])
def apifunc(id):
result = trainer.consume(id)
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True, port=LISTEN_PORT, threaded=True, use_reloader=False)
trainer.py
from utilities import function1
def consume(id)
value = function1(agg1)
... some codes...
return value
utilities.py
aggregate = 30
def function1(agg1):
global aggregate
... some codes...
print(aggregate)
when we run the app for the first time and hit the end point "/start", it picks the global variable "aggregate" value, it works,
but on 2nd hit, it throws error,
ERROR:api:500 Internal Server Error: name 'aggregate' is not defined
but when I stop and re-start the app and hit end point it works. Not sure why that's happening.
Solution
Edit: Since modification of the global variable on runtime is required, you should definitely use flask.g object. Module-wise global variables are neither thread safe nor process safe and this is most probably what causes the issue you're experiencing.
In python global variables are global to the module they are defined in, not to the global application context.
Regarding the examples provided, the global variable does not seem to be needed to be defined as global. Also, if you need it to be really global, you can put the variable into some module and import it where needed or use you can use the g global namespace of flask as seen below
from flask import g
...
setattr(g, VAR, VAL)
# then in some other function / module etc
from flask import g
val = getattr(g, VAR)
# or
val = g.VAR
# or set it when needed
setattr(g, VAR, NEW_VAL)
Answered By - altunyurt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.