diff --git a/backend/app/api/v1/controllers/system/auth_controller.py b/backend/app/api/v1/controllers/system/auth_controller.py index 11def157..1026e484 100644 --- a/backend/app/api/v1/controllers/system/auth_controller.py +++ b/backend/app/api/v1/controllers/system/auth_controller.py @@ -1,12 +1,13 @@ # -*- coding: utf-8 -*- +import asyncio from typing import Union, Dict -from fastapi import APIRouter, Depends, Request +from fastapi import APIRouter, BackgroundTasks, Depends, Request, WebSocket from fastapi.responses import JSONResponse from sqlalchemy.ext.asyncio import AsyncSession from app.config.setting import settings -from app.common.response import ErrorResponse, SuccessResponse +from app.common.response import ErrorResponse, SuccessResponse, StreamResponse from app.api.v1.services.system.auth_service import ( LoginService, CaptchaService @@ -24,6 +25,7 @@ from app.core.dependencies import ( from app.core.router_class import OperationLogRoute from app.core.security import CustomOAuth2PasswordRequestForm from app.core.logger import logger +from app.core.tasks import background_task, long_running_task router = APIRouter(route_class=OperationLogRoute) @@ -76,3 +78,32 @@ async def logout( logger.info('退出成功') return SuccessResponse(msg='退出成功') return ErrorResponse(msg='退出失败') + +# ws://127.0.0.1:8000/api/v1/system/auth/ws +@router.websocket("/ws", name="websocket") +async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + + +@router.post("/celery-task", summary="模拟celery进行后台任务") +async def process_data(data: str): + # 调用 Celery 任务 + result = long_running_task.delay(data) + return SuccessResponse(msg=f"任务已提交到 Celery: {result}") + + +# 模拟流响应 +@router.get("/bg-stream", summary="模拟fastapi自带后台任务-模拟流式响应") +async def stream_response(background_tasks: BackgroundTasks): + def log_task(message): + logger.info(message) + + background_tasks.add_task(log_task, "Streaming started") + return StreamResponse( + data = background_task(), + headers={"X-Custom-Header": "Streaming-Response"}, + media_type="text/plain", + ) \ No newline at end of file diff --git a/backend/app/core/tasks.py b/backend/app/core/tasks.py new file mode 100644 index 00000000..c04a4f34 --- /dev/null +++ b/backend/app/core/tasks.py @@ -0,0 +1,24 @@ +from celery import Celery + +# 创建 Celery 实例 +app = Celery( + "worker", + broker="redis://localhost:6379/0", + backend="redis://localhost:6379/0", # 使用 Redis 存储任务结果 + include=["tasks"], # 包含任务模块 +) + +# 配置 Celery +app.conf.update( + result_expires=3600, # 任务结果过期时间(秒) + timezone="Asia/Shanghai", # 时区 +) + +@app.task +def long_running_task(data): + return f"Processed: {data}" + + +def background_task(): + for i in range(10): + yield f"执行后台任务: {i}\n" diff --git a/backend/dev_sql.db b/backend/dev_sql.db index 169ddd80..8a3e8567 100644 Binary files a/backend/dev_sql.db and b/backend/dev_sql.db differ diff --git a/backend/requirements.txt b/backend/requirements.txt index 9f1f9163..2340d9af 100755 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,7 +1,9 @@ fastapi==0.115.2 typer==0.12.5 uvicorn==0.30.6 +websockets==14.2 gunicorn==23.0.0 +celery==5.4.0 requests==2.32.3 pandas==2.2.2 openpyxl==3.1.5 @@ -17,6 +19,7 @@ python-multipart==0.0.9 greenlet==3.1.1 bcrypt==4.0.1 aiofiles==24.1.0 # 文件操作 +redis==5.2.1 # redis 同步操作数据库(用户celery配套使用) aioredis==2.0.1 # redis 异步操作数据库 aiosqlite==0.17.0 # sqlite 异步操作数据库 asyncmy==0.2.9 # mysql 异步操作数据库:基于 mysqlclient:asyncmy 是 mysqlclient 的异步版本,mysqlclient 是一个 C 语言编写的 MySQL 客户端,性能较高。性能:asyncmy 通常在性能上优于 aiomysql,特别是在高并发和大数据量的场景下。