We have a custom Jinja filter that we use for creating cache busting URL for our Javascript and CSS resources. We now noticed that in our production environment the final, c
There is a way to disable caching of the result of a particular filter: it's by not using a constant input, e.g. by exposing a random source as a global variable.
# Expose to Jinja
from random import random as RANDOM
And in the templates
{{ RANDOM() | eval_this_filter_every_time }}
The caching behaviour of Jinja2 can be configured using the cache_size
setting: http://jinja.pocoo.org/docs/api/#jinja2.Environment
However, this only caches the templates itself. As long as the input for a filter is variable the output will be variable too.
So... how are you using the filter? Can you post the part of the template and the filter that is getting cached?
The easiest way to do this is:
On your flask server script do this:
from time import ctime
In your app.route() function,
in the return line add:
time=ctime()
for example:
return render_template('signup', error = error, time = ctime())
In the html reference for your css file(if using jinja2) add:
?{{time}}
at the end of your reference line.
That shoud look like this:
<link rel="stylesheet" href="{{ url_for('static', filename='css/base.css')}}?{{time}}">
Worked pretty good for me and the browser stopped caching.
I hope it helps!
Cheers!
-Nelio
After lots of Googling, I finally found the real solution to this. Jinja has a special helper called contextfilter that you can use to decorate your function with to make your filter context-aware (and context-dependent). The Jinja bytecode cache will not cache this computed value, even when a constant is passed as input.
In your filter in Python:
from jinja2 import contextfilter
@contextfilter
def asset_url(context, url):
return some_url_thing(url)
In your template:
<link rel="stylesheet" href="{{ 'styles.css' | asset_url }}" />