schemas.py
class ExpenseBase(BaseModel):
Fixed: float
Variable: float
Salary: float
month: int
year: int
class Expense(ExpenseBase):
class Config:
arbitrary_types_allowed = True
orm_mode = True
class ExpenseSingle(BaseModel):
__root__: Expense
class Config:
arbitrary_types_allowed = True
orm_mode = True
In my main.py
:
from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from . import api, models, schemas
from .database import SessionLocal, engine
[...]
@app.get('/expense/{id}/', response_model=schemas.ExpenseSingle)
def read_expense(id: int, db: Session = Depends(get_db)):
if id is None or isinstance(id, int) is not int:
raise HTTPException(status_code=400, detail="ID is not int")
expense = api.get_expense_by_id(db, id=id)
return expense
but I get the following error when I try to get that API endpoint:
pydantic.error_wrappers.ValidationError: 1 validation error for ExpenseSingle
response
none is not an allowed value (type=type_error.none.not_allowed)
I have tried to change schemas.py
, to this:
class ExpenseSingle(BaseModel):
reponse: None
class Config:
arbitrary_types_allowed = True
orm_mode = True
I can't understand where it should be fixed - looks like I didn't understand how pydantic
and fastapi
relate to each other...
This was solved when I started to handle empty ( None
) responses from the database with the following code:
if not expense:
raise HTTPException(status_code=404, detail="No Expenses found")
return expense
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.