python-3.x 无法更新Fastapi

f0brbegy  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(134)

当我用下面的代码从FastAPI文档运行put时,我得到500 Error: Internal Server Error,终端显示

{'type': 'missing', 'loc': ('response', 'id'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}
  {'type': 'missing', 'loc': ('response', 'type'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}
  {'type': 'missing', 'loc': ('response', 'create_uid'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}
  {'type': 'missing', 'loc': ('response', 'create_date'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}
  {'type': 'missing', 'loc': ('response', 'view_post'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}
  {'type': 'missing', 'loc': ('response', 'is_published'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}
  {'type': 'missing', 'loc': ('response', 'rate'), 'msg': 'Field required', 'input': {'data': <app.models.post.post_models.Post object at 0x0000019CAA6C4310>, 'message': 'C\u1eadp nh\u1eadp bài \u0111\u0103ng có 1 thành công'}, 'url': 'https://errors.pydantic.dev/2.4/v/missing'}

字符串

型号:

class Post(Base):
    __tablename__ = 'post'

    id = Column(BIGINT, primary_key=True, nullable=False)
    type = Column(VARCHAR, nullable=False)
    content_post = Column(TEXT, nullable=True)
    description_post = Column(TEXT, nullable=True)
    create_uid = Column(BIGINT, nullable=False)
    create_date = Column(TIMESTAMP, nullable=False)
    view_post = Column(BIGINT, nullable=True)
    is_published = Column(Boolean, nullable=False)
    rate = Column(BIGINT, nullable=False)
    image_filename = Column(VARCHAR, nullable=True)
    image_url = Column(VARCHAR, nullable=True)

架构

class PostResponse(BaseModel):
    id: int
    type: str
    content_post: str | None = None
    description_post: str | None = None
    create_uid: int
    create_date: datetime.datetime
    view_post: int
    is_published: bool
    rate: int
    image_filename: str | None = None
    image_url: str | None = None

服务

def update_post(db: Session, post: PostResponse):
   post_query = db.query(Post).filter(or_(Post.id == post.id)).first()
   if post_query is None:
       raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Bản ghi có {id} không tồn tại")
   else:
       try:
           post_query.id = post.id
           post_query.type = post.type
           post_query.content_post = post.content_post
           post_query.description_post = post.description_post
           post_query.create_uid = post.create_uid
           post_query.create_date = post.create_date
           post_query.view_post = post.view_post
           post_query.is_published = post.is_published
           post_query.rate = post.rate
           db.commit()
           return {
               "data": post_query,
               "message": f"Cập nhập bài đăng có {post.id} thành công"
           }
       except Exception as e:
            db.rollback()
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
                                detail=e)

路由器

@router.post('/update-post', response_model=PostResponse)
def update_post(post: PostResponse, db: Session = Depends(get_db)):
    return post_service.update_post(db, post)


我的要求:

{
  "id": 1,
  "type": "Python",
  "content_post": "string",
  "description_post": "string",
  "create_uid": 0,
  "create_date": "2023-11-09T01:50:54.344Z",
  "view_post": 0,
  "is_published": true,
  "rate": 1
}

bvk5enib

bvk5enib1#

您遇到的错误消息表明FastAPI应用程序预期的响应对象中缺少某些字段。这与Pydantic有关,Pydantic是FastAPI用于数据验证的库。每个错误消息都明确指出响应对象中缺少的字段。让我们分解问题及其潜在解决方案:
1.**响应对象中缺少字段:**错误消息表示响应对象中缺少idtypecreate_uidcreate_dateview_postis_publishedrate等字段,这表明您在服务层的update_post函数返回的响应不符合PostResponse架构。
1.**返回类型不匹配:**您在服务层的update_post函数返回了一个字典,其中包含键"data""message",但您的PostResponse模型需要直接属性,如idtype等。您需要确保您的update_post函数返回的对象与PostResponse定义的结构匹配。

*潜在解决方案:

  • 修改你的update_post函数以返回PostResponse的一个示例而不是一个字典。这样可以确保响应与预期的模式相匹配。
  • 您可以使用post_query中的数据创建一个新的PostResponse示例,然后返回它。

下面是update_post函数的修改版本:

def update_post(db: Session, post: PostResponse):
   post_query = db.query(Post).filter(or_(Post.id == post.id)).first()
   if post_query is None:
       raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Bản ghi có {id} không tồn tại")
   else:
       try:
           # Update the post record as before
           # ...

           db.commit()

           # Create a new PostResponse instance with updated data
           updated_post_response = PostResponse(
               id=post_query.id,
               type=post_query.type,
               content_post=post_query.content_post,
               description_post=post_query.description_post,
               create_uid=post_query.create_uid,
               create_date=post_query.create_date,
               view_post=post_query.view_post,
               is_published=post_query.is_published,
               rate=post_query.rate,
               image_filename=post_query.image_filename,
               image_url=post_query.image_url
           )
           return updated_post_response

       except Exception as e:
           db.rollback()
           raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
                               detail=e)

字符串
确保PostResponse的属性与Post模型的字段匹配。如果不匹配,则需要相应地Map它们。此修改应解决预期响应模型与返回的实际响应之间的不匹配。

相关问题