Spaces:
Running
Running
from flask import Flask, send_from_directory, render_template_string | |
import os | |
app = Flask(__name__) | |
def dir_listing(req_path=''): | |
base_dir = os.path.abspath(os.getcwd()) # 使用绝对路径 | |
abs_path = os.path.join(base_dir, req_path) | |
# 检查路径是否存在 | |
if not os.path.exists(abs_path): | |
return render_template_string('<h1>404 Not Found</h1>'), 404 | |
# 检查路径是否是文件 | |
if os.path.isfile(abs_path): | |
# 如果是文件,则下载文件 | |
return send_from_directory(base_dir, req_path, as_attachment=True) | |
# 显示目录内容 | |
files = os.listdir(abs_path) | |
return render_template_string(''' | |
<h1>Directory listing for {{req_path}}</h1> | |
<ul> | |
{% for file in files %} | |
<li><a href="{{ req_path|safe }}/{{ file|safe }}">{{ file }}</a></li> | |
{% endfor %} | |
</ul> | |
''', files=files, req_path=req_path) | |
if __name__ == '__main__': | |
app.run(debug=True) | |