Spaces:
Paused
Paused
| #!/usr/bin/env python3 | |
| """ | |
| 简单的上传与触发服务(FastAPI) | |
| 提供: | |
| GET / -> 上传页面 | |
| POST /upload -> 上传文件(multipart) | |
| POST /run -> 手动触发 process_report.py | |
| 部署时请确保 INPUT_DIR 与 OUTPUT_DIR 与 process_report.py 一致 | |
| """ | |
| import os | |
| import shutil | |
| import subprocess | |
| from fastapi import FastAPI, UploadFile, File, Form | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| import uvicorn | |
| INPUT_DIR = os.environ.get('INPUT_DIR', '/data/uploads') | |
| OUTPUT_DIR = os.environ.get('OUTPUT_DIR', '/data/outputs') | |
| os.makedirs(INPUT_DIR, exist_ok=True) | |
| os.makedirs(OUTPUT_DIR, exist_ok=True) | |
| app = FastAPI() | |
| async def index(): | |
| # 这里直接返回 HTML 内容,不需要 templates 文件夹 | |
| return HTMLResponse(''' | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>采购执行表自动化 - 上传</title> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <style> | |
| body { font-family: sans-serif; background-color: #f4f4f9; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } | |
| .container { background: white; padding: 2rem; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-align: center; } | |
| h2 { color: #333; } | |
| input[type="file"] { border: 1px solid #ddd; padding: 0.5rem; border-radius: 4px; } | |
| input[type="submit"] { background-color: #007bff; color: white; padding: 0.6rem 1rem; border: none; border-radius: 4px; cursor: pointer; margin-left: 1rem; } | |
| input[type="submit"]:hover { background-color: #0056b3; } | |
| p { font-size: 0.9rem; color: #666; margin-top: 1rem; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h2>采购执行表自动化 - 上传页面</h2> | |
| <form action="/upload" enctype="multipart/form-data" method="post"> | |
| <input name="file" type="file" required /> | |
| <input type="submit" value="上传文件" /> | |
| </form> | |
| <p>上传后,系统将按计划自动处理或可通过API手动触发。</p> | |
| </div> | |
| </body> | |
| </html> | |
| ''') | |
| async def upload(file: UploadFile = File(...)): | |
| save_path = os.path.join(INPUT_DIR, file.filename) | |
| with open(save_path, 'wb') as f: | |
| content = await file.read() | |
| f.write(content) | |
| return JSONResponse({'status': 'ok', 'saved': save_path, 'message': f'文件 {file.filename} 上传成功!'}) | |
| async def run_once(): | |
| # 调用核心处理脚本 | |
| proc = subprocess.run(['python', '/workspace/process_report.py'], capture_output=True, text=True) | |
| if proc.returncode == 0: | |
| return JSONResponse({'status': 'ok', 'returncode': proc.returncode, 'stdout': proc.stdout, 'stderr': proc.stderr}) | |
| else: | |
| return JSONResponse({'status': 'error', 'returncode': proc.returncode, 'stdout': proc.stdout, 'stderr': proc.stderr}, status_code=500) | |
| if __name__ == '__main__': | |
| uvicorn.run(app, host='0.0.0.0', port=7860) |