fastapi中需要的pydantic验证错误字段
在FastAPI应用中,我在尝试通过此端点获取数据时遇到了此错误:
@app.get(
"/users/{telegram_id}",
response_model=schemas.UserBase,
tags=["user"],
status_code=status.HTTP_200_OK,
)
def read_user(telegram_id: int, db: Session = Depends(get_db)):
"""Read user by telegram id."""
db_user = crud.get_user(db, user_telegram_id=telegram_id)
if db_user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
)
return db_user
路由器为:
def get_user(db: Session, user_telegram_id: int):
"""GEt user by telegram id."""
return (
db.query(models.User)
.filter(models.User.telegram_id == user_telegram_id)
.first()
)
schemas as:
class UserArticlesSentView(BaseModel):
"""What fields will be in nested sent_articles list."""
id: int
# sent_articles: List[ArticleSentView] = []
class Config:
"""Enable ORM mode."""
orm_mode = True
class UserBase(BaseModel):
"""Base serializer for a user."""
id: int
telegram_id: int = Field(..., ge=0)
username: str = Field(..., max_length=50)
pet_name: str = Field(..., max_length=50)
language_code: str = Field(..., max_length=3, min_length=2)
sent_articles: List[UserArticlesSentView] = []
class Config:
"""Enable ORM mode for all child methods."""
orm_mode = True
用户库Pydantic模型包含send_articles字段,该字段必须包含带有“ id”:value的dicts列表。
验证错误是:
pydantic.error_wrappers.ValidationError: 2 validation errors for UserBase
response -> sent_articles -> 0 -> id
field required (type=value_error.missing)
response -> sent_articles -> 1 -> id
field required (type=value_error.missing)
此错误导致用户基架模式中的字段“ send_articles”。我不明白为什么。
我的型号
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
telegram_id = Column(Integer, unique=True, index=True)
username = Column(String(50))
pet_name = Column(String(50))
language_code = Column(String(5))
sent_articles = relationship("Log", back_populates="sent_to_user")
class Article(Base):
__tablename__ = "articles"
id = Column(Integer, primary_key=True, index=True)
text = Column(String(1024))
image_url = Column(String(500))
language_code = Column(String(255), index=True)
sent_to_user = relationship("Log", back_populates="sent_articles")
class Log(Base):
__tablename__ = "sent_log"
user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
sent_to_user = relationship("User", back_populates="sent_articles")
article_id = Column(Integer, ForeignKey("articles.id"), primary_key=True)
sent_articles = relationship("Article", back_populates="sent_to_user")
sent_time = (Column(DateTime(), server_default=text("NOW()")))
如何解决?
In FastAPI app I got this error while trying to fetch data by this endpoint:
@app.get(
"/users/{telegram_id}",
response_model=schemas.UserBase,
tags=["user"],
status_code=status.HTTP_200_OK,
)
def read_user(telegram_id: int, db: Session = Depends(get_db)):
"""Read user by telegram id."""
db_user = crud.get_user(db, user_telegram_id=telegram_id)
if db_user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
)
return db_user
Router is:
def get_user(db: Session, user_telegram_id: int):
"""GEt user by telegram id."""
return (
db.query(models.User)
.filter(models.User.telegram_id == user_telegram_id)
.first()
)
Schemas are:
class UserArticlesSentView(BaseModel):
"""What fields will be in nested sent_articles list."""
id: int
# sent_articles: List[ArticleSentView] = []
class Config:
"""Enable ORM mode."""
orm_mode = True
class UserBase(BaseModel):
"""Base serializer for a user."""
id: int
telegram_id: int = Field(..., ge=0)
username: str = Field(..., max_length=50)
pet_name: str = Field(..., max_length=50)
language_code: str = Field(..., max_length=3, min_length=2)
sent_articles: List[UserArticlesSentView] = []
class Config:
"""Enable ORM mode for all child methods."""
orm_mode = True
UserBase pydantic model contains sent_articles field that must have a list of dicts with "id": value.
A validation error is:
pydantic.error_wrappers.ValidationError: 2 validation errors for UserBase
response -> sent_articles -> 0 -> id
field required (type=value_error.missing)
response -> sent_articles -> 1 -> id
field required (type=value_error.missing)
This error causes field "sent_articles" in UserBase schema. I do not understand why.
My models.py
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
telegram_id = Column(Integer, unique=True, index=True)
username = Column(String(50))
pet_name = Column(String(50))
language_code = Column(String(5))
sent_articles = relationship("Log", back_populates="sent_to_user")
class Article(Base):
__tablename__ = "articles"
id = Column(Integer, primary_key=True, index=True)
text = Column(String(1024))
image_url = Column(String(500))
language_code = Column(String(255), index=True)
sent_to_user = relationship("Log", back_populates="sent_articles")
class Log(Base):
__tablename__ = "sent_log"
user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
sent_to_user = relationship("User", back_populates="sent_articles")
article_id = Column(Integer, ForeignKey("articles.id"), primary_key=True)
sent_articles = relationship("Article", back_populates="sent_to_user")
sent_time = (Column(DateTime(), server_default=text("NOW()")))
How to solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论