代码之家  ›  专栏  ›  技术社区  ›  chenmodidi

为什么我的烧瓶错误处理程序在gunicorn中不起作用

  •  0
  • chenmodidi  · 技术社区  · 2 年前

    我有一个Flask应用程序,它使用蓝图来组织不同的模块。我在errors.py中定义了一个错误处理程序来处理500个错误,以呈现自定义的500页。

    @main.app_errorhandler(500)
    def internal_server_error(e):
        print 'yes'    
        return render_template('500.html'), 500
    

    当我使用Flask内置服务器运行我的应用程序时,这个错误处理程序运行良好,我可以看到 500.html 页但是当我用gunicorn运行我的应用程序时,这个错误处理程序不起作用,我看不到 500.html 页面,我只看到默认值 Internal Server Error 消息

    我尝试过以下方法,但都不起作用: 背景 PROPAGATE_EXCEPTIONS=True 在我的应用程序中,让Flask重新引发异常,而不是让gunicorn处理它们。 背景 DEBUG=True 在我的应用程序中,让Flask显示错误消息,而不是让gunicorn处理它们。 使用 app.config['PROPAGATE_EXCEPTIONS']=True 我使用的是gunicorn 20.1.0版本,我使用以下命令运行gunicorn:

    gunicorn -w 5 -t 60 -b 0.0.0.0:5000 manage:app
    

    有人知道为什么我的错误处理程序不能在gunicorn中工作吗?我该如何解决这个问题?非常感谢。

    0 回复  |  直到 2 年前
        1
  •  0
  •   zurgeg    2 年前

    我看到两个问题:

    1. 看起来像 print 缺少括号,这将导致语法错误
    2. 你似乎在使用一个不必要的变量。尝试更改 @main.app_errorhandler(500) @main.app.errorhandler(500)

    有了这些更改,带有此错误处理程序的最小烧瓶应用程序如下所示:

    from flask import Flask
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
        raise Exception
    
    @app.errorhandler(500)
    def internal_server_error(e):
        print('yes')    
        return 'It works!', 500
    
    
    if __name__ == '__main__':
        app.run(host='127.0.0.1', port=8000, debug=True)
    

    访问索引页面时,上面的代码显示“它有效!”。