Python 简单的网页列表文件脚本

王先生
2024-06-18 / 0 评论 / 3 阅读 / 正在检测是否收录...

功能

可控制

  • √是否允许下载
  • √是否允许打包下载文件夹
  • 设置忽略文件(规划中。。。)
  • √设置监听地址
  • √设置监听端口

代码

import argparse
from flask import Flask, send_file
import os
import zipfile

app = Flask(__name__)

def list_files(startpath, allow_file_download, allow_folder_zip_download, indent=""):
    file_list = ""
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent_str = "   " * (level)
        folder_name = os.path.basename(root)
        if allow_folder_zip_download:
            file_list += f"{indent}{indent_str}<strong>{folder_name}</strong> <a href='/zipdownload/{root}'><button>Download as ZIP</button></a><br>"
        else:
            file_list += f"{indent}{indent_str}<strong>{folder_name}</strong><br>"
        subindent = "&nbsp;&nbsp;&nbsp;" * (level + 1)
        for f in files:
            if allow_file_download:
                file_list += f"{indent}{subindent}<a href='/download/{os.path.join(root, f)}'>{f}</a><br>"
            else:
                file_list += f"{indent}{subindent}{f}<br>"
    return file_list

@app.route('/')
def index():
    start_path = '.'  # Change this to the desired directory
    file_list = list_files(start_path, args.allow_file_download, args.allow_folder_zip_download)
    return file_list

@app.route('/download/<path:filename>')
def download_file(filename):
    if args.allow_file_download:
        return send_file(filename, as_attachment=True)
    else:
        return "File download is not allowed."

@app.route('/zipdownload/<path:folder>')
def zip_download(folder):
    if args.allow_folder_zip_download:
        folder_name = os.path.basename(folder)
        zipf = zipfile.ZipFile(f'{folder_name}.zip', 'w', zipfile.ZIP_DEFLATED)
        for root, dirs, files in os.walk(folder):
            for file in files:
                zipf.write(os.path.join(root, file))
        zipf.close()
        return send_file(f'{folder_name}.zip', as_attachment=True)
    else:
        return "Folder zip download is not allowed."

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Flask App with File Download Options')
    parser.add_argument('--host', default='0.0.0.0', help='Host address to listen on')
    parser.add_argument('--port', type=int, default=22222, help='Port to listen on')
    parser.add_argument('--allow_file_download', action='store_true', default=False, help='Allow file download')
    parser.add_argument('--allow_folder_zip_download', action='store_true', default=False, help='Allow folder zip download')

    args = parser.parse_args()
    app.run(host=args.host, port=args.port)

评论 (0)

取消