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__/
|
||||
uploads/
|
||||
output/
|
112
main.py
Normal file → Executable file
112
main.py
Normal file → Executable file
@ -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)
|
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 # 设置为开机自启
|
68
web/index.html
Normal file → Executable file
68
web/index.html
Normal file → Executable file
@ -3,38 +3,54 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>FastAPI Example</title>
|
||||
<title>DBC2C</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, FastAPI!</h1>
|
||||
<p>This is an example of loading an HTML file using FastAPI.</p>
|
||||
uploadfile
|
||||
<h1>dbc转换为C代码</h1>
|
||||
<p>上传dbc文件。</p>
|
||||
|
||||
<form id="uploadForm" enctype="multipart/form-data">
|
||||
<input type="file" name="file" id="file">
|
||||
<input type="submit" value="Upload File">
|
||||
<input type="file" name="file" id="fileInput">
|
||||
<input type="submit" value="上传">
|
||||
</form>
|
||||
<p id="status"></p>
|
||||
<p id="responseInfo"></p> <!-- 用于显示API返回的结果 -->
|
||||
<p id="errorMessage" style="color: red;"></p> <!-- 用于显示错误信息 -->
|
||||
<script>
|
||||
// 使用jQuery处理表单提交
|
||||
$('#uploadForm').submit(function(e) {
|
||||
e.preventDefault(); // 阻止表单默认提交行为
|
||||
|
||||
var formData = new FormData(this); // 创建FormData对象
|
||||
|
||||
$.ajax({
|
||||
url: '/api/uploadfile/', // 上传文件的API端点
|
||||
type: 'POST',
|
||||
data: formData,
|
||||
contentType: false, // 不设置内容类型
|
||||
processData: false, // 不处理数据
|
||||
success: function(response) {
|
||||
// 文件上传成功后,下载文件
|
||||
window.location.href = '/api/download/'; // 重定向到下载API端点
|
||||
},
|
||||
error: function(xhr, status, error) {
|
||||
alert('Upload error: ' + error);
|
||||
}
|
||||
document.getElementById('uploadForm').addEventListener('submit', async function(event) {
|
||||
event.preventDefault(); // 阻止表单提交
|
||||
|
||||
const formData = new FormData();
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
formData.append("file", fileInput.files[0]);
|
||||
|
||||
// 显示上传状态
|
||||
document.getElementById("status").textContent = "Uploading...";
|
||||
// 上传文件
|
||||
const response = await fetch('/api/uploadfile/', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
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>
|
||||
</html>
|
Loading…
x
Reference in New Issue
Block a user