代码之家  ›  专栏  ›  技术社区  ›  Data Mastery

FastAPI-GET请求导致typeerror(值不是有效的dict)

  •  0
  • Data Mastery  · 技术社区  · 3 年前

    这是我的数据库模式。

    enter image description here

    我这样定义了我的模式:

    class Userattribute(BaseModel):
        name: str
        value: str
        user_id: str
        id: str
    

    class Userattribute(Base):
        __tablename__ = "user_attribute"
    
        name = Column(String)
        value = Column(String)
        user_id = Column(String)
        id = Column(String, primary_key=True, index=True)
    

    在crud.py中,我定义了 get_attributes 方法

    def get_attributes(db: Session, skip: int = 0, limit: int = 100):
        return db.query(models.Userattribute).offset(skip).limit(limit).all()
    

    这是我的 GET 终点:

    @app.get("/attributes/", response_model=List[schemas.Userattribute])
    def read_attributes(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
        users = crud.get_attributes(db, skip=skip, limit=limit)
        print(users)
        return users
    

    与数据库的连接似乎正常,但数据类型存在问题:

    pydantic.error_wrappers.ValidationError: 7 validation errors for Userattribute
    response -> 0
      value is not a valid dict (type=type_error.dict)
    response -> 1
      value is not a valid dict (type=type_error.dict)
    response -> 2
      value is not a valid dict (type=type_error.dict)
    response -> 3
      value is not a valid dict (type=type_error.dict)
    response -> 4
      value is not a valid dict (type=type_error.dict)
    response -> 5
      value is not a valid dict (type=type_error.dict)
    response -> 6
      value is not a valid dict (type=type_error.dict)
    

    为什么FASTApi希望这里有一本字典?我真的不明白,因为我甚至无法打印出回复。我怎样才能解决这个问题?

    1 回复  |  直到 3 年前
        1
  •  1
  •   MatsLindh    3 年前

    SQLAlchemy不会返回字典,这是pydantic在默认情况下所期望的。您可以将模型配置为还支持从标准orm参数(即对象上的属性,而不是字典查找)加载:

    class Userattribute(BaseModel):
        name: str
        value: str
        user_id: str
        id: str
    
        class Config:
            orm_mode = True
    

    您还可以在调用之前附加调试器 return 看看有什么被退回。

    推荐文章