long2ice / fastapi-cache

fastapi-cache is a tool to cache fastapi response and function result, with backends support redis and memcached.
https://github.com/long2ice/fastapi-cache
Apache License 2.0
1.28k stars 157 forks source link

fastapi-cache not converting back to Pydantic #236

Open titogarrido opened 1 year ago

titogarrido commented 1 year ago

Hi Folks,

I have a function that returns an user querying the username:

The endpoint:

@app.get("/users/u/{username}", response_model=schemas.Artist)
@cache(expire=180, key_builder=request_key_builder)
async def read_user(username: str, db: Session = Depends(get_db)) -> schemas.Artist:
    user = crud.get_user_by_username(db, username=username)
    if user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
    return user

The schemas.Artist:

class Artist(UserBase):
    id: int
    avatar: Optional[str]
    full_avatar: Optional[str]
    badges: List[Badge] = []
    posts: List[PostSeachResult] = []
    created_at: datetime
    website: Optional[str] = None
    bio: Optional[str] = None
    location: Optional[str] = None
    instagram: Optional[str] = None
    youtube: Optional[str] = None
    following_count: int
    followers_count: int
    posts_count: int

    class Config:
        orm_mode = True

When the first request queries the DB and writes in redis, the second one try to fetch from redis and I am receiving:

    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 3 validation errors for Artist
response -> following_count
  field required (type=value_error.missing)
response -> followers_count
  field required (type=value_error.missing)
response -> posts_count
  field required (type=value_error.missing)

It does not support orm_mode?

Thanks!

titogarrido commented 1 year ago

I just noticed that types that are other Pydantic classes are not added to cache...

titogarrido commented 1 year ago
class Post(PostBase):
    id: int
    author_id: int
    author: UserSimple = None
    category: Optional[PostCategory] = None
    created_at: datetime
    updated_at: Optional[datetime]
    visible: bool
    editors_choice: bool
    never_popular: bool
    full_cover: Optional[str] = None
    cover_position: Optional[str] = None
    visitors: Optional[int] = 0
    score: Optional[float] = 0
    bookmarks_count: Optional[int] = 0
    votes_count: Optional[int] = 0
    photos: List[PhotoFull] = []
    badges: List[Badge] = []

Another schema that is missing data, the "author" does not get cached.

mkdir700 commented 1 year ago

@long2ice It seems that this issue has already been resolved in the latest main branch, so when are we planning to release version 0.2.2?