重构基本完成
This commit is contained in:
@ -13,6 +13,7 @@ from app.common import reponse_code as rc
|
||||
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, Request, UploadFile, File, Form
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
"""项目管理API"""
|
||||
@ -150,3 +151,12 @@ def get_img_leafer(image_id: int, session: Session = Depends(get_db)):
|
||||
img_leafer_out = ps.get_img_leafer(image_id, session)
|
||||
return rc.response_success(data=img_leafer_out)
|
||||
|
||||
|
||||
@project.get("/run_train/{project_id}")
|
||||
def run_train(project_id: int, session: Session = Depends(get_db)):
|
||||
project_info = pic.get_project_by_id(project_id, session)
|
||||
if project_info is None:
|
||||
return rc.response_error("项目查询错误")
|
||||
if project_info.project_status == '1':
|
||||
return rc.response_error("项目当前存在训练进程,请稍后再试")
|
||||
return StreamingResponse(ps.run_train_yolo(project_info, session), media_type="text/plain")
|
||||
|
42
app/api/common/test_api.py
Normal file
42
app/api/common/test_api.py
Normal file
@ -0,0 +1,42 @@
|
||||
import asyncio
|
||||
import subprocess
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
|
||||
test = APIRouter()
|
||||
|
||||
|
||||
async def generate_data():
|
||||
for i in range(1, 10): # 生成 5 行数据
|
||||
await asyncio.sleep(1) # 等待 1 秒
|
||||
yield f"data: This is line {i}\n\n" # 返回 SSE 格式的数据
|
||||
|
||||
|
||||
def run_command(command):
|
||||
"""执行命令并实时打印每一行输出"""
|
||||
# 启动子进程
|
||||
with subprocess.Popen(
|
||||
command,
|
||||
shell=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
universal_newlines=True, # 确保输出以字符串形式返回而不是字节
|
||||
bufsize=1, # 行缓冲
|
||||
) as process:
|
||||
# 使用iter逐行读取stdout和stderr
|
||||
for line in process.stdout:
|
||||
yield f"stdout: {line.strip()} \n"
|
||||
|
||||
for line in process.stderr:
|
||||
yield f"stderr: {line.strip()} \n"
|
||||
|
||||
# 等待进程结束并获取返回码
|
||||
return_code = process.wait()
|
||||
if return_code != 0:
|
||||
print(f"Process exited with non-zero code: {return_code}")
|
||||
|
||||
|
||||
@test.get("/stream")
|
||||
async def stream_response():
|
||||
return StreamingResponse(run_command(["ping", "-n", "10", "127.0.0.1"]), media_type="text/plain")
|
Reference in New Issue
Block a user