Python 如何调试 Flask 应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17309889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:51:11  来源:igfitidea点击:

How to debug a Flask app

pythondebuggingflask

提问by Kimmy

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?

你打算如何在 Flask 中调试错误?打印到控制台?快闪消息到页面?或者是否有更强大的选项可用于找出出现问题时发生的情况?

回答by bnlucas

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

您可以使用下面提到app.run(debug=True)Werkzeug Debugger编辑,我应该知道。

回答by davidism

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=developmentenvironment variable then use the flask runcommand (remember to point FLASK_APPto your app as well).

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

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

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

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

For Windows CMD, use setinstead of export:

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

set FLASK_ENV=development

For PowerShell, use $env:

对于 PowerShell,请使用$env

$env:FLASK_ENV = "development"

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

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

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

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

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/flaskscript 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.

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

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

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



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.

确保不要使用太广泛的块除外。用 catch-all 包围所有代码try... except...将使您想要调试的错误静音。通常没有必要,因为 Flask 已经通过显示调试器或 500 错误并将回溯打印到控制台来处理异常。

回答by édouard Lopez

From the 1.1.xdocumentation, you can enable debug mode by exporting an environment variable:

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

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

回答by rstackhouse

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

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

python -m pdb script.py

python -m pdb script.py

回答by turdus-merula

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

还可以使用Flask 调试工具栏扩展来获取嵌入在渲染页面中的更多详细信息。

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

回答by Eman4real

If you're using Visual Studio Code, replace

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

app.run(debug=True)

with

app.run()

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

当打开内部调试器禁用 VS Code 调试器时出现。

回答by Sgryt87

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

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

回答by omkar yadav

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.

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

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.

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

回答by thisisayush

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

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

回答by Manishankar Singh

Install python-dotenvin your virtual environment.

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

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

在您的项目根目录中创建一个 .flaskenv。通过项目根目录,我的意思是包含您的 app.py 文件的文件夹

Inside this file write the following:

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

FLASK_APP=myapp 
FLASK_ENV=development

Now issue the following command:

现在发出以下命令:

flask run