2023-11-28 14:29:16 -08:00
|
|
|
from typing import Any, Dict, Type, TypeVar, Union
|
2023-11-28 14:16:05 -08:00
|
|
|
|
2023-11-28 14:29:16 -08:00
|
|
|
import attr
|
2023-11-28 23:50:50 -08:00
|
|
|
from pydantic import GetCoreSchemaHandler
|
|
|
|
from pydantic_core import CoreSchema, core_schema
|
2023-08-30 15:59:51 -07:00
|
|
|
|
|
|
|
from .failure_web_socket_response import FailureWebSocketResponse
|
|
|
|
from .success_web_socket_response import SuccessWebSocketResponse
|
|
|
|
|
2023-11-28 14:29:16 -08:00
|
|
|
GY = TypeVar("GY", bound="WebSocketResponse")
|
2023-11-28 14:16:05 -08:00
|
|
|
|
2023-11-28 14:29:16 -08:00
|
|
|
|
|
|
|
@attr.s(auto_attribs=True)
|
2023-11-28 14:16:05 -08:00
|
|
|
class WebSocketResponse:
|
|
|
|
|
|
|
|
"""Websocket responses can either be successful or unsuccessful. Slightly different schemas in either case."""
|
|
|
|
|
|
|
|
type: Union[
|
|
|
|
SuccessWebSocketResponse,
|
|
|
|
FailureWebSocketResponse,
|
2023-11-28 14:29:16 -08:00
|
|
|
]
|
2023-11-28 14:16:05 -08:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
type: Union[
|
2023-11-28 14:29:16 -08:00
|
|
|
SuccessWebSocketResponse,
|
|
|
|
FailureWebSocketResponse,
|
2023-11-28 14:16:05 -08:00
|
|
|
],
|
|
|
|
):
|
|
|
|
self.type = type
|
|
|
|
|
2023-11-28 23:50:50 -08:00
|
|
|
def model_dump(self) -> Dict[str, Any]:
|
2023-11-28 14:16:05 -08:00
|
|
|
if isinstance(self.type, SuccessWebSocketResponse):
|
2023-11-28 23:50:50 -08:00
|
|
|
HV: SuccessWebSocketResponse = self.type
|
|
|
|
return HV.model_dump()
|
2023-11-28 14:16:05 -08:00
|
|
|
elif isinstance(self.type, FailureWebSocketResponse):
|
2023-11-28 23:50:50 -08:00
|
|
|
CL: FailureWebSocketResponse = self.type
|
|
|
|
return CL.model_dump()
|
2023-11-28 14:16:05 -08:00
|
|
|
|
|
|
|
raise Exception("Unknown type")
|
|
|
|
|
2023-11-28 14:29:16 -08:00
|
|
|
@classmethod
|
|
|
|
def from_dict(cls: Type[GY], d: Dict[str, Any]) -> GY:
|
2023-11-28 16:37:47 -08:00
|
|
|
if d.get("success") is True:
|
2023-11-28 23:50:50 -08:00
|
|
|
CD: SuccessWebSocketResponse = SuccessWebSocketResponse(**d)
|
|
|
|
return cls(type=CD)
|
2023-11-28 16:37:47 -08:00
|
|
|
elif d.get("success") is False:
|
2023-11-28 23:50:50 -08:00
|
|
|
ZO: FailureWebSocketResponse = FailureWebSocketResponse(**d)
|
|
|
|
return cls(type=ZO)
|
2023-11-28 14:16:05 -08:00
|
|
|
|
|
|
|
raise Exception("Unknown type")
|
2023-11-28 23:50:50 -08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def __get_pydantic_core_schema__(
|
|
|
|
cls, source_type: Any, handler: GetCoreSchemaHandler
|
|
|
|
) -> CoreSchema:
|
|
|
|
return core_schema.no_info_after_validator_function(
|
|
|
|
cls,
|
|
|
|
handler(
|
|
|
|
Union[
|
|
|
|
SuccessWebSocketResponse,
|
|
|
|
FailureWebSocketResponse,
|
|
|
|
]
|
|
|
|
),
|
|
|
|
)
|