【问题标题】:Get content-length of FastAPI response获取 FastAPI 响应的内容长度
【发布时间】:2020-11-12 13:24:26
【问题描述】:

我试图在服务器端获取 FastAPI 响应的内容长度以用于日志记录。这可能吗?谢谢。

@app.get("/foo")
async def foo(background_tasks: BackgroundTasks):

  data = {"foo": "foo"}

  response_content_length = get_content_length()

  background_tasks.add_task(log, response_content_length ) 

  return data

【问题讨论】:

    标签: python-3.x fastapi


    【解决方案1】:

    您可以通过继承 APIRoute 类创建自己的路由,现在您应该可以记录所有内容,而无需重复自己。

    from fastapi import FastAPI, Request, Response, Body, BackgroundTasks, APIRouter
    from fastapi.routing import APIRoute
    
    from typing import Callable, List
    
    
    
    class ContextIncludedRoute(APIRoute):
        def get_route_handler(self) -> Callable:
            original_route_handler = super().get_route_handler()
    
            async def custom_route_handler(request: Request) -> Response:
    
                response: Response = await original_route_handler(request)
    
                content_length = response.headers["content-length"]
                print(content_length)
                
                return response
    
            return custom_route_handler
    
    
    app = FastAPI()
    router = APIRouter(route_class=ContextIncludedRoute)
    
    
    @router.post("/dummy")
    async def dummy():
        return {"foo":"foo"}
    
    
    app.include_router(router)
    

    【讨论】:

    • 我说的是响应而不是请求,但它也有助于部分回答
    • 有没有办法在同一个服务器调用的上下文中获取值,以便 Ill 知道它是哪个调用?
    • 你的意思是得到{"foo": "foo"}
    • 我的意思是将 dummy() 调用与 content_length 关联起来,这样我就可以将它们组合在一起形成一个日志行
    • 首先检查await request.body()是否可用添加它,如果不是它应该有查询,检查request.query_params并将其添加到日志中,您可以使用我以前的路径评论
    猜你喜欢
    • 2011-07-30
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2016-04-23
    相关资源
    最近更新 更多