I'm trying to share a variable I defined in my main function with a flask app which is imported from another file. First I tried to solve it via a classic global
variable which did not bring me any further, until I stumbled over the concept of flask.g and the app context.
So I tried the following: I have two files in the same directory, a main.py
:
# main.py
import app
from flask import g
if __name__ == "__main__":
with app.app.app_context():
g.value = "Hello World"
app.app.run(debug=True, threaded=True, host='localhost', port=5000)
and a app.py
:
# app.py
from flask import Flask, g
app = Flask(__name__)
@app.route('/helloworld')
def send_response():
return g.value
However, when I request at http://localhost:5000/helloworld I get
AttributeError: '_AppCtxGlobals' object has no attribute 'value'
So it seems that setting the value g.value
in one file is not reflected in the app.
I'm a beginner in Flask and it is very likely I did not get the concept right.
Similar questions did not get me any answer I could use to fix the issue:
Flask passing global variable, python-How to set global variables in Flask?, Preserving global state in a flask application
Help would be much appreciated!