from flask import Flask, request, send_file, redirect import pandas as pd import os import time from threading import Thread from datetime import datetime app = Flask(__name__) UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = {'xlsx'} CLEANUP_INTERVAL = 300 # 5分钟 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def cleanup_uploads(): """定时清理uploads文件夹""" while True: time.sleep(CLEANUP_INTERVAL) try: for filename in os.listdir(app.config['UPLOAD_FOLDER']): file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) except Exception as e: print(f'删除文件 {file_path} 失败: {e}') except Exception as e: print(f'清理uploads文件夹失败: {e}') # 启动清理线程 cleanup_thread = Thread(target=cleanup_uploads) cleanup_thread.daemon = True cleanup_thread.start() def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: return "没有选择文件" file = request.files['file'] if file.filename == '': return "没有选择文件" if file and allowed_file(file.filename): # 确保上传目录存在 os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) # 生成安全的文件名 upload_dir = os.path.abspath(app.config['UPLOAD_FOLDER']) os.makedirs(upload_dir, exist_ok=True) filename = os.path.join(upload_dir, file.filename) file.save(filename) # 处理Excel文件 df = pd.read_excel(filename) df_deduplicated = df.drop_duplicates() # 生成带时间戳的输出文件名 timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') base_name, ext = os.path.splitext(file.filename) output_filename = os.path.join(upload_dir, f'{base_name}_{timestamp}{ext}') df_deduplicated.to_excel(output_filename, index=False) # 确保文件已写入 if not os.path.exists(output_filename): raise FileNotFoundError(f"无法创建文件: {output_filename}") return f''' 去重完成

去重完成

文件去重处理成功!

下载去重后的文件
''' return ''' Excel去重工具

Excel文件去重工具

''' @app.route('/download/') def download_file(filename): try: upload_dir = os.path.abspath(app.config['UPLOAD_FOLDER']) path = os.path.join(upload_dir, filename) if not os.path.exists(path): raise FileNotFoundError(f"文件 {filename} 不存在") return send_file(path, as_attachment=True) except Exception as e: return f"下载文件失败: {str(e)}", 500 @app.route('/clear_cache', methods=['POST']) def clear_cache(): try: for filename in os.listdir(app.config['UPLOAD_FOLDER']): file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) except Exception as e: print(f'删除文件 {file_path} 失败: {e}') return ''' 缓存已清理

缓存已成功清理

将在 3 秒后返回首页
''' except Exception as e: return f'清理缓存失败: {e}' if __name__ == '__main__': os.makedirs(UPLOAD_FOLDER, exist_ok=True) app.run(host='0.0.0.0', port=5000)