The following examples both work just fine, the only issue is that mypy is complaing about create_operation. Specifically I'm getting these errors:
Variable "model" is not valid as a typemodel? has no attribute "dict"
Especially the second error doesn't make sense to me since pydantic.BaseModel definitely has a dict method. Is there a better way to annotate this?
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 https://stackoverflow.com/questions/66481304/how-to-handle-models-when-programmatically-creating-endpoints-in-fastapi March 05, 2021 at 02:53AM
没有评论:
发表评论