FastAPI-Cache using Redis
You can use the FastAPI-Cache library with a FastAPI app deployed on Sevalla by connecting a Redis service to your application.Install
To use the caching extension, both FastAPI-Cache and Redis need to be installed.Code
The library must first be set up as a lifespan function to work with FastAPI. This setup can be added inmain.py.
REDIS_URL to config.py.
REDIS_URL to your .env file.
REDIS_URL to your app when you connect the Redis service to it.
Example
To cache a route, decorate the route with@cache decorator. This example caches the route for two minutes.
cached/ endpoint, the time the view was added to the cache will be displayed until the cache is updated.
FastAPI-Cache can also be used with the same configuration to cache regular functions in your app.
If you want to cache your entire API, consider using edge caching instead.
CDN
Even though static files aren’t typically served from FastAPI, if you happen to serve static files, you can take advantage of CDN caching. To add CDN caching, enable the CDN setting to cache your static assets on Cloudflare. To verify your static files are being cached correctly, request a file and inspect the response headers. Thecf-cache-status header should be either HIT or MISS. MISS should only occur when the file needs to be set or updated in the CDN. HIT will be the expected value for most requests.
Edge caching
If your app primarily serves endpoints with data that doesn’t change frequently, you can use edge caching to cache the responses. This will apply to your entire app, except for endpoints that explicitly include headers preventing caching, which the edge cache will ignore. You can prevent caching by updating the endpoint’s response to have aCache-Control header with the value no-store.
max-age value in your Cache-Control header.
cf-cache-status header should be either HIT or MISS. MISS should only occur when the page needs to be set or updated in the CDN. HIT will be the expected value for most requests.