如何调试Flask应用

问题:如何调试Flask应用

您打算如何调试Flask中的错误?打印到控制台?向页面闪现消息?还是有一个更强大的选项可用来找出出现问题时发生的情况?

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?


回答 0

出现错误时,以开发模式运行该应用程序将在浏览器中显示交互式回溯和控制台。要在开发模式下运行,请设置FLASK_ENV=development环境变量,然后使用flask run命令(请记住也指向FLASK_APP您的应用程序)。

对于Linux,Mac,Windows的Linux子系统,Windows的Git Bash等:

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

对于Windows CMD,使用set而不是导出:

set FLASK_ENV=development

对于PowerShell,请使用$env

$env:FLASK_ENV = "development"

在Flask 1.0之前,它是由FLASK_DEBUG=1环境变量控制的。

如果您使用的是app.run()方法而不是flask run命令,请传递debug=True以启用调试模式。

不管开发模式如何,都将回溯打印到运行服务器的终端。

如果您使用的是PyCharm,VS Code等,则可以利用其调试器逐步使用带有断点的代码。运行配置可以指向调用app.run(debug=True, use_reloader=False)venv/bin/flask脚本,也可以将其指向脚本并像在命令行中一样使用它。您可以禁用重新加载器,但是重新加载将终止调试上下文,并且您将不得不再次捕获断点。

您还可以通过set_trace在要开始调试的视图中调用来使用pdb,pudb或其他终端调试器。


确保不要使用太宽的积木。将所有代码都包含在“包罗万象”中try... except...将使您想要调试的错误静音。一般来说,这是不必要的,因为Flask已经可以通过显示调试器或500错误并将回溯打印到控制台来处理异常。

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.


回答 1

您可以按如下所述app.run(debug=True)用于Werkzeug调试器 编辑,我应该知道。

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


回答 2

1.1.x文档中,您可以通过将环境变量导出到Shell提示符来启用调试模式:

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

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

回答 3

人们还可以使用Flask Debug Toolbar扩展程序来获取嵌入在渲染页面中的更多详细信息。

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>"

启动应用程序,如下所示:

FLASK_APP=main.py FLASK_DEBUG=1 flask run

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

回答 4

如果您使用的是Visual Studio Code,请替换

app.run(debug=True)

app.run()

当打开内部调试器禁用VS 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.


回答 5

如果要调试flask应用程序,则只需转到flask应用程序所在的文件夹。不要忘了激活您的虚拟环境,并将控制台行中的行更改“ mainfilename”粘贴到flask主文件。

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

启用flask应用程序的调试器后,几乎所有错误都会打印在控制台或浏览器窗口上。如果您想弄清楚发生了什么,可以使用简单的打印语句,也可以将console.log()用于javascript代码。

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.


回答 6

python-dotenv在虚拟环境中安装。

在项目根目录中创建一个.flaskenv。用项目根目录,是指包含您的app.py文件的文件夹

在此文件中写入以下内容:

FLASK_APP=myapp 
FLASK_ENV=development

现在发出以下命令:

flask run

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

回答 7

要在Flask中激活调试模式,您只需FLASK_DEBUG=1CMDWindows 上键入set 并FLASK_DEBUG=1在Linux terminal上导出,然后重新启动您的应用程序就可以了!

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!!


回答 8

快速提示-如果您使用的是PyCharm,请转到Edit Configurations=> Configurations并启用FLASK_DEBUG复选框,然后重新启动Run

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


回答 9

在开发环境中使用记录器和打印语句,在生产环境中可以进行岗哨。

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


回答 10

对于Windows用户:

打开Powershell并cd进入您的项目目录。

在Powershell中使用这些突击队,其他所有东西在Powershell中将无法使用。

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

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"

回答 11

如果您在本地运行它并希望能够逐步执行代码:

python -m pdb script.py

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

python -m pdb script.py