4

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?

Mikey T.K.
  • 1,112
  • 18
  • 43

2 Answers2

2

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.

jumbopap
  • 3,969
  • 5
  • 27
  • 47
1

Also note that you can start Flask in a separate thread with some restrictions. See this answer.

Community
  • 1
  • 1
Anton Drukh
  • 873
  • 7
  • 12