How to prevent cached response (flask server, using chrome)

11,153

To prevent cached responses from the browser: - press F12 or right click > inspect - click network tab - check "Disable cache".

To prevent cached responses from the server: add the following definition to application.py:

# prevent cached responses
if app.config["DEBUG"]:
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response
Share:
11,153
Feraru Silviu Marian
Author by

Feraru Silviu Marian

Smoke mid everyday

Updated on June 07, 2022

Comments

  • Feraru Silviu Marian
    Feraru Silviu Marian almost 2 years

    EDIT: Figured it out, press F12, click network, check "Disable cache".

    I have a basic flask server I'm using to learn d3. The problem is that chrome is giving me a cached javascript file I'm working with, example.js.

    Request Method:GET Status Code:200 OK (from memory cache)

    The server itself is sending a non cached response, I can see this by looking at the response directly via:

    /static/example.js

    I added this in application.py to prevent caching.

    @app.after_request
    def add_header(r):
        """
        Add headers to both force latest IE rendering engine or Chrome Frame,
        and also to cache the rendered page for 10 minutes.
        """
        r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        r.headers["Pragma"] = "no-cache"
        r.headers["Expires"] = "0"
        r.headers['Cache-Control'] = 'public, max-age=0'
        return r
    

    Here's the entire code

    import os
    import re
    from flask import Flask, jsonify, render_template, request, url_for
    from flask_jsglue import JSGlue
    
    from flask import send_file
    
    # configure application
    app = Flask(__name__)
    JSGlue(app)
    
    # prevent cached responses
    @app.after_request
    def add_header(r):
        """
        Add headers to both force latest IE rendering engine or Chrome Frame,
        and also to cache the rendered page for 10 minutes.
        """
        r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        r.headers["Pragma"] = "no-cache"
        r.headers["Expires"] = "0"
        r.headers['Cache-Control'] = 'public, max-age=0'
        return r
    
    @app.route("/<string:filename>")
    def main(filename):
        """Render file."""
        return render_template(filename)
    
    @app.route("/favicon.ico")
    def favicon():
        filename = 'images/fav.png'
        return send_file(filename, mimetype='image/png')
    

    Thanks for reading.