如何调试 Flask 应用程序 [英] How to debug a Flask app

查看:34
本文介绍了如何调试 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?

推荐答案

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

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).

适用于 Linux、Mac、适用于 Windows 的 Linux 子系统、适用于 Windows 的 Git Bash 等:

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

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

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

For Windows CMD, use set instead of export:

set FLASK_ENV=development

对于 PowerShell,使用 $env:

For PowerShell, use $env:

$env:FLASK_ENV = "development"

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

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

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

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.

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

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.

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

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

一定不要使用太宽泛的块,除了块.用一个包罗万象的 try... except... 包围你的所有代码将消除你想要调试的错误.通常没有必要,因为 Flask 已经通过显示调试器或 500 错误并将回溯打印到控制台来处理异常.

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.

这篇关于如何调试 Flask 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆