Skip to main content
 首页 » 编程设计

python之Flask,动态生成文件链接

2025年05月04日56jillzhang

如何使用 Flask 动态生成文件链接?这是我的示例代码,但当我单击链接时它不起作用。目录中的所有文件都是文本文件,因此浏览器无需下载任何内容即可打开它们。

{% for x, y in links %} 
<tr> 
     <td><a href="{{y}}">{{x}}</a></td> 
     <td><a href="{{y}}">{{y}}</a></td> 
</tr> 
{% endfor %} 
 
path = 'path/directory' 
if request.method == 'GET': 
# a is the date last modified, b is the file path 
    link = [(a, b) for a, b in get_files_sorted(path)] 
    return render_template('file_structure.html', links=link) 
if request.method == 'POST': 
    #open the text file that was clicked on 

请您参考如下方法:

假设您的文件在您的静态目录中,您可以执行如下操作:

<td><a href="{{ url_for('static', filename=y) }}">{{x}}</a></td>

或

<td><a href="{{ url_for('static', filename='path/directory/%s' % (y)) ) }}">{{x}}</a></td>