def fetch(self, connection_id: str) -> str: try: item = self.connection.get_item( Key={"connectionId": connection_id})["Item"] except KeyError: raise WebSocketError(f"Connection not found: {connection_id}") initial_scope = item["initial_scope"] return initial_scope
def post_to_connection(self, msg_data: bytes) -> None: # pragma: no cover try: apigw_client = boto3.client( "apigatewaymanagementapi", endpoint_url=self.api_gateway_endpoint_url, region_name=self.api_gateway_region_name, ) apigw_client.post_to_connection( ConnectionId=self.connection_id, Data=msg_data ) except ClientError as exc: status_code = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode") if status_code == 410: self.delete() else: raise WebSocketError(exc)
def __post_init__(self) -> None: parsed_dsn = urlparse(self.dsn) parsed_query = parse_qs(parsed_dsn.query) table_name = get_table_name(parsed_dsn) region_name = (parsed_query["region"][0] if "region" in parsed_query else os.environ["AWS_REGION"]) endpoint_url = (parsed_query["endpoint_url"][0] if "endpoint_url" in parsed_query else None) try: dynamodb_resource = boto3.resource( "dynamodb", region_name=region_name, endpoint_url=endpoint_url, config=Config(connect_timeout=2, retries={"max_attempts": 0}), ) dynamodb_resource.meta.client.describe_table(TableName=table_name) except (EndpointConnectionError, ClientError) as exc: raise WebSocketError(exc) self.connection = dynamodb_resource.Table(table_name)
def __post_init__(self) -> None: if boto3 is None: # pragma: no cover raise WebSocketError("boto3 must be installed to use WebSockets.") self.logger: logging.Logger = logging.getLogger("mangum.websocket") parsed_dsn = urlparse(self.dsn) if not any((parsed_dsn.hostname, parsed_dsn.path)): raise ConfigurationError("Invalid value for `dsn` provided.") scheme = parsed_dsn.scheme self.logger.debug( f"Attempting WebSocket backend connection using scheme: {scheme}" ) if scheme == "sqlite": self.logger.info( "The `SQLiteBackend` should be only be used for local " "debugging. It will not work in a deployed environment." ) from mangum.backends.sqlite import SQLiteBackend self._backend = SQLiteBackend(self.dsn) # type: ignore elif scheme == "dynamodb": from mangum.backends.dynamodb import DynamoDBBackend self._backend = DynamoDBBackend(self.dsn) # type: ignore elif scheme == "s3": from mangum.backends.s3 import S3Backend self._backend = S3Backend(self.dsn) # type: ignore elif scheme in ("postgresql", "postgres"): from mangum.backends.postgresql import PostgreSQLBackend self._backend = PostgreSQLBackend(self.dsn) # type: ignore elif scheme == "redis": from mangum.backends.redis import RedisBackend self._backend = RedisBackend(self.dsn) # type: ignore else: raise ConfigurationError(f"{scheme} does not match a supported backend.") self.logger.debug("WebSocket backend connection established.")