FastAPI错误:Redis HashModel的响应字段的参数无效- Pydantic Issue

ni65a41a  于 12个月前  发布在  Redis
关注(0)|答案(1)|浏览(119)

我正在做一个FastAPI项目,我试图使用redis_om库中的HashModel类与Redis数据库交互。然而,我在为我的一个API端点定义响应模型时遇到了与Pydantic相关的问题。下面是我的代码:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from redis_om import get_redis_connection, HashModel

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=['http://localhost:3000'],
    allow_methods=['*'],
    allow_headers=['*'])

redis = get_redis_connection(
    host='redis-hos.cloud.redislabs.com',
    port='port',
    password='password',
    decode_responses=True)

class Product(HashModel):
    name: str
    price: float
    quantity: int

    class Meta:
        database = redis

@app.get("/")
async def root():
    return {"message": "Hello, World!"}

@app.get("/product")
def all():
    # Fetch and return all products
    products = Product.all()
    return products

@app.post("/addproduct")
async def create(product: Product):
    # Create a new Product instance and save it to Redis
    return product.save()

字符串
当我尝试运行这段代码时,我得到以下错误:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'main.Product'> is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None. Read more: https://fastapi.tiangolo.com/tutorial/response-model/


我已经检查了我的Product类,它似乎被正确地定义了必要的Pydantic字段。有人能帮助我理解为什么我会得到这个错误,以及如何解决它吗?谢谢!

gcuhipw9

gcuhipw91#

我也遇到了同样的问题。在系统中安装Pydantic v1而不是最新版本。最新版本的Pydantic不支持HashModel。

pip install pydantic==1.10.13

字符串
参考:https://github.com/redis/redis-om-python/issues/539

相关问题