Reputation: 729
I currently am using Flask to serve up a visual programming environment. I would like the users to be able to load the code currently in the system if they come back later. I have tried using:
return redirect(url_for('static', filename='rawxml.txt'))
return redirect(send_from_directory('static', 'rawxml.txt'))
However, both will never serve the modified version of the file, and instead what seems to be a cached version of the file. How can I serve a file that gets rewritten often with the new content.
Note: rawxml.txt is stored in the "static" directory, but it is a sym link to where the actual XML is (I have tried a hard link as well).
Upvotes: 4
Views: 1601
Reputation: 77349
Untested:
url = url_for('static', filename='rawxml.txt', t=time.time())
return redirect(url)
If the content is not that dynamic, you can rewrite it to use an MD5 hash of the file - this way you will only invalidate the cache when the file changes. The answer from tbicr looks like a good example of this.
[update]
At the jQuery side, do something like:
$('#some_selector').load('{{ url }}#'+new Date().valueOf());
Upvotes: 1
Reputation: 26080
I have next implementation for static files:
hash_cache = {}
@app.url_defaults
def add_hash_for_static_files(endpoint, values):
'''Add content hash argument for url to make url unique.
It's have sense for updates to avoid caches.
'''
if endpoint != 'static':
return
filename = values['filename']
if filename in hash_cache:
values['hash'] = hash_cache[filename]
return
filepath = safe_join(app.static_folder, filename)
if os.path.isfile(filepath):
with open(filepath, 'rb') as static_file:
filehash = get_hash(static_file.read(), 8)
values['hash'] = hash_cache[filename] = filehash
It just add hash argument to urls which generated with url_for
.
Upvotes: 5