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, before_request=None, after_request=None, is_from_router=False)

Bases: WebSocketPath, Dispatcher, 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, Type[View], Type[WebSocketHandler]]

name

The name for the Gateway. The name can be reversed by 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 Lilya 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

before_request

A list of events that are trigger after the application processes the request.

Read more about the events.

TYPE: Union[Sequence[Callable[[], Any]], None] DEFAULT: None

after_request

A list of events that are trigger after the application processes the request.

Read more about the events.

TYPE: Union[Sequence[Callable[[], Any]], None] 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
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, Type[View], Type["WebSocketHandler"]],
        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 `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 [Lilya Middleware](https://www.lilya.dev/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,
    before_request: Annotated[
        Union[Sequence[Callable[[], Any]], None],
        Doc(
            """
            A `list` of events that are trigger after the application
            processes the request.

            Read more about the [events](https://lilya.dev/lifespan/).
            """
        ),
    ] = None,
    after_request: Annotated[
        Union[Sequence[Callable[[], Any]], None],
        Doc(
            """
            A `list` of events that are trigger after the application
            processes the request.

            Read more about the [events](https://lilya.dev/lifespan/).
            """
        ),
    ] = 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)
    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 = handler.name or clean_string(handler.fn.__name__)  # type: ignore
        else:
            name = clean_string(handler.__class__.__name__)

    else:
        route_name_list = [name]
        if not isinstance(handler, View) and handler.name:  # type: ignore
            route_name_list.append(handler.name)  # type: ignore
            name = ":".join(route_name_list)

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

    self.__base_permissions__ = permissions or []
    self.__lilya_permissions__ = [
        wrap_permission(permission)
        for permission in self.__base_permissions__ or []
        if is_lilya_permission(permission)
    ]
    super().__init__(
        path=self.path,
        handler=cast("Callable", handler),
        name=name,
        middleware=self._middleware,
        exception_handlers=exception_handlers,
        permissions=self.__lilya_permissions__,  # type: ignore
        before_request=before_request,
        after_request=after_request,
    )
    """
    A "bridge" to a handler and router mapping functionality.
    Since the default Lilya Route handler 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.before_request = before_request if before_request is not None else []
    self.after_request = after_request if after_request is not None else []

    if self.before_request:
        if handler.before_request is None:
            handler.before_request = []

        for before in self.before_request:
            handler.before_request.insert(0, before)

    if self.after_request:
        if handler.after_request is None:
            handler.after_request = []

        for after in self.after_request:
            handler.after_request.append(after)

    self._interceptors: Union[list["Interceptor"], "VoidType"] = Void
    self.handler = cast("Callable", handler)
    self.dependencies = dependencies or {}
    self.interceptors = interceptors or []

    # Filter out the lilya unique permissions
    if self.__lilya_permissions__:
        self.lilya_permissions: Any = dict(enumerate(self.__lilya_permissions__))
        if not self.handler.lilya_permissions:
            self.handler.lilya_permissions = self.lilya_permissions
        else:
            handler_lilya_permissions = {
                index + len(self.lilya_permissions): permission
                for index, permission in enumerate(self.lilya_permissions.values())
            }
            self.handler.lilya_permissions = {
                **self.lilya_permissions,
                **handler_lilya_permissions,
            }
    else:
        self.lilya_permissions = {}

    # Filter out the esmerald unique permissions
    if self.__base_permissions__:
        self.permissions: Any = {
            index: wrap_permission(permission)
            for index, permission in enumerate(permissions)
            if is_esmerald_permission(permission)
        }

        if not self.handler.permissions:
            self.handler.permissions = self.permissions
        else:
            handler_permissions = {
                index + len(self.permissions): permission
                for index, permission in enumerate(self.permissions.values())
            }
            self.handler.permissions = {
                **self.permissions,
                **handler_permissions,
            }
    else:
        self.permissions = {}

    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 = cast('Callable', 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 = {index: wrap_permission(permission)for (index, permission) in enumerate(permissions) if is_esmerald_permission(permission)}

exception_handlers instance-attribute

exception_handlers = {} if exception_handlers is None else dict(exception_handlers)