3

我目前正在使用 Flask 来提供可视化编程环境。我希望用户稍后回来时能够加载系统中当前的代码。我试过使用:

return redirect(url_for('static', filename='rawxml.txt'))
return redirect(send_from_directory('static', 'rawxml.txt'))

但是,两者都不会提供文件的修改版本,而是似乎是文件的缓存版本。我如何提供一个经常被新内容重写的文件。

注意:rawxml.txt 存储在“静态”目录中,但它是指向实际 XML 所在位置的符号链接(我也尝试过硬链接)。

4

2 回答 2

3

我有静态文件的下一个实现:

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

它只是将哈希参数添加到使用url_for.

于 2013-08-07T05:27:28.777 回答
1

未经测试:

url = url_for('static', filename='rawxml.txt', t=time.time())
return redirect(url)

如果内容不是那么动态的,您可以重写它以使用文件的 MD5 哈希 - 这样您只会在文件更改时使缓存无效。tbicr的答案看起来就是一个很好的例子。

[更新]

在 jQuery 方面,执行以下操作:

$('#some_selector').load('{{ url }}#'+new Date().valueOf());
于 2013-08-07T00:37:42.593 回答