flask
python
auto-reload
web-development
code-changes

Flask auto reload: restart the dev server on code changes

Codemia Knowledge Hub ·

Run Flask in debug mode and the built-in reloader restarts the development server whenever you change a Python source file. Use flask run --debug, pass debug=True to app.run(), or set FLASK_DEBUG=1. The reloader comes from Werkzeug. Non-Python files may need extra configuration, and debug mode must never be enabled in production.

Option 1: app.run(debug=True)

python
1from flask import Flask
2
3app = Flask(__name__)
4
5@app.route('/')
6def hello():
7    return 'Hello, World!'
8
9if __name__ == '__main__':
10    app.run(debug=True)  # Enables auto-reload + debugger
bash
1python app.py
2# * Running on http://127.0.0.1:5000
3# * Restarting with stat
4# * Debugger is active!

debug=True enables both the auto-reloader and the interactive debugger. When you save a .py file, the server restarts within about a second.

bash
1# Set the app entry point
2export FLASK_APP=app.py
3
4# Run with debug mode
5flask run --debug
6
7# Or with reload explicitly
8flask run --reload
9
10# Or set via environment variable
11export FLASK_DEBUG=1
12flask run

The flask run CLI is the recommended way to start Flask applications. --debug enables both auto-reload and the debugger. --reload enables only the reloader, without the debugger.

Option 3: environment variables in a .env file

bash
1# .env file (used with python-dotenv)
2FLASK_APP=app.py
3FLASK_DEBUG=1
4FLASK_RUN_PORT=5000
5FLASK_RUN_HOST=0.0.0.0
python
1# app.py — Flask automatically loads .env if python-dotenv is installed
2from flask import Flask
3
4app = Flask(__name__)
5
6@app.route('/')
7def index():
8    return 'Auto-reload enabled!'
bash
pip install python-dotenv
flask run
# Automatically reads .env and enables debug mode

A .env file keeps debug configuration out of your source code. Flask loads it automatically when python-dotenv is installed.

stat vs watchdog reloader

python
1if __name__ == '__main__':
2    # 'stat' reloader — polls files for changes (default)
3    app.run(debug=True, reloader_type='stat')
4
5    # 'watchdog' reloader — uses OS file system events (faster)
6    # Requires: pip install watchdog
7    # app.run(debug=True, reloader_type='watchdog')
bash
1# Install watchdog for faster file change detection
2pip install watchdog
3
4# Flask automatically uses watchdog if installed
5flask run --debug
6# * Restarting with watchdog (inotify)

The default stat reloader polls files every second, which can be slow on large projects. The watchdog reloader uses OS file system events (inotify on Linux, FSEvents on macOS) for near-instant detection.

Watching extra files

bash
1# Watch additional file types beyond .py
2flask run --debug --extra-files templates/base.html:config.yaml
3
4# A directory only adds the .py files inside it, so list other files one by one
5flask run --debug --extra-files "static/css/site.css:static/css/print.css"
python
1if __name__ == '__main__':
2    # Watch extra files programmatically
3    app.run(
4        debug=True,
5        extra_files=[
6            'config.yaml',
7            'templates/base.html',
8        ]
9    )

By default, Flask watches only .py files. Jinja2 template changes show up without a restart because templates are re-rendered on each request. Configuration files and other non-Python files need extra_files.

Live reload inside Docker

yaml
1# docker-compose.yml
2version: '3.8'
3services:
4  web:
5    build: .
6    ports:
7      - "5000:5000"
8    volumes:
9      - .:/app          # Mount source code for live changes
10    environment:
11      - FLASK_APP=app.py
12      - FLASK_DEBUG=1
13    command: flask run --host=0.0.0.0 --debug
dockerfile
1# Dockerfile
2FROM python:3.11-slim
3WORKDIR /app
4COPY requirements.txt .
5RUN pip install -r requirements.txt
6COPY . .
7CMD ["flask", "run", "--host=0.0.0.0"]

The volume mount (- .:/app) maps your local source into the container, so the reloader inside the container sees your edits and restarts.

Turning the reloader off

python
# Debug mode ON but reloader OFF
if __name__ == '__main__':
    app.run(debug=True, use_reloader=False)
bash
# CLI equivalent
flask run --debug --no-reload

Disable the reloader when the restart itself causes problems, for example dropped database connections, or when attaching an external debugger such as PyCharm or VS Code.

Reloader problems and how to fix them

  • Debug mode in production: debug=True exposes the Werkzeug interactive debugger, which allows arbitrary Python code execution from the browser. This is a critical security vulnerability. Use environment variables so debug mode is only active in development.
  • Changes to non-.py files are not detected: templates are re-rendered per request, but .yaml, .json and other config files need --extra-files or extra_files=.
  • Restart loop after a syntax error: if a syntax error occurs during import, the reloader may fail to restart cleanly. Fix the error and it recovers. If it does not, stop and restart the server manually.
  • Port already in use after a crash: the port (5000) may stay bound. Run lsof -i :5000 (macOS/Linux) or netstat -ano | findstr :5000 (Windows) to find and kill the orphaned process.
  • Startup code runs twice: the Werkzeug reloader spawns a child process that runs your app again, so initialization such as database setup or starting a scheduler executes in both processes. Werkzeug provides werkzeug.serving.is_running_from_reloader(), which tells you whether the current process is the reloader's subprocess. Flask's before_first_request was deprecated in 2.2 and removed in 2.3, so run setup code when creating the application (for example in an app factory) instead.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms