diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 index c18dd8d..b5efaeb --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ __pycache__/ +uploads/ +output/ \ No newline at end of file diff --git a/main.py b/main.py old mode 100644 new mode 100755 index 5ccd8f7..b1127d4 --- a/main.py +++ b/main.py @@ -5,6 +5,9 @@ from shutil import copyfileobj import shutil import subprocess from fastapi.responses import FileResponse +from uuid import uuid4 +import logging + app = FastAPI() @@ -17,53 +20,84 @@ async def root(): @app.post("/api/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): try: - # 设置文件保存的路径 - folder_path = './uploads/' - # 清空文件夹 - shutil.rmtree(folder_path) - # 新建文件夹 + # 创建一个唯一的文件夹来存储文件 + folder_id = str(uuid4()) + folder_path = f'./uploads/{folder_id}/' + + # 清空并创建新的文件夹 os.makedirs(folder_path, exist_ok=True) - os.makedirs(folder_path+'gen/', exist_ok=True) - # 复制coderdbc程序 + os.makedirs(os.path.join(folder_path, 'gen'), exist_ok=True) + + # 复制程序到目标路径 shutil.copy2("../dbc2c/coderdbc", folder_path) + + # 保存上传的文件 file_location = os.path.join(folder_path, file.filename) with open(file_location, "wb") as buffer: copyfileobj(file.file, buffer) - # 执行二进制程序并等待其完成 + + # 执行外部程序 command = [ - folder_path+"coderdbc", - "-dbc", folder_path+file.filename, - "-out", folder_path+"gen/", + os.path.join(folder_path, "coderdbc"), + "-dbc", file_location, + "-out", os.path.join(folder_path, "gen"), "-drvname", "CANmatrix", "-nodeutils", "-rw", - "-driverdir", # 这个参数后面没有值,所以它后面不应该有逗号 + "-driverdir", # 这个参数没有值,因此可以不传入任何值 "-gendate" ] - result = subprocess.run(command, capture_output=True, text=True) - # 获取输出和错误 - - if result.stderr == "": - command = ['zip', '-r', folder_path+'gen/CANmatrix.zip', folder_path+'gen/CANmatrix'] - # 使用subprocess.run执行命令 - result = subprocess.run(command, capture_output=True, text=True) - - return {"info": f"File {file.filename} uploaded successfully!", - "coderdbc_stdout":result.stdout, - "coderdbc_stderr":result.stderr, - } + # 执行命令并捕获输出 + result = subprocess.run(command, capture_output=True, text=True) + + # 检查stderr是否为空,执行压缩操作 + if result.stderr == "": + # 确保 'CANmatrix' 文件夹存在 + canmatrix_folder = os.path.join(folder_path, 'gen', 'CANmatrix') + if not os.path.exists(canmatrix_folder): + return {"error": "CANmatrix folder not found in gen directory"} + + zip_command = ['zip', '-r', 'CANmatrix.zip', 'CANmatrix'] + + # 使用 cwd 设置为 gen 目录 + zip_result = subprocess.run(zip_command, cwd=os.path.join(folder_path, 'gen'), capture_output=True, text=True) + + if zip_result.stderr != "": + return {"error": "Failed to create zip file", "stderr": zip_result.stderr} + + # 复制压缩包到output目录 + output_folder = './output/' + os.makedirs(output_folder, exist_ok=True) # 创建output文件夹(如果不存在) + shutil.copy2(os.path.join(folder_path, 'gen/CANmatrix.zip'), os.path.join(output_folder, 'CANmatrix.zip')) + + # 删除UUID临时文件夹 + shutil.rmtree(folder_path) + + # 返回结果 + return { + "info": f"File {file.filename} uploaded and processed successfully!", + "coderdbc_stdout": result.stdout, + "coderdbc_stderr": result.stderr, + } except Exception as e: return {"error": str(e)} -@app.get("/api/download/") -async def download_file(): +@app.get("/api/download/{filename}") +async def download_file(filename: str): try: # 设置文件保存的路径 - folder_path = './uploads/' - return FileResponse(path=folder_path+"gen/CANmatrix.zip", filename="CANmatrix.zip", media_type="application/zip") - except FileNotFoundError: - return JSONResponse(content={"message": "File not found"}, status_code=404) + output_folder = './output/' + file_path = os.path.join(output_folder, filename) + + # 检查文件是否存在 + if not os.path.exists(file_path): + return JSONResponse(content={"message": "File not found"}, status_code=404) + + # 返回文件响应 + return FileResponse(path=file_path, filename=filename, media_type="application/zip") + except Exception as e: + return JSONResponse(content={"message": f"Error: {str(e)}"}, status_code=500) def process_file(file_path, output_path): with open(file_path, 'r') as file: @@ -73,4 +107,22 @@ def process_file(file_path, output_path): if __name__ == "__main__": import uvicorn + # 配置日志记录 + log_dir = "../logs" + if not os.path.exists(log_dir): + os.makedirs(log_dir) + logging.basicConfig( + level=logging.INFO, # 记录 INFO 级别及以上的日志 + format="%(asctime)s - %(levelname)s - %(message)s", # 日志格式 + handlers=[ + logging.FileHandler(log_file), # 保存到文件 + logging.StreamHandler() # 输出到控制台 + ] + ) + + logger = logging.getLogger(__name__) + + # 设置日志文件路径 + log_file = os.path.join(log_dir, "app.log") + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/note.txt b/note.txt new file mode 100755 index 0000000..fd87c1c --- /dev/null +++ b/note.txt @@ -0,0 +1,38 @@ +1.进入虚拟环境 +source .venv/bin/activate +2.运行fastapi +uvicorn main:app --reload --host 0.0.0.0 --port 8000 + +后台运行 +nohup uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info > ../log/app.log 2>&1 & + + +//待定(还有问题) +3.服务脚本 +sudo nano /etc/systemd/system/fastapi.service +''' +[Unit] +Description=FastAPI Application +After=network.target + +[Service] +User=huahua # 设置为运行应用的用户 +WorkingDirectory=/home/huahua/intr/HostMain/code +ExecStart=/home/huahua/intr/HostMain/.venv/bin/uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info +Restart=always + +[Install] +WantedBy=multi-user.target + + +''' + +4.运行服务 +sudo systemctl daemon-reload +sudo systemctl start fastapi.service +sudo systemctl enable fastapi.service # 设置为开机自启 + +sudo systemctl stop fastapi.service +sudo journalctl -u fastapi.service -f # 实时查看日志 + +sudo systemctl disable fastapi.service # 设置为开机自启 \ No newline at end of file diff --git a/web/index.html b/web/index.html old mode 100644 new mode 100755 index a544fab..4e7476a --- a/web/index.html +++ b/web/index.html @@ -3,38 +3,54 @@
-This is an example of loading an HTML file using FastAPI.
- uploadfile +上传dbc文件。
+ + + + +