0

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!

Sebastian Dengler
  • 1,258
  • 13
  • 30

1 Answers1

1

Just use a regular Python module-level variable.

# app.py

g = "Example"

@app.route("/example")
def example_endpoint():
    return g
# main.py

import app

app.g = "Hello"

Quoting the same page you linked:

The application context is created and destroyed as necessary. When a Flask application begins handling a request, it pushes an application context and a request context. When the request ends it pops the request context then the application context. Typically, an application context will have the same lifetime as a request.

So your setting flask.g outside of a request context (in your main.py) doesn't carry your value to anywhere.

iBug
  • 35,554
  • 7
  • 89
  • 134