Stopping Flask initialization from blocking

旧时模样 提交于 2021-01-28 01:37:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!