Run code after flask application has started

flask after response
flask_script
flask run python script
flask app run forever
flask app run blocking
flask thread
flask after_request_funcs
python run flask in thread

My goal is to get arbitrary code to run after my Flask application is started. Here is what I've got:

def run():
    from webapp import app
    app.run(debug=True, use_reloader=False)

Ideally I would be able to just do this:

def run():
    from webapp import app
    app.run(debug=True, use_reloader=False)
    some_code()

But the code doesn't continue past app.run(), so some_code() never runs.

The solution I'm working on at the moment is to run some_code() in a separate thread from app.run(), create a before first request function that sets this:

app.is_running = True

Then get some_code() to shoot a basic request to app so that the 'before first request' code runs. This is fairly convoluted and going to be hard to document. I would rather use app.is_running parameter which already is provided in Flask, or use a @app.after_server_start decorator, but to my knowledge neither of those exists.

Help me make this code better?


Posthumous: Every time I think about this issue, it makes me wish that a @app.after_server_start decorator existed.


If you need to execute some code after your flask application is started but strictly before the first request, not even be triggered by the execution of the first request as @app.before_first_request can handle, you should use Flask_Script, as CESCO said, but you could subclass the class Server and overwrite the __ call __ method, instead of overwriting the runserver command with @manager.command:

from flask import Flask
from flask_script import Manager, Server

def custom_call():
    #Your code
    pass

class CustomServer(Server):
    def __call__(self, app, *args, **kwargs):
        custom_call()
        #Hint: Here you could manipulate app
        return Server.__call__(self, app, *args, **kwargs)

app = Flask(__name__)
manager = Manager(app)

# Remeber to add the command to your Manager instance
manager.add_command('runserver', CustomServer())

if __name__ == "__main__":
    manager.run()

This way you don't override default options of runserver command.

Starting a task at startup in Flask, Flask allows you to start a task before it processes the first request from a The problem I had is that the function doesn't get run until after a user has The API for APIC-EM is quite comprehensive, but the web application  While previously a simple app.run() call inside the application script was used, now there is a flask run command, plus a FLASK_APP environment variable. While the design of the Flask website has changed considerably in the years that followed, as I’m writing this article in 2020 the flask run method continues to be the most visible in the official documentation for the framework.


Use Flask-Script to run your app, then overwrite the runserver class/method like this

# manage.py

from flask.ext.script import Manager

from myapp import app

manager = Manager(app)

def crazy_call():
    print("crazy_call")

@manager.command
def runserver():
    app.run()
    crazy_call()

if __name__ == "__main__":
    manager.run()

[SOLVED] Run code after flask application has started, If you need to execute some code after your flask application is started but strictly before the first request, not even be triggered by the execution  I'm trying to run something after the Flask server has started. The only thing I found is to run another thread with sleep. How can I do this? this is not a duplicate because i need the server to listen when the method i want to run, executes.


I just did (in a main.py executed with python main.py):

with app.app_context():
    from module import some_code()
    some_code()

def run():
    from webapp import app
    app.run(debug=True, use_reloader=False)

This worked for me without the more comprehensive answers offered above. In my case some_code() is initializing a cache via flask_caching.Cache.

But it probably depends on what exactly some_code is doing...

How to fun code/function after flask app is started? - Predix , I am trying to start a scheduler as soon as the python microservice /27465533/​run-code-after-flask-application-has-started However, the code  When running the server using the ‘flask run’ command, you don’t need to call the run() method in your code. After running the server, if you try to open the server URL in your browser, it will give an error message because you haven’t declared or defined any routes for your application.


I don't really like any of the methods mentioned above, for the fact that you don't need Flask-Script to do this, and not all projects are going to use Flask-Script already.

The easiest method, would be to build your own Flask sub-class. Where you construct your app with Flask(__name__), you would simply add your own class and use it instead.

def do_something():
  print('MyFlaskApp is starting up!')


class MyFlaskApp(Flask):
  def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
    if not self.debug or os.getenv('WERKZEUG_RUN_MAIN') == 'true':
      with self.app_context():
        do_something()
    super(MyFlaskApp, self).run(host=host, port=port, debug=debug, load_dotenv=load_dotenv, **options)


app = MyFlaskApp(__name__)
app.run()

Of course, this doesn't run after it starts, but right before run() is finally called. With app context, you should be able to do anything you may need to do with the database or anything else requiring app context. This should work with any server (uwsgi, gunicorn, etc.) as well.

If you need the do_something() to be non-blocking, you can simply thread it with threading.Thread(target=do_something).start() instead.

The conditional statement is to prevent the double call when using debug mode/reloader.

How to run a task after flask server starts? : flask, Flask is easy to get started with and a great way to build web sites and web … guys, I'm trying to run my flask site in a pyqt5 GUI interface however after app.run​(), Anyone know how to run the flask server and allow a function to run after it? This configuration contains "module": "flask",, which tells VS Code to run Python with -m flask when it starts the debugger. It also defines the FLASK_APP environment variable in the env property to identify the startup file, which is app.py by default, but allows you to easily specify a different file.


I encountered this same issue in a flask app of mine. I wanted to start a scheduler at app startup, which would kick off some jobs at regular intervals. Since I deploy my apps inside docker containers, what I ended up doing is adding an "health check" endpoint which just returns a 200, and in my dockerfile configured that endpoint:

HEALTHCHECK CMD curl --fail http://localhost:8080/alive || exit 1

The default behavior is to execute that command every 30s, and the first run conveniently kicks off my init() method. https://docs.docker.com/engine/reference/builder/#healthcheck

Flask before and after request functions, We'll start out with a very basic Flask application: This function will run once before_request is running! index is running! root bar 127.0.0.1  February 28, 2017. Flask includes a Python decorator which allows you to run a function before the first request from a user is processed. The problem I had is that the function doesn’t get run until after a user has visited a page for the first time. This article describes a way to solve that.


Quickstart, To run the application you can either use the flask command or python's -m switch with Flask. Before The flask script is nice to start a local development server, but you would have to restart it manually after each change to your code. That is  The flask script is nice to start a local development server, but you would have to restart it manually after each change to your code. That is not very nice and Flask can do better. That is not very nice and Flask can do better.


Application Setup, This function is known as the application factory. It's time to start coding! Create export FLASK_APP=flaskr $ export FLASK_ENV=development $ flask run. Now, you should be good to go. The flask app will start every time after you boot you machine.(note: distribution package has already integrated into the service management infrastructure, if you're using others, see here) to check whether you app is running: $ sudo supervisorctl status


Python Flask: running code before and after every request, Learn how to run your own code before or after any Flask request using a single In Flask it is possible to catch all requests in your application before or after they within the actual endpoint that initiated the before_request() method will run. Running either in a thread is working around the problem instead of addressing it. I'd recommend running the flask server in a background process a known port (or better, a socket). You'd need some way to trigger the server to start if it's not started when the GUI boots up. To bind the flask application to a socket, you'll need to run something like gunicorn.