我对我的 fastapi 终端点发生异常的原因是什么?

huangapple go评论147阅读模式
英文:

Why i take an exception with my endpoint fastapi?

问题

I have translated the code for you:

我有一个类似的数据库:
```python
class NewsBase(BaseModel):
    title: str
    topic: str


class NewsCreate(NewsBase):
    datetime: datetime


class News(NewsBase):
    id: int
    datetime: datetime

    class Config:
        orm_mode = True

当我尝试发出此请求时,它返回500错误:

@app.get("/news/find_by_topic/{topic}", response_model=schemas.News)
def find_news_by_topic(topic: str, db: Session = Depends(get_db)):
    db_news = crud.get_news_by_topic(db, topic=topic)
    if db_news is None:
        raise HTTPException(status_code=404, detail="This title is not found")
    return db_news

Crud.py:

def get_news_by_topic(db: Session, topic: str):
    return db.query(models.News).filter(models.News.topic == topic).all()

这是一个错误信息:

 File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
    raise exc
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 20, in __call__
    raise e
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 17, in __call__
    await self.app(scope, receive, send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\routing.py", line 66, in app
    response = await func(request)
               ^^^^^^^^^^^^^^^^^^^
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\routing.py", line 291, in app
    content = await serialize_response(
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\routing.py", line 154, in serialize_response
    raise ResponseValidationError(
fastapi.exceptions.ResponseValidationError

如何修复它?

英文:

I have got an db like:

class NewsBase(BaseModel):
    title: str
    topic: str


class NewsCreate(NewsBase):
    datetime: datetime


class News(NewsBase):
    id: int
    datetime: datetime

    class Config:
        orm_mode = True

When i try to make this request, it returns with 500:

@app.get("/news/find_by_topic/{topic}", response_model=schemas.News)
def find_news_by_topic(topic: str, db: Session = Depends(get_db)):
    db_news = crud.get_news_by_topic(db, topic=topic)
    if db_news is None:
        raise HTTPException(status_code=404, detail="This title is not found")
    return db_news

Crud.py:

def get_news_by_topic(db: Session, topic: str):
    return db.query(models.News).filter(models.News.topic == topic).all()

It's like error:

 File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
    raise exc
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 20, in __call__
    raise e
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 17, in __call__
    await self.app(scope, receive, send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "C:\Projects\RestAPI\venv\Lib\site-packages\starlette\routing.py", line 66, in app
    response = await func(request)
               ^^^^^^^^^^^^^^^^^^^
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\routing.py", line 291, in app
    content = await serialize_response(
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Projects\RestAPI\venv\Lib\site-packages\fastapi\routing.py", line 154, in serialize_response
    raise ResponseValidationError(
fastapi.exceptions.ResponseValidationError

How can I fix it?

答案1

得分: 2

It seems like you need to set response_model properly. Read more here.

If you are using Python 3.9:

response_model=list[schemas.News]

If you are using older Python:

from typing import List

response_model=List[schemas.News]

英文:

It seems like you need to set response_model properly. Read more here.

If you are using Python 3.9:

response_model=list[schemas.News]

If you are using older Python:

from typing import List

response_model=List[schemas.News]

huangapple
  • 本文由 发表于 2023年7月18日 16:30:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定