File size: 1,035 Bytes
b4a2012
6e4454b
05fca73
 
 
 
b4a2012
 
 
 
6e4454b
b4a2012
 
 
6e4454b
b4a2012
 
 
 
59961e7
b4a2012
 
 
 
 
 
 
 
 
 
05fca73
 
6e4454b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from flask import Flask, send_from_directory, render_template_string
import os

app = Flask(__name__)

@app.route('/')
@app.route('/<path:req_path>')
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)