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

问题描述 投票:58回答:5

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

Ops-wise,一切正常 - 我遇到的问题是调试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运行烧瓶应用程序:

gunicorn -c gunicorn.conf.py testserver:app

谢谢你们

python flask gunicorn
5个回答
72
投票

接受解决方案对我不起作用。

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

Attention

即使交互式调试器在分叉环境中不起作用(这使得它几乎不可能在生产服务器上使用)[...]

即使你设置了app.debug = True,如果你使用gunicorn testserver:app运行,你仍然只会得到一个带有内部服务器错误消息的空白页面。用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。为了让这个工作:

Contents of Procfile

web: bin/web

Contents of bin/web, file is relative to project root

#!/bin/sh

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

In development, create a .env file relative to project root with the following contents (docs here)

FLASK_ENV=development
DEBUG=True

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

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

44
投票

Flask配置完全独立于gunicorn。在the Flask documentation on config files之后,一个好的解决方案是改变我的来源:

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

在config.py中:

DEBUG = True

23
投票

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

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


0
投票

尝试在运行命令上设置调试标志,如下所示

gunicorn -c gunicorn.conf.py --debug testserver:app

并将DEBUG = True保存在Flask应用程序中。必须有一个原因,你的调试选项没有从配置文件中应用,但现在上面的说明应该让你去。


0
投票

我在gunicorn下运行烧瓶时遇到类似问题我没有在浏览器中看到堆栈跟踪(每次都必须查看日志)。设置DEBUG,FLASK_DEBUG或此页面上提到的任何内容都不起作用。最后我这样做了:

app = Flask(__name__)
app.config.from_object(settings_map[environment])
if environment == 'development':
    from werkzeug.debug import DebuggedApplication
    app_runtime = DebuggedApplication(app, evalex=False)
else:
    app_runtime = app

注意evalex被禁用,因为交互式debbugging不适用于分叉(gunicorn)。

© www.soinside.com 2019 - 2024. All rights reserved.