我试图列出特定目录(“/data/file/transfer”)中的所有文件和子目录。
现在我遇到这个问题,只能获取位于第二级子目录中的文件。我正在使用 Jinja 模板来查看页面。
目录结构如下:
/data/
----file/
--------transfer/
-------------first/
----------------second/
-------------------get_this_file.txt
文件 get_this_file.txt 位于/data/file/transfer/first/second/目录中。
#! /usr/bin/env python
from flask import Flask,render_template, send_file
import os
import sys
app = Flask(__name__)
@app.route("/list_data", defaults={'req_path': ''})
@app.route('/<path:req_path>')
def incident_data(req_path):
base_dir = "/data/file/transfer/"
abs_path = os.path.join(base_dir, req_path)
if os.path.isfile(abs_path):
return send_file(abs_path)
final_files = []
if os.path.isdir(abs_path):
files = os.listdir(abs_path)
for file in files:
temp_file = req_path + "/" + file
print temp_file
final_files.append(temp_file)
return render_template('files.html', files=final_files)
if __name__ == "__main__":
app.config.update(dict(
DEBUG=True,
SECRET_KEY=b'_isecret/'
))
app.run(host="0.0.0.0", port=8080)
我的 templates/files.html 如下:
<ul>
{% for file in files %}
<li><a href="{{ file }}">{{ file }}</a></li>
{% endfor %}
</ul>
输出:
在 Chrome 上:
192.168.168.xxx:8080/第一/第二
第一/第二/get_this_file.txt <---(单击时)
192.168.168.xxx:8080/第一/第一/第二/get_this_file.txt
无法理解为什么 get_this_file.txt 的 href 是错误的。
任何帮助表示赞赏。为此苦苦挣扎了很长时间。
最佳答案
您应该通过在 href 开头添加 /
正斜杠来添加相对路径。因此它解析域就像从域的根开始一样。
<a href="/{{ file }}">{{ file }}</a>
然后
OUTPUT:
on chrome:
192.168.168.xxx:8080/first/second
first/second/get_this_file.txt <--- (when clicked)
192.168.168.xxx:8080/first/second/get_this_file.txt
更新:
尝试使用 url_for 来解决您的所有 href 问题。
<li><a href="{{ url_for('incident_data', req_path=file) }}">{{ file }}</a></li>
关于Python、Flask、Jinja : listing directory and files: href is set incorrectly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45429117/