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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-03 09:58:09 +0000
Seen: 16 times
Last updated: Jun 03 '23
How to delete cache and cookies on Flutter Web?
How can the cache be cleared on the client side using React Vite?
In what manner does react-scripts v5 manage the lasting caching created through webpack?
Why are the packages not getting installed with the npm command?
How do I shut down a WPF page and erase its cache?
Does the Microsoft.Extensions.Caching.Memory.IMemoryCache provide thread safety?
How can I address the issue of NPM ERESOLVE being incapable of resolving the dependency tree?