Flask如何在after_request中打印所有响应并不破坏swagger-ui?

0 投票
1 回答
18 浏览
提问于 2025-04-12 22:57

设置:

  • connexion[swagger-ui]==2.13.0
  • Flask==2.2.5

我正在使用connexion(不是直接使用Flask)来搭建我的应用并托管swagger。我想在发送每个请求和响应的内容之前,把它们打印到控制台上。

在构建我的connexion应用后,我尝试使用了这些

# Add pre payload printer to app
connex_app.app.before_request(print_request(config))
connex_app.app.after_request(print_response(config))

这些是我用的函数

def print_request(config):
    '''
    Print out requests received, or response sent
    '''
    def request_logger():
        if request.method not in ('GET'):
            if config.myproject.logging.myproject.pretty_print.request_payloads:
                logger.debug(f"Request received, Body: {request.get_data(as_text=True)}")
            else:
                data = request.get_json() if request.is_json else {}
                flat_json = json.dumps(data, separators=(',', ':'))
                logger.debug(f"Request received, Body: {flat_json}")
        else:
            logger.debug("Request received")

    return request_logger

def print_response(config):
    '''
    Print out requests received, or response sent
    '''
    def response_logger(response):
        # Ensure you have access to the correct response object here, this might need to be passed explicitly
        if config.myproject.logging.myproject.pretty_print.response_payloads:
            logger.debug(f"Response sent, Body: {response.get_data(as_text=False)}")
        else:
            # This section might need adjustment based on how you're handling response data
            data = response.get_json() if response.is_json else {}
            flat_json = json.dumps(data, separators=(',', ':'))
            logger.debug(f"Response sent, Body: {flat_json}")
        return response

    return response_logger

问题出在这一行

logger.debug(f"Response sent, Body: {response.get_data(as_text=False)}")

出于某种原因,它试图将swagger-ui的请求和响应重定向到它的界面,这样就导致了swagger-ui的崩溃。这让我感到很奇怪,因为我昨天没有遇到这个问题。我之前的connexion依赖版本是2.*,而且我不知道之前使用的具体版本是什么。我现在没有时间把所有代码都改成使用connexion 3.0,所以这不是一个选项。此外,我还必须将Flask==2.2.5设置为这个版本,因为新版本有个JSON编码的问题。

有没有人遇到过类似的情况?我打印响应的方式正确吗?有没有更好的方法?

我觉得这可能是个依赖问题,但我不太确定该怎么解决...

1 个回答

0

我放弃了不破坏swagger的情况下让这个功能正常工作。我禁用了这个方法,最后自己写了一个装饰器,然后把它加到我想要打印响应的每个路由路径上。这不是一个很好的解决办法,但满足了我的需求。

撰写回答