静态目录文件浏览结束得太早

时间:2018-06-18 19:44:02

标签: python html python-3.x flask

我目前正在制作一个小型网站来托管大量无人机图像马赛克,并希望有人能够通过我获得的数据文件夹结构来查找他们的数据。但是,在我找到任何文件之前,我已经中止了。当我在过去的" 2017数据中有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)

我在实现最终目标方面还有其他问题,但他们与此问题无关,因此我将为他们提出单独的问题。

1 个答案:

答案 0 :(得分:0)

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

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

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