http_session_service.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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, HttpSessionUpdate
  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
  32. # ============================
  33. # 根据 session_id 删除
  34. # ============================
  35. @staticmethod
  36. async def delete_by_sid(
  37. db: AsyncSession,
  38. session_id: str
  39. ) -> bool:
  40. stmt = delete(HttpSession).where(HttpSession.session_id == session_id)
  41. result = await db.execute(stmt)
  42. if result.rowcount == 0:
  43. raise NotFoundError("Session not found")
  44. await db.commit()
  45. return True
  46. # ============================
  47. # 根据 session_id 更新
  48. # ============================
  49. @staticmethod
  50. async def update_by_sid(
  51. db: AsyncSession,
  52. session_id: str,
  53. data: HttpSessionUpdate
  54. ) -> HttpSession:
  55. stmt = select(HttpSession).where(HttpSession.session_id == session_id)
  56. result = await db.execute(stmt)
  57. obj = result.scalar_one_or_none()
  58. if not obj:
  59. raise NotFoundError("Session not found")
  60. for field, value in data.dict(exclude_unset=True).items():
  61. setattr(obj, field, value)
  62. await db.commit()
  63. await db.refresh(obj)
  64. return obj