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?
Running the app in debug mode will show an interactive traceback and console in the browser when there is an error. As of Flask 2.2, to run in debug mode, pass the --app and --debug options to the flask command.
$ flask --app example --debug run
Prior to Flask 2.2, this was controlled by the FLASK_ENV=development environment variable instead. You can still use FLASK_APP and FLASK_DEBUG=1 instead of the options above.
For Linux, Mac, Linux Subsystem for Windows, Git Bash on Windows, etc.:
$ export FLASK_APP=example
$ export FLASK_DEBUG=1
$ flask run
For Windows CMD, use set instead of export:
set FLASK_DEBUG=1
For PowerShell, use $env:
$env:FLASK_DEBUG = "1"
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.
You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.
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
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.
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.
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!!
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
When running as python app.py instead of the flask command, you can pass debug=True to app.run.
if __name__ == "__main__":
app.run(debug=True)
$ python app.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)
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"
If you have PyCharm Professional, you can create a Flask server run configuration and enable the FLASK_DEBUG checkbox. Go to Run > Edit Configurations, select or create a Flask server configuration, and enable the FLASK_DEBUG checkbox. Click OK, then click the run button.
You can install python-dotenv with
pip install python-dotenv then create a .flask_env or a .env file
The contents of the file can be:
FLASK_APP=myapp
FLASK_DEBUG=True
Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.
After setting the environment variables FLASK_ENV and FLASK_APP running flask run will give me this error:
The snippet shows the command promt.
It says that environment is production and that I didn't provide the FLASK_APP environment variable, even though I typed them in. Did I miss something or can someone explain why this error occurs?
i suggest you this good read https://www.twilio.com/blog/how-run-flask-application on how to run Flask Application (there are 2 approaches)
i also recommend you reading this topic https://flask.palletsprojects.com/en/1.1.x/cli/?highlight=flaskenv#environment-variables-from-dotenv
the better approach is to create .flaskenv file in the root of your project where you set your environment variables like so :
in /.flaskenv file
FLASK_APP=myflaskproject:create_app()
FLASK_ENV=development
FLASK_DEBUG=0
# FLASK_RUN_EXTRA_FILES=
# FLASK_RUN_HOST=
# FLASK_RUN_PORT=8080
# FLASK_RUN_CERT=
# FLASK_RUN_KEY=
in FLASK_APP you call your app but usually it's recommended to use "Application Factory" pattern, see https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/
then
(.venv) flask run
don't forget to install python-dotenv
At least on Linux you cannot have spaces around the equal sign. Maybe on Windows this is the same.
In the official Flask documentation you can read:
set FLASK_APP=hello
https://flask.palletsprojects.com/en/1.1.x/cli/
set flask<space>=<space>src/app.py
As you can see you are NOT setting flask but flask<space>. Flask may accept that path but it is an illegal windows path.
I am looking for an efficient way to develop plugins within Airflow.
Current behavior: I change something in Python files e.g. test_plugin.py, reload the page in browser and nothing happens until I restart the webserver. This is most annoying and time consuming.
Desired behavior: I change something in Python files and the change is reflected after reloading the app in the browser.
As Airflow is based on Flask and in Flask the desired behavior is achievable by running Flask in debug mode (export FLASK_DEBUG=1, then start Flask app): Can I achieve the Flask behavior somehow in Airflow?
It turns out that this was indeed a bug with the Airflow CLI's webserver --debug mode; future versions will have the expected behavior.
Issue: https://issues.apache.org/jira/browse/AIRFLOW-5867
PR: https://github.com/apache/airflow/pull/6517
In order to run Airflow with live reloading, run the following command (10.7+):
$ airflow webserver --debug
In contrast to the code modification suggested by #herrjeh42, make sure that your configuration does not include unit_test_mode = True in order to enable reloading.
Cheers!
You can force reloading the python code by starting the airflow webserver in debug & reload mode. As of Airflow 1.10.5 I had to modify airflow/bin/cli.py (from my opinion the line is buggy).
old:
app.run(debug=True, use_reloader=False if app.config['TESTING'] else True,
new:
app.run(debug=True, use_reloader=True if json.loads(app.config['TESTING'].lower()) else False,
Change in airflow.cfg
unit_test_mode = True
Start the webserver with
airflow webserver -d
Is it possible to run my Django project in DEBUG mode, when in PyCharm? If not in PyCharm, say in production, then of course the DEBUG mode should not be True. How can this be done most neatly?
The easiest way would probably be setting up your settings.py to read the DEBUG value from the environment variables, then tell PyCharm to run with that env var set.
import os
# ...
DEBUG = (True if os.environ.get('DEBUG') else False)
and set DEBUG=1 in PyCharm's Edit Configurations... window.
Edit your run configuration and set an environment variable called DJANGO_DEBUG to True. The easiest way to do this is to create a custom run configuration.
Run > Edit Configurations
Create a new configuration for django, by clicking on + and selecting django server:
Then, set a custom environment variable. You do this by clicking on the button next to PYTHONUNBUFFERED=1:
Next, add a new configuration variable by clicking the +
Click OK, and give your new configuration a name:
Click Apply then OK to dismiss the dialogues.
Edit your settings.py and add this:
import os
DEBUG = os.environ.get('DJANGO_DEBUG', False)
Now, simply select your new configuration from the Run menu when you want to run with debugging enabled.
The standard approach for this is to have multiple Django settings files:
settings/
base.py
production.py
development.py
testing.py
then you can run DJANGO_SETTINGS_MODULE=settings.development manage.py runserver.
PyCharm allows to pick the settings in run configurations too.
Use cookiecutter-duango to generate the project template when starting a new Django project. Your project can be configured for development with PyCharm and you get the both configurations, development (with DEBUG=True) and production (with DEBUG=False) automatically.
I'm writing my first Flask application. The application itself runs fine. I just have a newbie question about logging in production mode.
The basic structure:
app/
app/templates/
app/static
config.py
flask/... <- virtual env with flask + extensions
run.py
The application is started by run.py script:
#!flask/bin/python
import os.path
import sys
appdir = os.path.dirname(os.path.abspath(__file__))
if appdir not in sys.path:
sys.path.insert(1, appdir)
from app import app as application
if __name__ == '__main__':
application.run(debug=True)
and is started either directly or from an Apache 2.4 web server. I have these lines in the apache config:
WSGIPythonHome /usr/local/opt/app1/flask
WSGIScriptAlias /app1 /usr/local/opt/app1/run.py
In the former case, the debug=True is all I need for the development.
I'd like to have some logging also for the latter case, i.e. when running under Apache on a production server. Following is a recommendation from the Flask docs:
if not app.debug:
import logging
from themodule import TheHandlerYouWant
file_handler = TheHandlerYouWant(...)
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
It needs some customization, but that's what I want - instructions for the case when app.debug flag is not set. Similar recommendation was given also here:
How do I write Flask's excellent debug log message to a file in production?
Please help: where do I have to put this code?
UPDATE: based on the comments by davidism and the first answer I've got I think the app in the current simple form is not suitable for what I was asking for. I will modify it to use different sets of configuration data as recommended here: http://flask.pocoo.org/docs/0.10/config/#development-production . If my application were larger, I would follow the pech0rin's answer.
UPDATE2: I think the key here is that the environment variables should control how the application is to be configured.
I have had a lot of success with setting up my logging configurations inside a create_app function. This uses the application factory pattern. This allows you to pass in some arguments or a configuration class. The application is then specifically created using your parameters.
This allows you initialize the application, setup logging, and do whatever else you want to do, before the application is sent back to be run.
For example:
def create_app(dev=False):
app = Flask(__name__)
if dev:
app.config['DEBUG'] = True
else:
...
app.logger.addHandler(file_handler)
return app
This has worked very well for me in production environments. YMMV