Reputation: 103
I'm building a Flask application that needs to access an initialized class across requests. The below POST request to the Flask server says that the global variable ex is of type None, despite it being initialized and reassigned to the Engine class in the main on startup. Why is this?
ex = None #Storing the executable so that it can be accessed
flask_app = Flask(__name__)
flask_app.debug = True
@flask_app.route('/reach_engine', methods = ['POST'])
def result():
global ex
print(ex.txt) #Prints type error, saying that ex is of type None (this is the problem)
class Engine:
def __init__(self):
super(Engine, self).__init__()
self.txt = 'The real Engine'
def startApp():
global ex
ex = Engine()
if __name__ == '__main__':
#Start a thread that will run the main app
t = threading.Thread(target=startApp)
t.daemon = True
t.start()
# Start the flask app
print(rd_info + "Intializing Flask application")
flask_app.run('0.0.0.0', '1000', debug=True,
threaded=True, use_reloader=False)
Upvotes: 1
Views: 1616
Reputation: 103
This has now been resolved. In the original code, there was an intentional for loop in the initialization of the engine, causing the global variable ex never to be fully assigned. (Note for others finding this)
Upvotes: 0
Reputation: 24966
I ran your code after adding the missing imports, setting rd_info, and changing the port to 5000 (because ports below 1024 are privileged ports on many systems)
$ python stackoverflow.py
random-Intializing Flask application
* Serving Flask app "stackoverflow" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
then
$ curl --request POST --data '' http://0.0.0.0:5000/reach_engine
caused
The real Engine
10.0.2.2 - - [10/Jul/2020 17:31:18] "POST /reach_engine HTTP/1.1" 500 -
Traceback (most recent call last):
...
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
plus a spew of Flask/Werkzeug debug info on the curl side. I expected the TypeError, given the lack of return in the route. Still, this proves that the thread is running.
This was on Ubuntu 18.04 with Python 3.6.9.
Upvotes: 1
Reputation: 26
Try to use @flask_app.before_first_request and then create the thread. I leave you this link if you want more details: Global variable is None instead of instance - Python
Upvotes: 1