This commit is contained in:
15
backend/app/middleware/__init__.py
Normal file
15
backend/app/middleware/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
中间件模块
|
||||
"""
|
||||
|
||||
from .response_formatter import (
|
||||
ResponseFormatterMiddleware,
|
||||
format_error_response,
|
||||
format_success_response,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ResponseFormatterMiddleware",
|
||||
"format_error_response",
|
||||
"format_success_response",
|
||||
]
|
||||
91
backend/app/middleware/response_formatter.py
Normal file
91
backend/app/middleware/response_formatter.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
响应格式化中间件
|
||||
|
||||
自动将 API 响应中的字符串或错误信息格式化为统一风格
|
||||
"""
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
from typing import Callable
|
||||
|
||||
from backend.app.core import get_formatter
|
||||
|
||||
|
||||
class ResponseFormatterMiddleware(BaseHTTPMiddleware):
|
||||
"""
|
||||
响应格式化中间件
|
||||
|
||||
功能:
|
||||
1. 统一响应包装
|
||||
2. 错误信息格式化
|
||||
3. 调试信息注入(可选)
|
||||
"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next: Callable):
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
|
||||
def format_error_response(
|
||||
error_type: str,
|
||||
error_message: str,
|
||||
suggestions: list = None,
|
||||
retry_count: int = 0,
|
||||
max_retries: int = None
|
||||
) -> str:
|
||||
"""
|
||||
格式化错误响应
|
||||
|
||||
Args:
|
||||
error_type: 错误类型
|
||||
error_message: 错误详情
|
||||
suggestions: 建议操作列表
|
||||
retry_count: 已重试次数
|
||||
max_retries: 最大重试次数
|
||||
|
||||
Returns:
|
||||
格式化后的 Markdown 文本
|
||||
"""
|
||||
formatter = get_formatter()
|
||||
return formatter.render_error(
|
||||
error_type=error_type,
|
||||
error_message=error_message,
|
||||
suggestions=suggestions,
|
||||
retry_count=retry_count,
|
||||
max_retries=max_retries
|
||||
)
|
||||
|
||||
|
||||
def format_success_response(
|
||||
content: str,
|
||||
title: str = None,
|
||||
include_footer: bool = True
|
||||
) -> str:
|
||||
"""
|
||||
格式化成功响应
|
||||
|
||||
Args:
|
||||
content: 内容
|
||||
title: 可选标题
|
||||
include_footer: 是否包含页脚
|
||||
|
||||
Returns:
|
||||
格式化后的 Markdown 文本
|
||||
"""
|
||||
formatter = get_formatter()
|
||||
md = formatter.md
|
||||
|
||||
lines = []
|
||||
if title:
|
||||
lines.append(md.heading(title, 2))
|
||||
lines.append("")
|
||||
|
||||
lines.append(content)
|
||||
|
||||
if include_footer:
|
||||
lines.append("")
|
||||
lines.append("---")
|
||||
lines.append("*以上内容由 AI Agent 生成*")
|
||||
|
||||
return "\n".join(lines)
|
||||
Reference in New Issue
Block a user