python - FastApi 获取请求显示验证错误

标签 python api sqlalchemy fastapi pydantic

当我尝试从我的 postgre 数据库中获取一些数据并使用 fastapi 时出现此错误。

enter image description here

我不知道为什么会这样......但这是我的代码,谢谢你的帮助。

路线

@router.get("/fuentes", response_model=FuenteSerializer.MFuente) # <--- WHEN I REMOVE RESPONSE_MODEL WORKS AND RETURNS A JSON DATA DIRECTLY FROM MODEL I GUESS
    async def read_fuentes(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    fuentes = FuenteSerializer.get_fuente(db, skip=skip, limit=limit)
    return fuentes

sqlalchemy 模型

class MFuente(Base):
    __tablename__ = 'M_fuentes'

    idfuentes = Column(Integer, primary_key=True)
    idproductos = Column(ForeignKey('M_productos.idproductos', ondelete='RESTRICT', onupdate='RESTRICT'), index=True)
    autoapp = Column(CHAR(2))
    rutFabricante = Column(String(12))
    elemento = Column(String(100))
    estado = Column(Integer)
    stype = Column(Integer)
    aql = Column(String(5))
    equiv = Column(String(5))
    division = Column(String(100))
    nu = Column(Integer)
    filexcel = Column(String(100))

    M_producto = relationship('MProducto')

序列化器/模式

class MFuente(BaseModel):

    idfuentes: int
    autoapp: str
    fecregistro: datetime.date
    rutFabricante: str
    elemento: str
    estado: int
    stype: int
    aql: str
    equiv: str
    division: str
    fileexel: str
    productos: List[MProducto]

    class Config:
        orm_mode = True


def get_fuente(db: Session, skip: int = 0, limit: int = 100):
   return db.query(Fuente).offset(skip).limit(limit).all()

最佳答案

为了进行一些调试,我创建了相同的小原型(prototype),并找到了一些可能的答案。

首先是我创建的应用程序:

class MFuente(BaseModel):
    name: str
    value: int

@app.get("/items/{name}", response_model=MFuente)
async def get_item(name: str):
    query = fuente_db.select().where(fuente_db.c.name == name)
    return await database.fetch_all(query)

所以使用这个模式我得到了同样的错误

response -> name
  field required (type=value_error.missing)
response -> value
  field required (type=value_error.missing)

所以我调试了一点我发现它都是关于 response_model 的,所以我想出了这个:

from typing import List
...
@app.get("/items/{name}", response_model=List[MFuente])

一切开始工作:

INFO:     127.0.0.1:52872 - "GET /items/masteryoda HTTP/1.1" 200 OK

所以在你的情况下修复将是:

@router.get("/fuentes", response_model=List[FuenteSerializer.MFuente]) 
                                       ^^^^

关于python - FastApi 获取请求显示验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63004799/

相关文章:

Python:3.7-stretch unixodbc:冲突:unixodbc-bin

Python 参数绑定(bind)器

python - SQLAlchemy MySQL 复杂 ORDER BY

python - 如何制作启动Python脚本的Linux后台进程(在C中)

node.js - Nodejs twitter api 不返回预期的 token

api - huawei api短信文档

python - 从 JSON 中获取特定数据

python - MySQL - 如果表名称包含表列表的记录,则选择表名称

python - Python 中的 DynamoDB 查询(使用 GroupBy 进行计数)

Python:在字符串中查找字符串,然后返回其周围的字符串