admin管理员组文章数量:1516870
I encountered the following error while working with FastAPI and Pydantic and SlowApi:
pydantic.errors.PydanticUserError: `TypeAdapter[typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]]` is not fully defined; you should define `typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]` and all referenced types, then call `.rebuild()` on the instance.
Here is my code:
@app.post("/info")
@limiter.limit("5/minute")
async def random_function(
info: Data,
request: Request,
) -> ResponseModel:
if info.name == "test":
return ResponseModel(id=1)
return ResponseModel(id=2)
I noticed that:
- When I remove the rate limiter, the Swagger docs work fine.
- If I remove
Datafrom the function parameters and keep onlyRequestalong with the rate limiter, it also works.
i tried
- , explicitly call
.model_rebuild()on my Pydantic models to resolve forward references. but it didn't slove it
I encountered the following error while working with FastAPI and Pydantic and SlowApi:
pydantic.errors.PydanticUserError: `TypeAdapter[typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]]` is not fully defined; you should define `typing.Annotated[ForwardRef('ResponseModel'), FieldInfo(annotation=ForwardRef('ResponseModel'), required=True)]` and all referenced types, then call `.rebuild()` on the instance.
Here is my code:
@app.post("/info")
@limiter.limit("5/minute")
async def random_function(
info: Data,
request: Request,
) -> ResponseModel:
if info.name == "test":
return ResponseModel(id=1)
return ResponseModel(id=2)
I noticed that:
- When I remove the rate limiter, the Swagger docs work fine.
- If I remove
Datafrom the function parameters and keep onlyRequestalong with the rate limiter, it also works.
i tried
- , explicitly call
.model_rebuild()on my Pydantic models to resolve forward references. but it didn't slove it
1 Answer
Reset to default 0- After debugging, I found that the issue was caused by the following import:
from _future_ import annotations
When I removed this import, the issue was resolved.
The error occurs because `from _future_ import annotations` enables postponed evaluation of type hints, which can interfere with Pydantic's handling of forward references in certain cases.
To fix this issue:
- Remove the from _future_ import annotations import if it's not necessary.
本文标签:
版权声明:本文标题:I encountered a Swagger error when using from __future__ import annotations with Pydantic, FastAPI, and SlowAPI in my project - 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.betaflare.com/web/1744473175a2607922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论