skip to Main Content

I use Flask and python. I have updatable .html file in my templates folder.

For updating .html file I delete it before rendering and then write it again.

if os.path.isfile(html_file):
    os.unlink(html_file)

html_text = ['bla', 'bla'] # that's the part that changes every time

with open(html_file, 'w') as f:
    f.writelines(html_text)

File is deleted, then created and written properly.

Then I call it:

@app.route('/html_file')
def show_html_file():
    return render_template('html_file.html')

First time render_template returns proper file. But then, not matter: updated .html file or even deleted, route /html_file show only old version of file. I’ve tried to force browser to force refresh ignoring caching, tried different browsers. I still got first version of .html file.

How to fix it?

3

Answers


  1. Chosen as BEST ANSWER

    It looks like templates by default are not updatable. And it must be forced.

    Here is a way how to do it:

    app = Flask(__name__)
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    

  2. I am unsure what you are trying to achieve, but I would recommend templating with Jinja2 in Flask. Jinja2 helps you to write python code in your html file.

    If you don’t want to use Jinja2, you could also format the html within your function and just return it.

    For further reading check out: https://www.geeksforgeeks.org/templating-with-jinja2-in-flask/

    Login or Signup to reply.
  3. The issue you’re encountering is likely due to caching. Browsers tend to cache static files like HTML, CSS, and JavaScript to improve loading times and reduce server load. When you make changes to your HTML file on the server, the browser may still be using the cached version, which is why you’re seeing the old version even after updating it.

    One common technique to prevent caching is to add a query parameter to the URL, which changes with each update. For example:

    from flask import request
    
    @app.route('/html_file')
    def show_html_file():
        version = '1.0'  # Change this value each time you update the HTML
        return render_template('html_file.html', version=version)
    

    Then, in your html_file.html, you can modify the URL of your HTML file to include the query parameter:

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}?v={{ version }}">
    

    This way, each time you update the HTML, you can change the value of version, and the browser will treat it as a new URL, fetching the updated version.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search