Files
PWF/CoreModules/middleware.py

36 lines
1.5 KiB
Python
Raw Permalink Normal View History

2025-11-05 16:21:05 +08:00
"""中间件模块"""
import asyncio
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
2025-11-07 15:52:06 +08:00
from ..Convention.Runtime.GlobalConfig import *
2025-11-07 23:47:33 +08:00
from ..Convention.Runtime.Architecture import Architecture
2025-11-05 16:21:05 +08:00
2025-11-07 23:47:33 +08:00
logger: ProjectConfig = Architecture.Get(ProjectConfig)
MAX_CONCURRENT_REQUESTS = logger.FindItem("max_concurrent_requests", 100)
logger.SaveProperties()
2025-11-05 16:21:05 +08:00
class ConcurrencyLimitMiddleware(BaseHTTPMiddleware):
"""并发限制中间件 - 防止内存爆炸"""
def __init__(self, app, max_concurrent: int = MAX_CONCURRENT_REQUESTS):
super().__init__(app)
self.semaphore = asyncio.Semaphore(max_concurrent)
self.max_concurrent = max_concurrent
2025-11-07 23:47:33 +08:00
logger.Log("Info", f"并发限制中间件已启用,最大并发数:{max_concurrent}")
2025-11-05 16:21:05 +08:00
async def dispatch(self, request: Request, call_next) -> Response:
"""处理请求"""
async with self.semaphore:
try:
response = await call_next(request)
return response
except Exception as e:
2025-11-07 23:47:33 +08:00
logger.Log("Error", f"{ConsoleFrontColor.RED}请求处理错误: {e}{ConsoleFrontColor.RESET}")
2025-11-05 16:21:05 +08:00
return Response(
content='{"error": "Internal Server Error"}',
status_code=500,
media_type="application/json"
)
__all__ = ["ConcurrencyLimitMiddleware"]