Comments (3)
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.
Hi everybody, I have the same issue and have to edit BetterJsonEncoder
and make it even more better!
from fastapi-redis-cache.
@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)
- eTag generation should be optional and configured via a global setting AND a setting per-endpoint
- cache-control: no-cache behavior is wrong HOT 1
- user can add must-revalidate directive to responses
- add support for if-modified-since directive
- ttl expired -> request contains eTag/last-mod -> current behavior is wrong
- feature: provide method on `FastApiRedisCache` object that allows user to delete single cache items by key HOT 1
- Nothing being cached HOT 2
- coroutine '<method that is cached>' was never awaited HOT 1
- Use cache() decorator outside of fastapi HOT 3
- handling dirty cache entries HOT 1
- How can I cache POST requests? HOT 4
- [Question] How to manually expire an entry ? HOT 1
- Add support for authentication to a remote redis HOT 2
- Feature request - async Redis client
- "Too much data for declared Content-Length" error when activating caching HOT 5
- Can't Cache List of serialized data HOT 1
- add async support for redis HOT 1
- @cache Decorator Not Working
- A Rebuild Maybe ?! ....
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fastapi-redis-cache.