【问题标题】:Logging response body in Flask WSGI request/response wrapper在 Flask WSGI 请求/响应包装器中记录响应正文
【发布时间】:2017-05-19 02:37:03
【问题描述】:

我正在开发一个 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

【问题讨论】:

    标签: flask wsgi werkzeug


    【解决方案1】:

    查看 mod_wsgi 网站上的示例代码:

    它应该适用于任何 WSGI 服务器。

    如果您使用的是mod_wsgi-express,则此审核功能是内置的。

    mod_wsgi-express start-server --enable-recorder wsgi.py
    

    【讨论】:

    • 像梦一样工作。谢谢格雷厄姆!
    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2021-07-21
    • 2014-02-15
    • 2019-05-17
    • 1970-01-01
    • 2017-02-21
    • 2019-08-01
    • 1970-01-01
    相关资源
    最近更新 更多