Skip to content

WebSocketGateway class

This is the reference for the WebSocketGateway that contains all the parameters, attributes and functions.

How to import

from esmerald import WebSocketGateway

esmerald.WebSocketGateway

WebSocketGateway(path=None, *, handler, name=None, parent=None, dependencies=None, middleware=None, interceptors=None, permissions=None, exception_handlers=None, is_from_router=False)

Bases: WebSocketRoute, BaseInterceptorMixin, BaseMiddleware

WebSocketGateway object class used by Esmerald routes.

The WebSocketGateway act as a brigde between the router handlers and the main Esmerald routing system.

Read more about WebSocketGateway and how to use it.

Example

from esmerald import Esmerald. websocket

@websocket()
async def world_socket(socket: Websocket) -> None:
    await socket.accept()
    msg = await socket.receive_json()
    assert msg
    assert socket
    await socket.close()

WebSocketGateway(path="/ws", handler=home)
PARAMETER DESCRIPTION
path

Relative path of the WebSocketGateway. The path can contain parameters in a dictionary like format and if the path is not provided, it will default to /.

Example

WebSocketGateway()

Example with parameters

WebSocketGateway(path="/{age: int}")

TYPE: Optional[str] DEFAULT: None

handler

An instance of handler.

TYPE: Union[WebSocketHandler, View]

name

The name for the Gateway. The name can be reversed by url_path_for().

TYPE: Optional[str] DEFAULT: None

parent

Who owns the Gateway. If not specified, the application automatically it assign it.

This is directly related with the application levels.

TYPE: Optional[ParentType] DEFAULT: None

dependencies

A dictionary of string and Inject instances enable application level dependency injection.

TYPE: Optional[Dependencies] DEFAULT: None

middleware

A list of middleware to run for every request. The middlewares of a Gateway will be checked from top-down or Starlette Middleware as they are both converted internally. Read more about Python Protocols.

TYPE: Optional[List[Middleware]] DEFAULT: None

interceptors

A list of interceptors to serve the application incoming requests (HTTP and Websockets).

TYPE: Optional[Sequence[Interceptor]] DEFAULT: None

permissions

A list of permissions to serve the application incoming requests (HTTP and Websockets).

TYPE: Optional[Sequence[Permission]] DEFAULT: None

exception_handlers

A dictionary of exception types (or custom exceptions) and the handler functions on an application top level. Exception handler callables should be of the form of handler(request, exc) -> response and may be be either standard functions, or async functions.

TYPE: Optional[ExceptionHandlerMap] DEFAULT: None

is_from_router

Used by the .add_router() function of the Esmerald class indicating if the Gateway is coming from a router.

TYPE: bool DEFAULT: False

Source code in esmerald/routing/gateways.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def __init__(
    self,
    path: Annotated[
        Optional[str],
        Doc(
            """
            Relative path of the `WebSocketGateway`.
            The path can contain parameters in a dictionary like format
            and if the path is not provided, it will default to `/`.

            **Example**

            ```python
            WebSocketGateway()
            ```

            **Example with parameters**

            ```python
            WebSocketGateway(path="/{age: int}")
            ```
            """
        ),
    ] = None,
    *,
    handler: Annotated[
        Union["WebSocketHandler", View],
        Doc(
            """
        An instance of [handler](https://esmerald.dev/routing/handlers/#websocket-handler).
        """
        ),
    ],
    name: Annotated[
        Optional[str],
        Doc(
            """
            The name for the Gateway. The name can be reversed by `url_path_for()`.
            """
        ),
    ] = None,
    parent: Annotated[
        Optional["ParentType"],
        Doc(
            """
            Who owns the Gateway. If not specified, the application automatically it assign it.

            This is directly related with the [application levels](https://esmerald.dev/application/levels/).
            """
        ),
    ] = None,
    dependencies: Annotated[
        Optional["Dependencies"],
        Doc(
            """
            A dictionary of string and [Inject](https://esmerald.dev/dependencies/) instances enable application level dependency injection.
            """
        ),
    ] = None,
    middleware: Annotated[
        Optional[List["Middleware"]],
        Doc(
            """
            A list of middleware to run for every request. The middlewares of a Gateway will be checked from top-down or [Starlette Middleware](https://www.starlette.io/middleware/) as they are both converted internally. Read more about [Python Protocols](https://peps.python.org/pep-0544/).
            """
        ),
    ] = None,
    interceptors: Annotated[
        Optional[Sequence["Interceptor"]],
        Doc(
            """
            A list of [interceptors](https://esmerald.dev/interceptors/) to serve the application incoming requests (HTTP and Websockets).
            """
        ),
    ] = None,
    permissions: Annotated[
        Optional[Sequence["Permission"]],
        Doc(
            """
            A list of [permissions](https://esmerald.dev/permissions/) to serve the application incoming requests (HTTP and Websockets).
            """
        ),
    ] = None,
    exception_handlers: Annotated[
        Optional["ExceptionHandlerMap"],
        Doc(
            """
            A dictionary of [exception types](https://esmerald.dev/exceptions/) (or custom exceptions) and the handler functions on an application top level. Exception handler callables should be of the form of `handler(request, exc) -> response` and may be be either standard functions, or async functions.
            """
        ),
    ] = None,
    is_from_router: Annotated[
        bool,
        Doc(
            """
            Used by the `.add_router()` function of the `Esmerald` class indicating if the
            Gateway is coming from a router.
            """
        ),
    ] = False,
) -> None:
    if not path:
        path = "/"
    if is_class_and_subclass(handler, View):
        handler = handler(parent=self)  # type: ignore

    if not is_from_router:
        self.path = clean_path(path + handler.path)
    else:
        self.path = clean_path(path)

    if not name:
        if not isinstance(handler, View):
            name = clean_string(handler.fn.__name__)
        else:
            name = clean_string(handler.__class__.__name__)

    # Handle middleware
    self.middleware = middleware or []
    self._middleware: List["Middleware"] = self.handle_middleware(
        handler=handler, base_middleware=self.middleware
    )
    self.is_middleware: bool = False

    super().__init__(
        path=self.path,
        endpoint=cast("Callable", handler),
        name=name,
        middleware=self._middleware,
    )
    """
    A "bridge" to a handler and router mapping functionality.
    Since the default Starlette Route endpoint does not understand the Esmerald handlers,
    the Gateway bridges both functionalities and adds an extra "flair" to be compliant with both class based views and decorated function views.
    """
    self._interceptors: Union[List["Interceptor"], "VoidType"] = Void
    self.handler = handler
    self.dependencies = dependencies or {}
    self.interceptors = interceptors or []
    self.permissions = permissions or []
    self.exception_handlers = exception_handlers or {}
    self.include_in_schema = False
    self.parent = parent
    (
        handler.path_regex,
        handler.path_format,
        handler.param_convertors,
    ) = compile_path(self.path)

path instance-attribute

path = clean_path(path + path)

handler instance-attribute

handler = handler

parent instance-attribute

parent = parent

dependencies instance-attribute

dependencies = dependencies or {}

middleware instance-attribute

middleware = middleware or []

interceptors instance-attribute

interceptors = interceptors or []

permissions instance-attribute

permissions = permissions or []

exception_handlers instance-attribute

exception_handlers = exception_handlers or {}