[python] How to debug a Flask app

How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what's happening when something goes wrong?

This question is related to python debugging flask

The answer is


If you are running it locally and want to be able to step through the code:

python -m pdb script.py


with virtual env activate

export FLASK_DEBUG=true

you can configure

export FLASK_APP=app.py  # run.py
export FLASK_ENV = "development"

to start

flask run

the result

 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: xxx-xxx-xxx

and if you change

export FLASK_DEBUG=false

 * Environment: development
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

From the 1.1.x documentation, you can enable debug mode by exporting an environment variable to your shell prompt:

export FLASK_APP=/daemon/api/views.py  # path to app
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0

One can also use the Flask Debug Toolbar extension to get more detailed information embedded in rendered pages.

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
import logging

app = Flask(__name__)
app.debug = True
app.secret_key = 'development key'

toolbar = DebugToolbarExtension(app)

@app.route('/')
def index():
    logging.warning("See this message in Flask Debug Toolbar!")
    return "<html><body></body></html>"

Start the application as follows:

FLASK_APP=main.py FLASK_DEBUG=1 flask run

To debug a Flask application you need to use:

server.run(
    debug=True
)

To activate debug mode in flask you simply type set FLASK_DEBUG=1 on your CMD for windows and export FLASK_DEBUG=1 on Linux termial then restart your app and you are good to go!!


Running the app in development mode will show an interactive traceback and console in the browser when there is an error. To run in development mode, set the FLASK_ENV=development environment variable then use the flask run command (remember to point FLASK_APP to your app as well).

For Linux, Mac, Linux Subsystem for Windows, Git Bash on Windows, etc.:

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

For Windows CMD, use set instead of export:

set FLASK_ENV=development

For PowerShell, use $env:

$env:FLASK_ENV = "development"

Prior to Flask 1.0, this was controlled by the FLASK_DEBUG=1 environment variable instead.

If you're using the app.run() method instead of the flask run command, pass debug=True to enable debug mode.

Tracebacks are also printed to the terminal running the server, regardless of development mode.

If you're using PyCharm, VS Code, etc., you can take advantage of its debugger to step through the code with breakpoints. The run configuration can point to a script calling app.run(debug=True, use_reloader=False), or point it at the venv/bin/flask script and use it as you would from the command line. You can leave the reloader disabled, but a reload will kill the debugging context and you will have to catch a breakpoint again.

You can also use pdb, pudb, or another terminal debugger by calling set_trace in the view where you want to start debugging.


Be sure not to use too-broad except blocks. Surrounding all your code with a catch-all try... except... will silence the error you want to debug. It's unnecessary in general, since Flask will already handle exceptions by showing the debugger or a 500 error and printing the traceback to the console.


Install python-dotenv in your virtual environment.

Create a .flaskenv in your project root. By project root, I mean the folder which has your app.py file

Inside this file write the following:

FLASK_APP=myapp 
FLASK_ENV=development

Now issue the following command:

flask run

If you want to debug your flask app then just go to the folder where flask app is. Don't forget to activate your virtual environment and paste the lines in the console change "mainfilename" to flask main file.

export FLASK_APP="mainfilename.py"
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0

After you enable your debugger for flask app almost every error will be printed on the console or on the browser window. If you want to figure out what's happening, you can use simple print statements or you can also use console.log() for javascript code.


If you're using Visual Studio Code, replace

app.run(debug=True)

with

app.run()

It appears when turning on the internal debugger disables the VS Code debugger.


For Windows users:

Open Powershell and cd into your project directory.

Use these commandos in Powershell, all the other stuff won't work in Powershell.

$env:FLASK_APP = "app"  
$env:FLASK_ENV = "development"

You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.


Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.


Quick tip - if you use a PyCharm, go to Edit Configurations => Configurations and enable FLASK_DEBUG checkbox, restart the Run.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to debugging

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?