问题
I'm adding Flask support to a plugin-based application. On startup, the app instantiates a number of plugin classes. I thought this would be as simple as having Flask kick off when the class is initialized, but instead, the whole app hangs when it hits the Flask startup method.
Consider the following example:
#!/usr/bin/env python
from flask import Flask
class TestClass:
def __init__(self):
print('Initializing an instance of TestClass')
self.app = Flask(__name__)
self.app.run()
print("Won't get here until Flask terminates!")
foo = TestClass()
The second print line won't be evaluated until Flask is terminated.
Is there a sane way to force the app.run
into the background so that the class continues its initialization steps, while still having the ability to communicate with Flask throughout the rest of my class?
回答1:
The app isn't "hanging", the intention of app.run
is to start a persistent server process that runs until explicitly closed. You should run all setup logic before you start the server.
If you need to run tasks after the app server process has initialized, you can dispatch them in another process with something like Celery.
回答2:
Also note that you can start Flask
in a separate thread with some restrictions. See this answer.
来源:https://stackoverflow.com/questions/34981896/stopping-flask-initialization-from-blocking