我正在开发Flask应用程序,并希望在Flask启动之前记录命令请求和传出响应。为此,我使用WSGI的包装器。我让它适用于请求部分,但需要一些关于响应部分的指示。
这是我到目前为止的代码。
import logging
import pprint
from cStringIO import StringIO
log = logging.getLogger(__name__)
class WSGIRequestResponseLogging(object):
"""
This wrapper works independently from Flask and wraps the WSGI application. It shows exactly what
request is going in and what response is going out.
http://werkzeug.pocoo.org/docs/0.11/wrappers/
"""
def __init__(self, app):
self._app = app
def __call__(self, environ, start_response):
log.debug(pprint.pprint(('REQUEST', environ)))
if environ.get('REQUEST_METHOD') == 'POST':
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
if length == 0:
log.debug("REQUEST_BODY: EMPTY")
else:
body = environ['wsgi.input'].read(length)
log.debug("REQUEST_BODY: " + body)
# After reading the body it is removed, restore it
environ['wsgi.input'] = StringIO(body)
def log_response(status, headers, *args):
log.debug(pprint.pprint(('RESPONSE', pprint.pprint(('RESPONSE', status, headers)))))
return start_response(status, headers, *args)
return self._app(environ, log_response)
如何在log_response中记录响应正文?
问候,nidkil
答案 0 :(得分:2)
请参阅mod_wsgi网站上的示例代码:
它应该适用于任何WSGI服务器。
如果您使用mod_wsgi-express
,则会内置此审核功能。
mod_wsgi-express start-server --enable-recorder wsgi.py