http_session_service.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from typing import Optional
  2. from sqlalchemy.ext.asyncio import AsyncSession
  3. from sqlalchemy import select, delete
  4. from app.core.biz_exception import NotFoundError
  5. from app.models.http_session import HttpSession
  6. from app.schemas.http_session import HttpSessionCreate
  7. class HttpSessionService:
  8. # ============================
  9. # 创建 Session
  10. # ============================
  11. @staticmethod
  12. async def create(db: AsyncSession, data: HttpSessionCreate) -> HttpSession:
  13. obj = HttpSession(**data.dict())
  14. db.add(obj)
  15. await db.commit()
  16. await db.refresh(obj)
  17. return obj
  18. # ============================
  19. # 根据 session_id 获取
  20. # ============================
  21. @staticmethod
  22. async def get_by_sid(
  23. db: AsyncSession,
  24. session_id: str
  25. ) -> HttpSession:
  26. stmt = select(HttpSession).where(HttpSession.session_id == session_id)
  27. result = await db.execute(stmt)
  28. obj = result.scalar_one_or_none()
  29. if not obj:
  30. raise NotFoundError("Session not found")
  31. return obj