Help me refactor this Python code to make it cleaner, improve it and make more robust:…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
Help me refactor this Python code to make it cleaner, improve it and make more robust: from profile.exceptions import NotAllowedException, TokenExpiredException from profile.services import ProfileServiceInterface
from auth.services import TokenServiceInterface from exceptions import ( AuthenticationError, ExpiredTokenError, InvalidTokenError, NoTokenError, ) from fastapi import WebSocket from fastapi.websockets import WebSocketDisconnect from usecases import BaseUseCase
class HandleWebsocketConnectionUseCase(BaseUseCase): def init( self, token_service: TokenServiceInterface, profile_service: ProfileServiceInterface, ) -> None: self._token_service = token_service self._profile_service = profile_service
codeasync def execute(self, websocket: WebSocket, connection_state: str) -> None: try: await self._profile_service.accept_ws_connection( websocket, connection_state ) auth_message = await websocket.receive_text() token, ref_code = await self._profile_service.get_auth_token_and_ref_code( auth_message ) except AuthenticationError: raise NotAllowedException except (WebSocketDisconnect, RuntimeError): return try: token_data = await self._token_service.get_access_token_data(token) except ExpiredTokenError: raise TokenExpiredException except (InvalidTokenError, NoTokenError): raise NotAllowedException await self._profile_service.connect_websocket( auth_user_uuid=token_data.auth_user_uuid, state=connection_state, websocket=websocket, ) await self._profile_service.authorize_user( auth_user_uuid=token_data.auth_user_uuid, name=token_data.name, state=connection_state, ref_code=ref_code, ) try: while True: command_message = await websocket.receive_text() await self._profile_service.handle_command( auth_user_uuid=token_data.auth_user_uuid, state=connection_state, command_message=command_message, ) except (WebSocketDisconnect, RuntimeError): if token_data: await self._profile_service.disconnect_websocket( auth_user_uuid=token_data.auth_user_uuid, state=connection_state ) return finally: if token_data: await self._profile_service.disconnect_websocket( auth_user_uuid=token_data.auth_user_uuid, state=connection_state ) return - Assistant