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

标签 python flask gunicorn

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

在操作方面,一切正常 - 我遇到的问题是调试 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

谢谢大家

最佳答案

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

Gunicorn 是一个预 fork 环境,显然是 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 运行,你仍然只会得到一个带有 Internal Server Error 消息的空页面:应用程序。使用 gunicorn 可以做的最好的事情是使用 gunicorn --debug testserver:app 运行它。除了 Internal Server Error 消息之外,这还为您提供了跟踪信息。但是,这只是您在终端中看到的相同文本跟踪,而不是 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`,因为[它为我设置了所有环境变量](https://devcenter.heroku.com/articles/config-vars#using-领类)。要让它工作:

Procfile的内容

web: bin/web

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

#!/bin/sh

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

在开发中,创建一个相对于项目根目录的 .env 文件,内容如下(文档 here)

FLASK_ENV=development
DEBUG=True

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

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

关于python - 调试在 Gunicorn 中运行的 Flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8950674/

相关文章:

python - 读取 txt 矩阵时,如何跳过第一列

python - 在线程中引发异常

python - 为什么基于生成器的协程是消费者,异步生成器是异步数据生产者,而协程是异步数据消费者?

python - 导入错误: cannot import name CKParser

javascript - 无法使用 D3.js 读取外部文件

django - 连接到 Sock 文件失败。资源暂时不可用

nginx - 无法在 systemd 203/EXEC 中将 Gunicorn 作为服务运行

python - django-tastypie : Related data not saving

python - Django 使用 'python manage.py' runserver 代替 Gunicorn

python - python如何在其中找到装饰函数?