v0.1发布
This commit is contained in:
parent
354347b4e9
commit
76a99222f4
2
.gitignore
vendored
Normal file → Executable file
2
.gitignore
vendored
Normal file → Executable file
@ -1 +1,3 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
|
uploads/
|
||||||
|
output/
|
98
main.py
Normal file → Executable file
98
main.py
Normal file → Executable file
@ -5,6 +5,9 @@ from shutil import copyfileobj
|
|||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
|
from uuid import uuid4
|
||||||
|
import logging
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@ -17,54 +20,85 @@ async def root():
|
|||||||
@app.post("/api/uploadfile/")
|
@app.post("/api/uploadfile/")
|
||||||
async def create_upload_file(file: UploadFile = File(...)):
|
async def create_upload_file(file: UploadFile = File(...)):
|
||||||
try:
|
try:
|
||||||
# 设置文件保存的路径
|
# 创建一个唯一的文件夹来存储文件
|
||||||
folder_path = './uploads/'
|
folder_id = str(uuid4())
|
||||||
# 清空文件夹
|
folder_path = f'./uploads/{folder_id}/'
|
||||||
shutil.rmtree(folder_path)
|
|
||||||
# 新建文件夹
|
# 清空并创建新的文件夹
|
||||||
os.makedirs(folder_path, exist_ok=True)
|
os.makedirs(folder_path, exist_ok=True)
|
||||||
os.makedirs(folder_path+'gen/', exist_ok=True)
|
os.makedirs(os.path.join(folder_path, 'gen'), exist_ok=True)
|
||||||
# 复制coderdbc程序
|
|
||||||
|
# 复制程序到目标路径
|
||||||
shutil.copy2("../dbc2c/coderdbc", folder_path)
|
shutil.copy2("../dbc2c/coderdbc", folder_path)
|
||||||
|
|
||||||
|
# 保存上传的文件
|
||||||
file_location = os.path.join(folder_path, file.filename)
|
file_location = os.path.join(folder_path, file.filename)
|
||||||
with open(file_location, "wb") as buffer:
|
with open(file_location, "wb") as buffer:
|
||||||
copyfileobj(file.file, buffer)
|
copyfileobj(file.file, buffer)
|
||||||
# 执行二进制程序并等待其完成
|
|
||||||
|
# 执行外部程序
|
||||||
command = [
|
command = [
|
||||||
folder_path+"coderdbc",
|
os.path.join(folder_path, "coderdbc"),
|
||||||
"-dbc", folder_path+file.filename,
|
"-dbc", file_location,
|
||||||
"-out", folder_path+"gen/",
|
"-out", os.path.join(folder_path, "gen"),
|
||||||
"-drvname", "CANmatrix",
|
"-drvname", "CANmatrix",
|
||||||
"-nodeutils",
|
"-nodeutils",
|
||||||
"-rw",
|
"-rw",
|
||||||
"-driverdir", # 这个参数后面没有值,所以它后面不应该有逗号
|
"-driverdir", # 这个参数没有值,因此可以不传入任何值
|
||||||
"-gendate"
|
"-gendate"
|
||||||
]
|
]
|
||||||
result = subprocess.run(command, capture_output=True, text=True)
|
|
||||||
# 获取输出和错误
|
|
||||||
|
|
||||||
|
# 执行命令并捕获输出
|
||||||
|
result = subprocess.run(command, capture_output=True, text=True)
|
||||||
|
|
||||||
|
# 检查stderr是否为空,执行压缩操作
|
||||||
if result.stderr == "":
|
if result.stderr == "":
|
||||||
command = ['zip', '-r', folder_path+'gen/CANmatrix.zip', folder_path+'gen/CANmatrix']
|
# 确保 'CANmatrix' 文件夹存在
|
||||||
# 使用subprocess.run执行命令
|
canmatrix_folder = os.path.join(folder_path, 'gen', 'CANmatrix')
|
||||||
result = subprocess.run(command, capture_output=True, text=True)
|
if not os.path.exists(canmatrix_folder):
|
||||||
|
return {"error": "CANmatrix folder not found in gen directory"}
|
||||||
|
|
||||||
|
zip_command = ['zip', '-r', 'CANmatrix.zip', 'CANmatrix']
|
||||||
|
|
||||||
return {"info": f"File {file.filename} uploaded successfully!",
|
# 使用 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_stdout": result.stdout,
|
||||||
"coderdbc_stderr": result.stderr,
|
"coderdbc_stderr": result.stderr,
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"error": str(e)}
|
return {"error": str(e)}
|
||||||
|
|
||||||
@app.get("/api/download/")
|
@app.get("/api/download/{filename}")
|
||||||
async def download_file():
|
async def download_file(filename: str):
|
||||||
try:
|
try:
|
||||||
# 设置文件保存的路径
|
# 设置文件保存的路径
|
||||||
folder_path = './uploads/'
|
output_folder = './output/'
|
||||||
return FileResponse(path=folder_path+"gen/CANmatrix.zip", filename="CANmatrix.zip", media_type="application/zip")
|
file_path = os.path.join(output_folder, filename)
|
||||||
except FileNotFoundError:
|
|
||||||
|
# 检查文件是否存在
|
||||||
|
if not os.path.exists(file_path):
|
||||||
return JSONResponse(content={"message": "File not found"}, status_code=404)
|
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):
|
def process_file(file_path, output_path):
|
||||||
with open(file_path, 'r') as file:
|
with open(file_path, 'r') as file:
|
||||||
content = file.read()
|
content = file.read()
|
||||||
@ -73,4 +107,22 @@ def process_file(file_path, output_path):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
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)
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|
38
note.txt
Executable file
38
note.txt
Executable file
@ -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 # 设置为开机自启
|
62
web/index.html
Normal file → Executable file
62
web/index.html
Normal file → Executable file
@ -3,37 +3,53 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>FastAPI Example</title>
|
<title>DBC2C</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Hello, FastAPI!</h1>
|
<h1>dbc转换为C代码</h1>
|
||||||
<p>This is an example of loading an HTML file using FastAPI.</p>
|
<p>上传dbc文件。</p>
|
||||||
uploadfile
|
|
||||||
<form id="uploadForm" enctype="multipart/form-data">
|
<form id="uploadForm" enctype="multipart/form-data">
|
||||||
<input type="file" name="file" id="file">
|
<input type="file" name="file" id="fileInput">
|
||||||
<input type="submit" value="Upload File">
|
<input type="submit" value="上传">
|
||||||
</form>
|
</form>
|
||||||
|
<p id="status"></p>
|
||||||
|
<p id="responseInfo"></p> <!-- 用于显示API返回的结果 -->
|
||||||
|
<p id="errorMessage" style="color: red;"></p> <!-- 用于显示错误信息 -->
|
||||||
<script>
|
<script>
|
||||||
// 使用jQuery处理表单提交
|
document.getElementById('uploadForm').addEventListener('submit', async function(event) {
|
||||||
$('#uploadForm').submit(function(e) {
|
event.preventDefault(); // 阻止表单提交
|
||||||
e.preventDefault(); // 阻止表单默认提交行为
|
|
||||||
|
|
||||||
var formData = new FormData(this); // 创建FormData对象
|
const formData = new FormData();
|
||||||
|
const fileInput = document.getElementById('fileInput');
|
||||||
|
formData.append("file", fileInput.files[0]);
|
||||||
|
|
||||||
$.ajax({
|
// 显示上传状态
|
||||||
url: '/api/uploadfile/', // 上传文件的API端点
|
document.getElementById("status").textContent = "Uploading...";
|
||||||
type: 'POST',
|
// 上传文件
|
||||||
data: formData,
|
const response = await fetch('/api/uploadfile/', {
|
||||||
contentType: false, // 不设置内容类型
|
method: 'POST',
|
||||||
processData: false, // 不处理数据
|
body: formData
|
||||||
success: function(response) {
|
|
||||||
// 文件上传成功后,下载文件
|
|
||||||
window.location.href = '/api/download/'; // 重定向到下载API端点
|
|
||||||
},
|
|
||||||
error: function(xhr, status, error) {
|
|
||||||
alert('Upload error: ' + error);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
// 获取原始响应内容并显示
|
||||||
|
//const rawResponse = data.text(); // 获取原始文本响应
|
||||||
|
// 将 JSON 数据转换为文本(字符串)
|
||||||
|
const dataText = JSON.stringify(data, null, 2); // 格式化为带缩进的文本
|
||||||
|
document.getElementById("responseInfo").textContent = dataText;
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
document.getElementById("status").textContent = "File uploaded successfully! Waiting to download...";
|
||||||
|
|
||||||
|
// 上传成功后,等待 5 秒再开始下载
|
||||||
|
setTimeout(() => {
|
||||||
|
// 延时后下载文件
|
||||||
|
window.location.href = `/api/download/CANmatrix.zip`; // 自动下载
|
||||||
|
}, 3000); // 3 秒
|
||||||
|
} else {
|
||||||
|
document.getElementById("status").textContent = `Error: ${data.error}`;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user