调试在Gunicorn中运行的Flask应用程序

2024-05-02 16:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在开发一个新的开发平台,我的应用程序使用nginx/gunicorn和Flask。

操作上,一切都很好-我的问题是调试烧瓶层。当我的代码中有错误时,我只得到一个直接返回到浏览器的500个错误,在控制台或我的日志中没有任何显示。

我试过很多不同的配置/选项。。我想我肯定漏掉了一些显而易见的东西。

我的gunicorn.conf:

import os

bind = '127.0.0.1:8002'
workers = 3
backlog = 2048
worker_class = "sync"
debug = True
proc_name = 'gunicorn.proc'
pidfile = '/tmp/gunicorn.pid'
logfile = '/var/log/gunicorn/debug.log'
loglevel = 'debug'

borks-testserver.py的一些Flask代码示例:

from flask import Flask
from flask import render_template_string
from werkzeug.contrib.fixers import ProxyFix

app = Flask(__name__)

@app.route('/')
def index():
    n = 1/0
    return "DIV/0 worked!"

最后,在gunicorn中运行flask应用程序的命令是:

gunicorn -c gunicorn.conf.py testserver:app

谢谢你们


Tags: 代码namefromdebugimportlogapp应用程序
3条回答

接受溶液对我不起作用。

Gunicorn是一个预分叉环境,显然是the Flask debugger doesn't work in a forking environment

Attention

Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers) [...]

即使您设置了app.debug = True,如果您使用gunicorn testserver:app运行,您仍然只能得到一个带有消息Internal Server Error的空页面。使用gunicorn的最佳方法是使用gunicorn --debug testserver:app运行它。除了内部服务器错误消息之外,还提供了跟踪。但是,这只是您在终端中看到的相同的文本跟踪,而不是Flask调试器。

if __name__ ...部分添加到testserver.py并运行python testserver.py以启动正在开发的服务器,这将为您提供Flask调试器。换句话说,如果需要Flask调试器,不要在开发中使用gunicorn。

app = Flask(__name__)
app.config['DEBUG'] = True

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


Heroku用户的提示:

就我个人而言,我仍然喜欢使用foreman start,而不是python testserver.py,因为it sets up all the env variables for me。要让它工作:

Procfile

的含量
web: bin/web

bin/web的内容,文件相对于项目根

#!/bin/sh

if [ "$FLASK_ENV" == "development" ]; then
        python app.py
else
        gunicorn app:app -w 3
fi

在开发过程中,创建一个与项目根目录相关的.env文件,其内容如下(docshere

FLASK_ENV=development
DEBUG=True

另外,不要忘记将testserver.py中的app.config['DEBUG']...行更改为在生产中不在调试模式下运行Flask的行。

app.config['DEBUG'] = os.environ.get('DEBUG', False)

烧瓶配置与gunicorn的完全不同。在the Flask documentation on config files之后,一个好的解决方案是将源更改为:

app = Flask(__name__)
app.config.from_pyfile('config.py')

在config.py中:

DEBUG = True

对于Heroku用户来说,有一个比创建Nick建议的bin/web脚本更简单的解决方案。

如果要在开发中调试应用程序,请使用foreman run python app.py,而不是foreman start

相关问题 更多 >