gra*_*tur 12 python flask gunicorn
对于我的生活,当我通过gunicorn运行它时,我无法弄清楚我的Flask应用程序中的错误来自哪里,因为我无法弄清楚如何显示堆栈跟踪.
例如,假设我有一个非常简单的"Hello,World!" 用烧瓶写的应用程序.
import logging
import os
from flask import Flask
app = Flask(__name__)
app.debug = True
@app.route('/')
def hello():
raise Exception('Exception raised!')
return 'Hello World!'
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
如果我运行它python hello.py,那么一切都很好,因为我得到一个非常有用的堆栈跟踪:
(venv)142:helloflask $ python hello.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader
127.0.0.1 - - [30/Jun/2014 18:52:42] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/grautur/code/helloflask/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/grautur/code/helloflask/hello.py", line 10, in hello
raise Exception('Exception raised!')
Exception: Exception raised!
Run Code Online (Sandbox Code Playgroud)
但是,如果我创建一个Procfile
web: gunicorn hello:app
Run Code Online (Sandbox Code Playgroud)
然后启动应用程序foreman start -p 8000,然后我什么也看不见.只是一个"内部服务器错误"网页.
$ foreman start -p 8000
18:56:10 web.1 | started with pid 36850
(...nothing else is ever displayed...)
Run Code Online (Sandbox Code Playgroud)
如何让我的Flask + gunicorn应用程序显示更有用的调试消息?我尝试设置app.debug = True(及其各种迭代),因为它看起来像其他StackOverflow帖子建议,但它似乎没有改变任何东西.
我不熟悉Foreman,所以不确定是否需要以任何方式进行配置,但是对于Gunicorn记录任何内容,首先需要为Flask应用程序设置日志记录.
这样做的简单方法如下:
import logging
# Log only in production mode.
if not app.debug:
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
app.logger.addHandler(stream_handler)
Run Code Online (Sandbox Code Playgroud)
StreamHandler默认情况下记录到stderr.如果你想记录到文件中,Gunicorn具有--access-logfile和--error-logfile选项.
有关Flask错误处理的更多详细说明和一些好主意,请参阅文档.
| 归档时间: |
|
| 查看次数: |
5844 次 |
| 最近记录: |