Ask Your Question
1

What is the method for storing data in FastAPI's cache?

asked 2023-06-03 09:58:09 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-03 10:04:02 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-06-03 09:58:09 +0000

Seen: 16 times

Last updated: Jun 03 '23