from fastapi import FastAPI, File, UploadFile from fastapi.staticfiles import StaticFiles import os from shutil import copyfileobj import shutil import subprocess from fastapi.responses import FileResponse app = FastAPI() 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: # 设置文件保存的路径 folder_path = './uploads/' # 清空文件夹 shutil.rmtree(folder_path) # 新建文件夹 os.makedirs(folder_path, exist_ok=True) os.makedirs(folder_path+'gen/', exist_ok=True) # 复制coderdbc程序 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/", "-drvname", "CANmatrix", "-nodeutils", "-rw", "-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, } except Exception as e: return {"error": str(e)} @app.get("/api/download/") async def download_file(): 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) 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()) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)