- 将file上传接口从一次性返回改为流式返回 - 使用StreamingResponse和NDJSON格式,与batch接口保持一致 - 提升用户体验,减少响应等待时间 - 统一两种接口的返回格式
60 lines
1.8 KiB
Python
60 lines
1.8 KiB
Python
from fastapi import APIRouter, UploadFile, File, HTTPException, Request
|
|
from fastapi.responses import StreamingResponse
|
|
from service import RmbgService
|
|
from utils import jingrow_api_verify_and_billing
|
|
from settings import settings
|
|
import json
|
|
import asyncio
|
|
|
|
router = APIRouter(prefix=settings.router_prefix)
|
|
service = RmbgService()
|
|
|
|
@router.post(settings.batch_route)
|
|
@jingrow_api_verify_and_billing(api_name=settings.api_name)
|
|
async def remove_background_batch(data: dict, request: Request):
|
|
"""
|
|
批量处理多个URL图片
|
|
|
|
Args:
|
|
data: 包含图片URL列表的字典
|
|
request: FastAPI 请求对象
|
|
|
|
Returns:
|
|
流式响应,包含每个图片的处理结果
|
|
"""
|
|
if "urls" not in data:
|
|
raise HTTPException(status_code=400, detail="缺少urls参数")
|
|
|
|
async def process_and_stream():
|
|
async for result in service.process_batch(data["urls"]):
|
|
yield json.dumps(result) + "\n"
|
|
|
|
return StreamingResponse(
|
|
process_and_stream(),
|
|
media_type="application/x-ndjson"
|
|
)
|
|
|
|
@router.post(settings.file_route)
|
|
@jingrow_api_verify_and_billing(api_name=settings.api_name)
|
|
async def remove_background_file(file: UploadFile = File(...), request: Request = None):
|
|
"""
|
|
从上传的文件移除背景(流式返回)
|
|
|
|
Args:
|
|
file: 上传的图片文件
|
|
request: FastAPI 请求对象
|
|
|
|
Returns:
|
|
流式响应,包含处理后的图片内容
|
|
"""
|
|
content = await file.read()
|
|
|
|
async def process_and_stream():
|
|
result = await service.remove_background_from_file(content)
|
|
yield json.dumps(result) + "\n"
|
|
|
|
return StreamingResponse(
|
|
process_and_stream(),
|
|
media_type="application/x-ndjson"
|
|
)
|