file_import_upload_project

博客提及了项目上传(UPLOAD PROJECT),但未提供更多详细信息。推测可能围绕项目上传的流程、方法等信息技术相关内容展开。
UPLOAD PROJECT
这是app.py代码 import os import logging import traceback import time import threading from flask import Flask, render_template, request, redirect, url_for, send_from_directory, jsonify from werkzeug.utils import secure_filename app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB app.config['SECRET_KEY'] = 'your_strong_secret_key_here' app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'] = '/shared/files' # 局域网文件共享目录 app.config['FILE_CLEANUP_INTERVAL'] = 3600 # 文件清理间隔(秒) # 确保上传目录和共享目录存在 os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) os.makedirs(app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'], exist_ok=True) # 配置详细日志记录 logging.basicConfig( filename='app.log', level=logging.INFO, format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s' ) app.logger = logging.getLogger(__name__) # 文件系统锁确保线程安全 file_lock = threading.Lock() def cleanup_old_files(): """定期清理临时上传目录中的旧文件""" while True: try: with file_lock: now = time.time() for filename in os.listdir(app.config['UPLOAD_FOLDER']): file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) if os.path.isfile(file_path): file_age = now - os.path.getctime(file_path) if file_age > 24 * 3600: # 删除超过1天的临时文件 os.remove(file_path) app.logger.info(f"Cleaned up old file: {filename}") except Exception as e: app.logger.error(f"File cleanup error: {str(e)}") time.sleep(app.config['FILE_CLEANUP_INTERVAL']) # 启动文件清理线程 cleanup_thread = threading.Thread(target=cleanup_old_files, daemon=True) cleanup_thread.start() @app.errorhandler(500) def internal_error(error): """自定义500错误处理页面""" app.logger.error(f"500 Error: {error}\n{traceback.format_exc()}") return render_template('500.html', error=traceback.format_exc()), 500 @app.errorhandler(404) def not_found_error(error): """自定义404错误处理页面""" return render_template('404.html', error=error.description), 404 @app.route('/') def index(): """安全的主页路由,显示共享文件列表""" try: # 获取共享目录中的文件列表 files = [] with file_lock: for filename in os.listdir(app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files']): file_path = os.path.join(app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'], filename) if os.path.isfile(file_path): files.append({ 'name': filename, 'size': os.path.getsize(file_path), 'modified': time.ctime(os.path.getmtime(file_path)) }) return render_template('index.html', files=files) except Exception as e: app.logger.error(f"Error in index route: {str(e)}") return render_template('500.html', error=str(e)), 500 @app.route('/upload', methods=['POST']) def upload_file(): """安全的文件上传处理""" try: if 'file' not in request.files: app.logger.warning("No file part in request") return jsonify({'status': 'error', 'message': 'No file part'}), 400 file = request.files['file'] if file.filename == '': app.logger.warning("No selected file") return jsonify({'status': 'error', 'message': 'No selected file'}), 400 if file: # 安全处理文件名 filename = secure_filename(file.filename) file_path = os.path.join(app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'], filename) # 保存文件到共享目录 with file_lock: file.save(file_path) app.logger.info(f"File uploaded: {filename}") return jsonify({'status': 'success', 'filename': filename}) except Exception as e: app.logger.error(f"Upload error: {str(e)}\n{traceback.format_exc()}") return jsonify({'status': 'error', 'message': str(e)}), 500 @app.route('/download/<filename>') def download_file(filename): """文件下载功能""" try: # 验证文件名是否安全 safe_filename = secure_filename(filename) file_path = os.path.join(app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'], safe_filename) # 检查文件是否存在 if not os.path.exists(file_path): app.logger.warning(f"File not found: {safe_filename}") return render_template('404.html', filename=safe_filename), 404 # 提供文件下载 return send_from_directory( app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'], safe_filename, as_attachment=True ) except Exception as e: app.logger.error(f"Download error: {str(e)}\n{traceback.format_exc()}") return render_template('500.html', error=str(e)), 500 @app.route('/delete/<filename>', methods=['POST']) def delete_file(filename): """删除文件功能""" try: # 验证文件名是否安全 safe_filename = secure_filename(filename) file_path = os.path.join(app.config['C:\\Users\21904\PycharmProjects\PythonProject\.venv\your_project\\uploads\shared\files'], safe_filename) # 检查文件是否存在 if not os.path.exists(file_path): app.logger.warning(f"File not found for deletion: {safe_filename}") return jsonify({'status': 'error', 'message': 'File not found'}), 404 # 删除文件 with file_lock: os.remove(file_path) app.logger.info(f"File deleted: {safe_filename}") return jsonify({'status': 'success', 'filename': safe_filename}) except Exception as e: app.logger.error(f"Delete error: {str(e)}\n{traceback.format_exc()}") return jsonify({'status': 'error', 'message': str(e)}), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=False)
08-14
import time import os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import openpyxl from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class ExcelFileHandler(FileSystemEventHandler): def __init__(self, upload_function): self.upload_function = upload_function def on_modified(self, event): if event.src_path.endswith('.xlsx') and os.path.getsize(event.src_path) > 0: print(f"检测到文件 {event.src_path} 被修改") # 暂时不调用上传函数 # self.upload_function(event.src_path) def read_excel(file_path): try: workbook = openpyxl.load_workbook(file_path) sheet = workbook.active data = [] for row in sheet.iter_rows(min_row=2, values_only=True): if row[0] is not None: data.append((row[0], row[1])) workbook.close() return data except Exception as e: print(f"读取Excel文件时出错: {e}") return None def upload_data(file_path): try: driver = webdriver.Chrome() driver.get("https://target-website.com/upload") wait = WebDriverWait(driver, 10) username_input = wait.until(EC.presence_of_element_located((By.ID, "username"))) password_input = driver.find_element(By.ID, "password") username_input.send_keys("your_username") password_input.send_keys("your_password") login_button = driver.find_element(By.ID, "login-button") login_button.click() upload_page = wait.until(EC.presence_of_element_located((By.ID, "upload-form"))) data = read_excel(file_path) if data is None: return for item in data: field1 = driver.find_element(By.ID, "field1") field2 = driver.find_element(By.ID, "field2") submit_button = driver.find_element(By.ID, "submit-button") field1.clear() field2.clear() field1.send_keys(item[0]) field2.send_keys(item[1]) submit_button.click() time.sleep(2) print("数据上传完成") driver.quit() except Exception as e: print(f"上传数据时出错: {e}") driver.quit() def setup_file_monitor(folder_path, upload_function): event_handler = ExcelFileHandler(upload_function) observer = Observer() observer.schedule(event_handler, path=folder_path, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": folder_path = r"D:\\\\work_project\\\\import_data" setup_file_monitor(folder_path, upload_data) 请你这个代码上按照你的方式来修改
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值