如何解决在 FastAPI 中以编程方式创建端点时如何处理模型
以下示例都可以正常工作,唯一的问题是 mypy 抱怨 create_operation
。
具体来说,我收到了这些错误:
Variable "model" is not valid as a type
model? has no attribute "dict"
特别是第二个错误对我来说没有意义,因为 pydantic.BaseModel
绝对有一个 dict
方法。有没有更好的注释方法?
from typing import Type
from pydantic import BaseModel
from fastapi import FastAPI,testclient
app = FastAPI()
client = testclient.TestClient(app)
class A(BaseModel):
foo: str
# regular way of creating an endpoint
@app.post("/foo")
def post(data: A):
assert data.dict() == {"foo": "1"}
# creating an endpoint programmatically
def create_operation(model: Type[BaseModel]):
@app.post("/bar")
def post(data: model):
assert data.dict() == {"foo": "1"}
create_operation(A)
assert client.post("/foo",json={"foo": 1}).status_code == 200
assert client.post("/bar",json={"foo": 1}).status_code == 200
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。