Flask-Caching with Redis
You can use the Flask-Caching extension with a Flask app deployed on Sevalla by connecting a Redis service to your application.Install
To use the caching extension, both Flask-Caching and Redis need to be installed.Code
The extension needs to be instantiated inside ofextensions.py.
__init__.py.
FLASK_CACHE_TYPE and FLASK_CACHE_REDIS_URL values to your .env file.
REDIS_URL environment variable to FLASK_CACHE_REDIS_URL and add it to the application.
You also need to add the environment variable FLASK_CACHE_TYPE with the value RedisCache.
Example
To cache a route, use thecache object to decorate the route with @cache.cached(). 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.
Flask-Caching can also be used with the same configuration to cache both templates and regular functions in your app.
If you want to cache your entire site, consider using edge caching instead.
CDN
Since static files are served by the Flask app when usingurl_for('static'), you can 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. The cf-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 route’s response to haveresponse.cache_control.no_store = True
response.cache_control.max_age value.
after_request decorator or by creating a custom decorator. This approach helps keep your route handlers clean and makes it easier to apply consistent caching behavior across multiple endpoints.
To verify your pages are being cached correctly, request a page and inspect the response headers. The 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.