DEV Community

Luke Babich
Luke Babich

Posted on

Python: Auto Reload Using Flask

So recently I have been jumping into the world of Python and creating my own servers etc now that I felt like I had a grasp of the language.

Coming from Javascript with NodeJS using nodemon, ts-node-dev etc. First thing I wanted in this server was for it to auto reload on changes.

So lets jump right into it.

from flask import Flask

app = Flask(__name__)

def hello_world():
    return 'Hello, Nice!'

if __name__ == '__main__':'', 8085)
Enter fullscreen mode Exit fullscreen mode

So this is just your standard Hello World server. The main difference is there is a little check to determine if the file is being executed itself or not.

So using our favorite IDE (In my case PyCharm) we are able to execute that file and the server would run with

 * Serving Flask app "app" (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: off
 * Running on (Press CTRL+C to quit)

We now want to run this with a debugger and for it to reload automagically on changes. To do so you can generally just run (you can one line this I just like multi):

export FLASK_ENV=development

flask run --port 8085

However that would become tedious to have to do that every time. So in my project folder I created a /bin directory and added a script with the following:


export FLASK_ENV=development

flask run --port 8085

Enter fullscreen mode Exit fullscreen mode

Now I can then execute the above script via the IDE which will set everything up for me that I could want. This will now output:

 * Serving Flask app "" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 294-871-031
 * Running on (Press CTRL+C to quit)

Which means we can then go and attach to the debugging process now created, then our breakpoints will work, with the benefit of reloading on changes!

The power of this is that I can now create different executable scripts depending on my needs and not have to worry about it.

Hopefully this helped someone and any improvements I welcome any feedback!

Discussion (3)

filipebezerra profile image
Filipe Bezerra • Edited on

Nice Luke. We can automate even more. Just create a .flaskenv in the root of the project and move those variables to this file, actually this is the recommended basic way to load enviroment variables with Flask.

Flask will use the default load_dotenv=True param and load this file.

ironcladdev profile image

You can have debug mode on inside of the function. Just do something like'', 8085, debug=True)

canopix profile image

Thanks! you´re helping a lot with this post