Git Product home page Git Product logo

Comments (3)

a-luna avatar a-luna commented on June 12, 2024 2

I recently ran into this issue myself! From your code snippet it appears that you may have tried the same fix and indicated that it didn't solve the issue. Here is an endpoint where I was encountering the same error:

@router.get("/details", response_model=PlayerSchema)
@cache()
def get_player_details(mlb_id: int, app = Depends(get_app)):
    return get_player(mlb_id, app)

PlayerSchema is a pydantic model class for a SQLAlchemy model class named Player, and get_player retrieves the requested Player object from the database. This endpoint works perfectly, until the @cache decorator is added and the FAILED_TO_CACHE_KEY errors start to appear.

The fix I found was to manually convert the SQLAlchemy type to a dict using the from_orm method of the pydantic model class as shown below:

def convert_player_to_dict(player: Player) -> Dict[str, Union[str, int]]:
    return PlayerSchema.from_orm(player).dict()

Player is a SQLAlchemy model class, PlayerSchema is a pydantic model class, and player is an instance of Player. I simply wrapped the get_player function with convert_player_to_dict as shown below and everything is being cached as expected:

@router.get("/details", response_model=PlayerSchema)
@cache()
def get_player_details(mlb_id: int, app = Depends(get_app)):
    return convert_player_to_dict(get_player(mlb_id, app))

Let me know if this works!

from fastapi-redis-cache.

b-simjoo avatar b-simjoo commented on June 12, 2024 1

Hi everybody, I have the same issue and have to edit BetterJsonEncoder and make it even more better!

from fastapi-redis-cache.

Ezhvsalate avatar Ezhvsalate commented on June 12, 2024

@a-luna, thanks for your response.

I tried your type of fix too and it doesn't work for me: I get the following:

 FAILED_TO_CACHE_KEY: Object of type <class 'dict'> is not JSON-serializable: key=cache:prj.api
.routes.dictionaries.bjcp_styles.get_bjcp_style_by_id(id=49895337-df68-4d07-819b-f08ebabfefaa)

After some hacking I found the reason in JSON encoder and modified a fastapi_redis_cache.util.BetterJsonEncoder in such way:

from uuid import UUID
from enum import Enum
prom pydantic import BaseModel

class BetterJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return {"val": obj.strftime(DATETIME_AWARE), "_spec_type": str(datetime)}
        elif isinstance(obj, date):
            return {"val": obj.strftime(DATE_ONLY), "_spec_type": str(date)}
        elif isinstance(obj, Decimal):
            return {"val": str(obj), "_spec_type": str(Decimal)}
        elif isinstance(obj, BaseModel):
            return obj.dict()
        elif isinstance(obj, UUID):
            return str(obj)
        elif isinstance(obj, Enum):
            return str(obj.value)
        else:  # pragma: no cover
            return super().default(obj)

So it can handle Enums and UUIDs, and we don't more need to use .dict() (it's included in encoder, but will cause Pydantic as dependency so make this decision yourself plz).
Anyway I couldn't get rid of PydanticModel.from_orm() cause we don't know what pydantic class should be parsed from ORM model.

And one more thing: I saw your mapping with additional '_spec_type' fields but have no idea why it will be required in this case.
Hope that will help :)

from fastapi-redis-cache.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.