How to debug a Flask app

PythonDebuggingFlask

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

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.

Solution 7 - Python

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

Solution 8 - Python

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

Solution 9 - Python

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"

Solution 10 - Python

Quick hack to force debug mode: If you really wanted to turn debugger mode on. There is a quick hack that worked for me.
First add below code in app.py

# app.py
if __name__ == "__main__":
    app.run(debug=True)

Now, instead of using flask run, try python3 app.py runserver -d

# Terminal
python3 app.py runserver -d 

This will force to run server in debug mode.

Solution 11 - Python

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

Solution 12 - Python

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)

Solution 13 - Python

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

Solution 14 - Python

If you're using pycharm like me and are using the "run" button, you simply have to modify some settings inside pycharm itself. What the IDE does is run a command using your options, just nicely wrapped.

Top right corner > Edit Configurations... > check the box next to "FLASK_DEBUG".

This option enables werkzeug debugger without you having to change your code (good for apps that you need to deploy). See here: https://flask.palletsprojects.com/en/2.0.x/debugging/

Works perfectly.

Solution 15 - Python

Flask is web application framework. Flask is written in Python language. By using this framework we can develop websites. It is also referred to as a micro framework . It does not have in-built abstraction layer for database handling. It supports the extensions to add such functionality to the application.

Flask framework use the routing technique to help a user remember application Url. By using router we can directly access the desired page without navigating. We can also build a Url dynamically , by adding some variable parts. In web application we use unique Url for each operation.

When the run() method call then our Flask application will start.

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

If we write app.run() and our application is under development, it should be restarted manually for each change in the code. So for every change in the program we have to restart the server and try to observe the changes. If we are developing an application then we have to check each changes that we are doing in our application is correct or not. So it will require to restart the server again and again. If we are doing this then it takes much time. We all know that time is very much important in the IT industry and if we do not complete our project on time then it will not good for the developer as well as the team who is working on that project.

To overcome this problem, enable debug support. The server will then reload it self if the code changes. It will also provide a useful debugger. By using this debugger it track the errors if any in the application. We can enable debug mode by setting the debug property of the application object to True before running or passing the debug parameter to the run() method. So we should have to write app.run(debug=True).

if __name__=="__main__":
    app.run(debug=True)

If we write app.run(debug=True) then it will save our time and we do not require to run the code again and again. If we write this then it will save our time and we can use our time in development and make more efficient project.

We can also write :

if __name__=="__main__":
    app.debug=True
    app.run()
    app.run(debug=True)

It also works the same like the above code is written and in this also we do not require to run the code again and again.

Solution 16 - Python

If you're using VSCode, press F5 or go to "Run" and "Run Debugging".

Solution 17 - Python

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

python -m pdb script.py

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKimmyView Question on Stackoverflow
Solution 1 - PythondavidismView Answer on Stackoverflow
Solution 2 - PythonbnlucasView Answer on Stackoverflow
Solution 3 - PythonÉdouard LopezView Answer on Stackoverflow
Solution 4 - Pythonturdus-merulaView Answer on Stackoverflow
Solution 5 - PythonEman4realView Answer on Stackoverflow
Solution 6 - Pythonomkar yadavView Answer on Stackoverflow
Solution 7 - PythonZahidView Answer on Stackoverflow
Solution 8 - PythonMSSView Answer on Stackoverflow
Solution 9 - Pythonsn98View Answer on Stackoverflow
Solution 10 - PythontusharView Answer on Stackoverflow
Solution 11 - PythonSgryt87View Answer on Stackoverflow
Solution 12 - PythonIoan BeilicView Answer on Stackoverflow
Solution 13 - PythonthisisayushView Answer on Stackoverflow
Solution 14 - PythonatultwView Answer on Stackoverflow
Solution 15 - PythonRobins KumarView Answer on Stackoverflow
Solution 16 - Pythonsule mohammedView Answer on Stackoverflow
Solution 17 - PythonrstackhouseView Answer on Stackoverflow