Coverage for apps/outers/interfaces/deliveries/middlewares/session_middleware.py: 73%

30 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-22 19:03 +0000

1from sqlmodel.ext.asyncio.session import AsyncSession 

2from starlette import status 

3from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint 

4from starlette.requests import Request 

5from starlette.responses import Response 

6from starlette.types import ASGIApp 

7 

8from apps.inners.exceptions import datastore_exception 

9from apps.inners.models.dtos.content import Content 

10from apps.outers.datastores.one_datastore import OneDatastore 

11 

12 

13class SessionMiddleware(BaseHTTPMiddleware): 

14 def __init__( 

15 self, 

16 app: ASGIApp, 

17 one_datastore: OneDatastore 

18 ): 

19 super().__init__(app) 

20 self.one_datastore = one_datastore 

21 

22 async def dispatch( 

23 self, 

24 request: Request, 

25 call_next: RequestResponseEndpoint 

26 ) -> Response: 

27 content: Content = Content( 

28 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, 

29 message=f"{self.__class__.__name__}.{self.dispatch.__name__}: Failed.", 

30 data=None 

31 ) 

32 

33 async def handler(session: AsyncSession): 

34 request.state.session = session 

35 handler_response: Response = await call_next(request) 

36 

37 return handler_response 

38 

39 try: 

40 response: Response = await self.one_datastore.retryable(handler) 

41 except datastore_exception.MaxRetriesExceeded as exception: 

42 content.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR 

43 content.message += f" {exception.caller.class_name}.{exception.caller.function_name}: {exception.__class__.__name__}." 

44 response: Response = content.to_response() 

45 except datastore_exception.HandlerError as exception: 

46 content.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR 

47 content.message += f" {exception.caller.class_name}.{exception.caller.function_name}: {exception.__class__.__name__}." 

48 response: Response = content.to_response() 

49 

50 return response