1 | initial version |
FastAPI's built-in cache system uses the CacheControl
library to store data in memory. To use it, you can define a cache instance using cachetools
library and decorate your function with @cached()
decorator from fastapi_cache
package.
Here's an example:
from fastapi import FastAPI
from fastapi_cache import caches, close_caches
from fastapi_cache.backends.memory_cache import MemoryCache
from fastapi_cache.decorator import cache
app = FastAPI()
cache_name = "my_cache"
cache_expire_time = 20 * 60 # 20 minutes
cache = MemoryCache(cache_expire_time)
caches.set(cache_name, cache)
@app.get("/my_data/{id}")
@cache(cache_name)
def get_data_from_cache(id: str):
# your code to fetch data
data = fetch_data_from_database(id)
return {"id": id, "data": data}
@app.on_event("shutdown")
def close_all_caches():
close_caches()
This will cache the response of the get_data_from_cache
function for 20 minutes in the specified memory cache instance. When the same request is made again within 20 minutes, the cached response will be returned instead of re-fetching the data from the database.