gpt4 book ai didi

python - fastapi 自定义响应类作为默认响应类

转载 作者:行者123 更新时间:2023-12-02 02:38:36 25 4
gpt4 key购买 nike

我正在尝试使用自定义响应类作为 default response .

from fastapi.responses import Response
from bson.json_util import dumps

class MongoResponse(Response):
def __init__(self, content, *args, **kwargs):
super().__init__(
content=dumps(content),
media_type="application/json",
*args,
**kwargs,
)

当我明确使用响应类时,这工作得很好。

@app.get("/")
async def getDoc():
foo = client.get_database('foo')
result = await foo.bar.find_one({'author': 'fool'})
return MongoResponse(result)

但是,当我尝试将其作为参数传递给 FastAPI 构造函数时,仅在从请求处理程序返回数据时似乎不会使用它。

app = FastAPI(default_response_class=MongoResponse)

@app.get("/")
async def getDoc():
foo = client.get_database('foo')
result = await foo.bar.find_one({'author': 'fool'})
return result

当我查看下面的堆栈跟踪时,它似乎仍在使用正常的默认响应,即 json response .

ERROR:    Exception in ASGI application
Traceback (most recent call last):
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 390, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/fastapi/applications.py", line 181, in __call__
await super().__call__(scope, receive, send) # pragma: no cover
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/applications.py", line 111, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/fastapi/routing.py", line 199, in app
is_coroutine=is_coroutine,
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/fastapi/routing.py", line 122, in serialize_response
return jsonable_encoder(response_content)
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/fastapi/encoders.py", line 94, in jsonable_encoder
sqlalchemy_safe=sqlalchemy_safe,
File "/home/blue/podman/test/.venv/lib/python3.6/site-packages/fastapi/encoders.py", line 139, in jsonable_encoder
raise ValueError(errors)
ValueError: [TypeError("'ObjectId' object is not iterable",), TypeError('vars() argument must have __dict__ attribute',)]

最佳答案

事实证明,默认响应类以及路由上的响应类仅适用于开放 API 文档。默认情况下,文档将记录每个端点,就像它们返回 json 一样。

因此,使用下面的示例代码,每个响应都将被标记为内容类型 text/html。在第二次路由中,这被 application/json 覆盖

app = FastAPI(default_response_class=HTMLResponse)

@app.get("/")
async def getDoc():
foo = client.get_database('foo')
result = await foo.bar.find_one({'author': 'Mike'})
return MongoResponse(result)


@app.get("/other", response_class=JSONResponse)
async def json():
return {"json": "true"}

image

从这个意义上说,我可能应该显式使用我的类并将默认响应类保留为 JSON,以便将它们记录为 JSON 响应。

关于python - fastapi 自定义响应类作为默认响应类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63960879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com