【问题标题】:Static directory file browsing ending too early静态目录文件浏览过早结束
【发布时间】:2018-06-18 19:44:01
【问题描述】:

我目前正在制作一个小网站来托管大量无人机图像马赛克,并希望进来的人能够通过我获得的数据文件夹结构来查找他们的数据。但是,我在访问任何文件之前中止了。当我在过去的“2017 Data”中有 3 个文件夹时,以下代码给出 404 错误。在某些情况下,这是存储图像的 1 或 2 个文件夹。

from flask import Flask, abort, send_file, render_template_string
import os
import remoteSensingData

app = Flask(__name__)

@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
    BASE_DIR = os.path.abspath("/Users/Huang.LabTech2/Desktop/Images/2017 Data/")

    # Joining the base and the requested path
    abs_path = os.path.join(BASE_DIR, req_path)

    # Return 404 if path doesn't exist
    if not os.path.exists(abs_path):
        return abort(404)

    # Check if path is a file and serve
    if os.path.isfile(abs_path):
        return send_file(abs_path)

    # Show directory contents
    files = os.listdir(abs_path)
    files = [os.path.join(req_path, f) for f in files]
    # return render_template('files.html', files=files)
    return render_template_string("""
    <ul>
        {% for file in files %}
        <li><a href="{{ file }}">{{ file }}</a></li>
        {% endfor %}
    </ul>
    """, files=files)


if __name__ == '__main__':
  app.run(debug=True)

我在实现我的最终目标方面还有其他问题,但它们与这个问题无关,所以我将为他们形成单独的问题。

【问题讨论】:

    标签: python html python-3.x flask


    【解决方案1】:

    我认为您的问题是由 BASE_DIR 路径中的空格引起的。

    您可以通过将文件夹从 2017 Data 重命名为 2017_Data 来轻松证明这一点 或者你可以尝试使用:

    BASE_DIR = os.path.abspath(r"/Users/Huang.LabTech2/Desktop/Images/2017 Data/")
    

    【讨论】:

    • 这些都没有解决问题,但感谢您的回复。
    • 您使用什么操作系统?问题出在您的 BASE_DIR - 尝试将 abs_path 记录到控制台,您将能够看到问题所在。我的第二个假设是缺少驱动器号(如果您使用的是 Windows),例如:“C:/Users/..”
    • 我使用的是 Windows 10。我已将问题缩小到 os.path.isfile(abs_path) 行不起作用,但我不确定如何解决它们。例如,如果我将 BASE_DIR 与包含一组图像的文件夹(C:\Users\Huang.LabTech2\Desktop\Images\2017 Data\UAV\Bobby_Hardin_Multi(8-16)\3_dsm_ortho\2_mosaic)一起加入,abs_path 将加入图像并给我正确的路径。但 os.path.isfile(abs_path) 返回 false。
    猜你喜欢
    • 2012-09-08
    • 2011-08-19
    • 1970-01-01
    • 2011-09-11
    • 2013-11-24
    • 1970-01-01
    • 2018-02-18
    相关资源
    最近更新 更多