HostMain/main.py

128 lines
4.5 KiB
Python
Raw Permalink Normal View History

2024-12-30 17:04:19 +08:00
from fastapi import FastAPI, File, UploadFile
2024-12-30 17:03:58 +08:00
from fastapi.staticfiles import StaticFiles
2024-12-30 17:04:19 +08:00
import os
from shutil import copyfileobj
import shutil
import subprocess
from fastapi.responses import FileResponse
2024-12-31 10:03:07 +08:00
from uuid import uuid4
import logging
2024-12-30 17:03:58 +08:00
app = FastAPI()
2024-12-30 17:04:19 +08:00
app.mount("/tool", StaticFiles(directory="./web", html=True))
@app.get("/api/test/")
async def root():
return {"message": "Hello World"}
@app.post("/api/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
try:
2024-12-31 10:03:07 +08:00
# 创建一个唯一的文件夹来存储文件
folder_id = str(uuid4())
folder_path = f'./uploads/{folder_id}/'
# 清空并创建新的文件夹
2024-12-30 17:04:19 +08:00
os.makedirs(folder_path, exist_ok=True)
2024-12-31 10:03:07 +08:00
os.makedirs(os.path.join(folder_path, 'gen'), exist_ok=True)
# 复制程序到目标路径
2024-12-30 17:04:19 +08:00
shutil.copy2("../dbc2c/coderdbc", folder_path)
2024-12-31 10:03:07 +08:00
# 保存上传的文件
2024-12-30 17:04:19 +08:00
file_location = os.path.join(folder_path, file.filename)
with open(file_location, "wb") as buffer:
copyfileobj(file.file, buffer)
2024-12-31 10:03:07 +08:00
# 执行外部程序
2025-01-17 14:08:48 +08:00
command = [ # coderdbc -dbc ./DMK-RP-77A.dbc -out ./gen -drvname CANmatrix -nodeutils -rw -driverdir -gendate
2024-12-31 10:03:07 +08:00
os.path.join(folder_path, "coderdbc"),
"-dbc", file_location,
"-out", os.path.join(folder_path, "gen"),
2024-12-30 17:04:19 +08:00
"-drvname", "CANmatrix",
"-nodeutils",
"-rw",
2024-12-31 10:03:07 +08:00
"-driverdir", # 这个参数没有值,因此可以不传入任何值
2024-12-30 17:04:19 +08:00
"-gendate"
]
2024-12-31 10:03:07 +08:00
# 执行命令并捕获输出
2024-12-30 17:04:19 +08:00
result = subprocess.run(command, capture_output=True, text=True)
2024-12-31 10:03:07 +08:00
# 检查stderr是否为空执行压缩操作
2024-12-30 17:04:19 +08:00
if result.stderr == "":
2024-12-31 10:03:07 +08:00
# 确保 '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"}
2024-12-30 17:04:19 +08:00
2024-12-31 10:03:07 +08:00
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,
}
2024-12-30 17:04:19 +08:00
except Exception as e:
return {"error": str(e)}
2024-12-31 10:03:07 +08:00
@app.get("/api/download/{filename}")
async def download_file(filename: str):
2024-12-30 17:04:19 +08:00
try:
# 设置文件保存的路径
2024-12-31 10:03:07 +08:00
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)
2024-12-30 17:04:19 +08:00
def process_file(file_path, output_path):
with open(file_path, 'r') as file:
content = file.read()
with open(output_path, 'w') as file:
file.write(content.upper())
2024-12-30 17:03:58 +08:00
if __name__ == "__main__":
import uvicorn
2024-12-31 10:03:07 +08:00
# 配置日志记录
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")
2024-12-30 17:03:58 +08:00
uvicorn.run(app, host="0.0.0.0", port=8000)