Skip to main content

CDN

Since static files are served by the Flask app when using url_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 consists of mostly routes that don’t change often, then you can cache the rendered output of your pages with edge caching. This will apply to your entire app and only endpoints with headers disallowing caching will ignored by the edge cache. You can prevent caching by updating the route’s response to have response.cache_control.no_store = True
from datetime import datetime 
from flask import Flask, make_response 

from .extensions import db, alembic

def create_app():
    app = Flask(__name__)
    app.config.from_prefixed_env()

    db.init_app(app)
    alembic.init_app(app)

    @app.route("/") 
    def index():
        response = make_response(f"Last generated at {datetime.now()}")
        response.cache_control.no_store = True
        return response

    return app
To control the longest a page will remain in the cache, you need to set response.cache_control.max_age to your desired value.
from datetime import datetime
from flask import Flask, make_response

from .extensions import db, alembic

def create_app():
    app = Flask(__name__)
    app.config.from_prefixed_env()

    db.init_app(app)
    alembic.init_app(app)

    @app.route("/")
    def index():
        response = make_response(f"Last generated at {datetime.now()}")
        response.cache_control.no_store = True
        return response
    
    @app.route("/page") 
    def page():
        response = make_response(f"Cached at {datetime.now()} for two minutes")
        response.cache_control.max_age = 60*2
        return response

    return app
Instead of setting the cache configuration in your routes, you also have the option of using the after_request decorator or creating your own decorator. 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.