Python、Flask、Jinja : listing directory and files: href is set incorrectly

标签 python python-2.7 flask jinja2

我试图列出特定目录(“/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/

相关文章:

python - cherrypy 作为 gevent-socketio 服务器

python - Heroku 中的 Django 部署 : Fails in createsuperuser : django. db.utils.OperationalError:没有这样的表:auth_user

docker - 无法更改 nginx.conf 文件

python - 如何在给定日期时间值限制下填充数据框中的列?

c# - 在 python 中编码时在 c# 中解码 base64

应用于变量的 Python 冒号 ":"运算符?

python - 在 Sqlalchemy 上删除多对多关系(关联对象)

python - 如何在 flask-admin 中创建一个额外的字段?

Python:扩展 'dict' 类

python - 将 PyQT 表项从 QComboBox 更改为 QTableWidgetItem