from flask import Flask, send_from_directory, render_template_string import os app = Flask(__name__) @app.route('/') @app.route('/') 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('

404 Not Found

'), 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('''

Directory listing for {{req_path}}

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