75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
from flask import Flask, send_from_directory, request, jsonify
|
|
import os
|
|
import hashlib
|
|
|
|
app = Flask(__name__)
|
|
|
|
# 设置允许访问的文件夹路径
|
|
UPLOAD_FOLDER = r'C:\小工具'
|
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
|
|
|
|
|
def filter_files_by_os(files, os_type):
|
|
"""根据操作系统类型过滤文件列表"""
|
|
if os_type == 'Windows':
|
|
# 只返回 .exe 文件
|
|
return [f for f in files if f.lower().endswith('.exe')]
|
|
elif os_type == 'Mac':
|
|
# 只返回 .dmg 或 .pkg 文件
|
|
return [f for f in files if f.lower().endswith(('.dmg', '.pkg'))]
|
|
else:
|
|
# 对于其他操作系统,返回所有文件
|
|
return files
|
|
|
|
|
|
def calculate_md5(file_path):
|
|
"""计算文件的 MD5 哈希值"""
|
|
hash_md5 = hashlib.md5()
|
|
with open(file_path, "rb") as f:
|
|
for chunk in iter(lambda: f.read(4096), b""):
|
|
hash_md5.update(chunk)
|
|
return hash_md5.hexdigest()
|
|
|
|
|
|
@app.route('/files', methods=['GET'])
|
|
def list_files():
|
|
# 获取指定目录下的所有文件名
|
|
files = os.listdir(app.config['UPLOAD_FOLDER'])
|
|
|
|
# 从查询参数中获取操作系统类型
|
|
os_type = request.args.get('os', 'Other') # 默认为 'Other'
|
|
print(f"Requested OS: {os_type}") # 打印请求的操作系统类型用于调试
|
|
|
|
# 根据操作系统类型过滤文件列表
|
|
filtered_files = filter_files_by_os(files, os_type)
|
|
|
|
return jsonify(filtered_files)
|
|
|
|
|
|
@app.route('/download/<filename>', methods=['GET'])
|
|
def download_file(filename):
|
|
try:
|
|
# 发送文件给客户端
|
|
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
|
|
except Exception as e:
|
|
return str(e), 404
|
|
|
|
|
|
@app.route('/hash/<filename>', methods=['GET'])
|
|
def get_file_hash(filename):
|
|
"""返回文件的 MD5 哈希值"""
|
|
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
|
if os.path.exists(file_path):
|
|
md5_hash = calculate_md5(file_path)
|
|
return md5_hash
|
|
else:
|
|
return "File not found", 404
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 确保文件夹存在
|
|
if not os.path.exists(app.config['UPLOAD_FOLDER']):
|
|
os.makedirs(app.config['UPLOAD_FOLDER'])
|
|
|
|
app.run(host='192.168.10.86', debug=True, port=5001)
|