mirror of
https://github.com/long2ice/fastapi-cache.git
synced 2026-03-25 04:57:54 +00:00
Decode cache data to the correct endpoint type
Use the return annotation to decode cached data to the correct type. This follows the same logic FastAPI uses to JSON request bodies. For the PickleCoder, this is a no-op as pickle already stores type information in the serialised data.
This commit is contained in:
@@ -7,6 +7,7 @@ from starlette.responses import JSONResponse, Response
|
||||
from fastapi_cache import FastAPICache
|
||||
from fastapi_cache.backends.inmemory import InMemoryBackend
|
||||
from fastapi_cache.decorator import cache
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@@ -80,6 +81,20 @@ instance = SomeClass(17)
|
||||
app.get("/method")(cache(namespace="test")(instance.handler_method))
|
||||
|
||||
|
||||
# cache a Pydantic model instance; the return type annotation is required in this case
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: str | None = None
|
||||
price: float
|
||||
tax: float | None = None
|
||||
|
||||
|
||||
@app.get("/pydantic_instance")
|
||||
@cache(namespace="test", expire=5)
|
||||
async def pydantic_instance() -> Item:
|
||||
return Item(name="Something", description="An instance of a Pydantic model", price=10.5)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
FastAPICache.init(InMemoryBackend())
|
||||
|
||||
Reference in New Issue
Block a user