Перейти к содержанию

View class

Warning

The current page still doesn't have a translation for this language.

But you can help translating it: Contributing.

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

The View server as the base of alll object oriented views of Esmerald such as APIView, SimpleAPIView and all the generics.

esmerald.routing.views.View

View(parent)

View class object acts as the base of all the object oriented views used by Esmerald.

The View contains all the available parameters that can be applied on a global level when subclassing it.

Example

from esmerald.routing.views import View


class CustomView(View):
    ...
PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers

esmerald.APIView

APIView(parent)

Bases: View

The Esmerald APIView class.

The parameters available are the ones provided by the parent, View class.

Example

from esmerald.permissions import DenyAll, IsAuthenticated
from esmerald.requests import Request
from esmerald.responses import JSONResponse
from esmerald.routing.apis.views import APIView
from esmerald.routing.handlers import delete, get, post


class UserAPIView(APIView):
    path = "/users"
    permissions = [IsAuthenticated]

    @get(path="/")
    async def all_users(self, request: Request) -> JSONResponse:
        # logic to get all users here
        users = ...

        return JSONResponse({"users": users})

    @get(path="/deny", permissions=[DenyAll], description="API description")
    async def all_usersa(self, request: Request) -> JSONResponse:
        ...

    @get(path="/allow")
    async def all_usersb(self, request: Request) -> JSONResponse:
        users = ...
        return JSONResponse({"Total Users": users.count()})

    @post(path="/create")
    async def create_user(self, request: Request) -> None:
        # logic to create a user goes here
        ...

    @delete(path="/delete/{user_id}")
    async def delete_user(self, request: Request, user_id: str) -> None:
        # logic to delete a user goes here
        ...
PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers

esmerald.SimpleAPIView

SimpleAPIView(parent)

Bases: View, MethodMixin

The Esmerald SimpleAPIView class.

This class has the same available parameters as the parent, View.

Example

from esmerald import SimpleAPIView, delete, get, patch, post, put


class UserAPI(SimpleAPIView):
    @get()
    async def get(self) -> str:
        ...

    @post()
    async def post(self) -> str:
        ...

    @put()
    async def put(self) -> str:
        ...

    @patch()
    async def patch(self) -> str:
        ...

    @delete()
    async def delete(self) -> None:
        ...
PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

http_allowed_methods class-attribute instance-attribute

http_allowed_methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

Allowed methods for the given base class.

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

is_method_allowed classmethod

is_method_allowed(name, base, method, error_message=None)
PARAMETER DESCRIPTION
name

String referring to the http verb (method) being validated.

Example: get, post.

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

error_message

An error message to be displayed upon the error being thrown.

TYPE: Union[str, None] DEFAULT: None

Source code in esmerald/routing/apis/_mixins.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@classmethod
def is_method_allowed(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            String referring to the http verb (method) being validated.

            Example: `get`, `post`.
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    error_message: Annotated[
        Union[str, None],
        Doc(
            """
            An error message to be displayed upon the error being thrown.
            """
        ),
    ] = None,
) -> bool:
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            hasattr(cls, "extra_allowed")
            and cls.extra_allowed is not None
            and name.lower() in cls.extra_allowed
        ):
            return True

        if name.lower() not in cls.http_allowed_methods:
            if error_message is None:
                error_message = ", ".join(cls.http_allowed_methods)

            raise ImproperlyConfigured(
                f"{cls.__name__} only allows functions with the name(s) `{error_message}` to be implemented, got `{name.lower()}` instead."
            )
        elif name.lower() != method.__type__.lower():
            raise ImproperlyConfigured(
                f"The function '{name.lower()}' must implement the '{name.lower()}()' handler, got '{method.__type__.lower()}()' instead."
            )
    return True

is_signature_valid classmethod

is_signature_valid(name, base, method, signature_type)

Validates if the signature of a given function is of type signature_type.

PARAMETER DESCRIPTION
name

The name of the function

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

signature_type

The annotation being checked against.

TYPE: Any

Source code in esmerald/routing/apis/_mixins.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
@classmethod
def is_signature_valid(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            The name of the function
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    signature_type: Annotated[
        Any,
        Doc(
            """
            The annotation being checked against.
            """
        ),
    ],
) -> bool:
    """
    Validates if the signature of a given function is of type `signature_type`.
    """
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            not method.handler_signature.return_annotation
            or method.handler_signature.return_annotation is None
        ):
            return True

        if not is_class_and_subclass(
            method.handler_signature.return_annotation, signature_type
        ):
            raise ImproperlyConfigured(
                f"{cls.__name__} must return type lists, got {type(method.handler_signature.return_annotation)} instead."
            )
    return True

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers

esmerald.routing.apis.generics.CreateAPIView

CreateAPIView(parent)

Bases: GenericMixin, SimpleAPIView

This class has the same available parameters as the parent, View but subclassing the SimpleAPIView.

from esmerald.routing.apis.generics import CreateAPIView

Example

from esmerald import patch, post, put
from esmerald.routing.apis.generics import CreateAPIView


class UserAPI(CreateAPIView):
    '''
    CreateAPIView only allows the `post`, `put` and `patch`
    to be used by default.
    '''

    @post()
    async def post(self) -> str:
        ...

    @put()
    async def put(self) -> str:
        ...

    @patch()
    async def patch(self) -> str:
    ...
PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

http_allowed_methods class-attribute instance-attribute

http_allowed_methods = ['post', 'put', 'patch']

Allowed methods for the given base class.

is_method_allowed classmethod

is_method_allowed(name, base, method, error_message=None)
PARAMETER DESCRIPTION
name

String referring to the http verb (method) being validated.

Example: get, post.

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

error_message

An error message to be displayed upon the error being thrown.

TYPE: Union[str, None] DEFAULT: None

Source code in esmerald/routing/apis/_mixins.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@classmethod
def is_method_allowed(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            String referring to the http verb (method) being validated.

            Example: `get`, `post`.
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    error_message: Annotated[
        Union[str, None],
        Doc(
            """
            An error message to be displayed upon the error being thrown.
            """
        ),
    ] = None,
) -> bool:
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            hasattr(cls, "extra_allowed")
            and cls.extra_allowed is not None
            and name.lower() in cls.extra_allowed
        ):
            return True

        if name.lower() not in cls.http_allowed_methods:
            if error_message is None:
                error_message = ", ".join(cls.http_allowed_methods)

            raise ImproperlyConfigured(
                f"{cls.__name__} only allows functions with the name(s) `{error_message}` to be implemented, got `{name.lower()}` instead."
            )
        elif name.lower() != method.__type__.lower():
            raise ImproperlyConfigured(
                f"The function '{name.lower()}' must implement the '{name.lower()}()' handler, got '{method.__type__.lower()}()' instead."
            )
    return True

is_signature_valid classmethod

is_signature_valid(name, base, method, signature_type)

Validates if the signature of a given function is of type signature_type.

PARAMETER DESCRIPTION
name

The name of the function

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

signature_type

The annotation being checked against.

TYPE: Any

Source code in esmerald/routing/apis/_mixins.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
@classmethod
def is_signature_valid(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            The name of the function
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    signature_type: Annotated[
        Any,
        Doc(
            """
            The annotation being checked against.
            """
        ),
    ],
) -> bool:
    """
    Validates if the signature of a given function is of type `signature_type`.
    """
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            not method.handler_signature.return_annotation
            or method.handler_signature.return_annotation is None
        ):
            return True

        if not is_class_and_subclass(
            method.handler_signature.return_annotation, signature_type
        ):
            raise ImproperlyConfigured(
                f"{cls.__name__} must return type lists, got {type(method.handler_signature.return_annotation)} instead."
            )
    return True

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers

esmerald.routing.apis.generics.ReadAPIView

ReadAPIView(parent)

Bases: GenericMixin, SimpleAPIView

This class has the same available parameters as the parent, View but subclassing the SimpleAPIView.

from esmerald.routing.apis.generics import ReadAPIView

Example

from esmerald import get
from esmerald.routing.apis.generics import ReadAPIView


class UserAPI(ReadAPIView):
    '''
    ReadAPIView only allows the `get` to be used by default..
    '''

    @get()
    async def get(self) -> None:
        ...
PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

http_allowed_methods class-attribute instance-attribute

http_allowed_methods = ['get']

Allowed methods for the given base class.

is_method_allowed classmethod

is_method_allowed(name, base, method, error_message=None)
PARAMETER DESCRIPTION
name

String referring to the http verb (method) being validated.

Example: get, post.

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

error_message

An error message to be displayed upon the error being thrown.

TYPE: Union[str, None] DEFAULT: None

Source code in esmerald/routing/apis/_mixins.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@classmethod
def is_method_allowed(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            String referring to the http verb (method) being validated.

            Example: `get`, `post`.
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    error_message: Annotated[
        Union[str, None],
        Doc(
            """
            An error message to be displayed upon the error being thrown.
            """
        ),
    ] = None,
) -> bool:
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            hasattr(cls, "extra_allowed")
            and cls.extra_allowed is not None
            and name.lower() in cls.extra_allowed
        ):
            return True

        if name.lower() not in cls.http_allowed_methods:
            if error_message is None:
                error_message = ", ".join(cls.http_allowed_methods)

            raise ImproperlyConfigured(
                f"{cls.__name__} only allows functions with the name(s) `{error_message}` to be implemented, got `{name.lower()}` instead."
            )
        elif name.lower() != method.__type__.lower():
            raise ImproperlyConfigured(
                f"The function '{name.lower()}' must implement the '{name.lower()}()' handler, got '{method.__type__.lower()}()' instead."
            )
    return True

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers

esmerald.routing.apis.generics.DeleteAPIView

DeleteAPIView(parent)

Bases: GenericMixin, SimpleAPIView

This class has the same available parameters as the parent, View but subclassing the SimpleAPIView.

from esmerald.routing.apis.generics import CreateAPIView

Example

from esmerald import delete
from esmerald.routing.apis.generics import DeleteAPIView


class UserAPI(DeleteAPIView):
    '''
    DeleteAPIView only allows the `delete` to be used by default.
    '''

    @delete()
    async def delete(self) -> None:
        ...
PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

http_allowed_methods class-attribute instance-attribute

http_allowed_methods = ['delete']

Allowed methods for the given base class.

is_method_allowed classmethod

is_method_allowed(name, base, method, error_message=None)
PARAMETER DESCRIPTION
name

String referring to the http verb (method) being validated.

Example: get, post.

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

error_message

An error message to be displayed upon the error being thrown.

TYPE: Union[str, None] DEFAULT: None

Source code in esmerald/routing/apis/_mixins.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@classmethod
def is_method_allowed(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            String referring to the http verb (method) being validated.

            Example: `get`, `post`.
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    error_message: Annotated[
        Union[str, None],
        Doc(
            """
            An error message to be displayed upon the error being thrown.
            """
        ),
    ] = None,
) -> bool:
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            hasattr(cls, "extra_allowed")
            and cls.extra_allowed is not None
            and name.lower() in cls.extra_allowed
        ):
            return True

        if name.lower() not in cls.http_allowed_methods:
            if error_message is None:
                error_message = ", ".join(cls.http_allowed_methods)

            raise ImproperlyConfigured(
                f"{cls.__name__} only allows functions with the name(s) `{error_message}` to be implemented, got `{name.lower()}` instead."
            )
        elif name.lower() != method.__type__.lower():
            raise ImproperlyConfigured(
                f"The function '{name.lower()}' must implement the '{name.lower()}()' handler, got '{method.__type__.lower()}()' instead."
            )
    return True

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers

esmerald.routing.apis.generics.ListAPIView

ListAPIView(parent)

Bases: GenericMixin, ListView

Only allows the return to be lists.

PARAMETER DESCRIPTION
parent

TYPE: Union[Gateway, WebSocketGateway]

Source code in esmerald/routing/apis/base.py
251
252
253
254
255
256
257
258
259
260
261
def __init__(self, parent: Union["Gateway", "WebSocketGateway"]) -> None:
    for key in self.__slots__:
        if not hasattr(self, key):
            setattr(self, key, None)

    self.path = clean_path(self.path or "/")
    self.path_regex, self.path_format, self.param_convertors, _ = compile_path(self.path)
    self.parent = parent
    self.route_map: Dict[str, Tuple["HTTPHandler", "TransformerModel"]] = {}
    self.operation_id: Optional[str] = None
    self.methods: List[str] = []

http_allowed_methods class-attribute instance-attribute

http_allowed_methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

Allowed methods for the given base class.

path instance-attribute

path = clean_path(path or '/')

Relative path of the Gateway. The path can contain parameters in a dictionary like format.

dependencies instance-attribute

dependencies

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

exception_handlers instance-attribute

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.

permissions instance-attribute

permissions

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

interceptors instance-attribute

interceptors

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

middleware instance-attribute

middleware

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

parent instance-attribute

parent = parent

Used internally by Esmerald to recognise and build the application levels.

Tip

Unless you know what are you doing, it is advisable not to touch this.

response_class instance-attribute

response_class

Default response class to be used within the Esmerald application.

Read more about the Responses and how to use them.

Example

from esmerald import APIView, JSONResponse


class MyView(APIView):
    response_class = JSONResponse

response_cookies instance-attribute

response_cookies

A sequence of esmerald.datastructures.Cookie objects.

Read more about the Cookies.

Example

from esmerald import APIView
from esmerald.datastructures import Cookie

response_cookies=[
    Cookie(
        key="csrf",
        value="CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz",
        max_age=3000,
        httponly=True,
    )
]

class MyView(APIView):
    response_cookies = response_cookies

response_headers instance-attribute

response_headers

A mapping of esmerald.datastructures.ResponseHeader objects.

Read more about the ResponseHeader.

Example

from esmerald import APIView
from esmerald.datastructures import ResponseHeader

response_headers={
    "authorize": ResponseHeader(value="granted")
}

class MyView(APIView):
    response_headers = response_headers

tags instance-attribute

tags

A list of strings tags to be applied to the path operation.

It will be added to the generated OpenAPI documentation.

Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.

include_in_schema instance-attribute

include_in_schema

Boolean flag indicating if it should be added to the OpenAPI docs.

security instance-attribute

security

Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.

The Esmerald security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass esmerald.openapi.security.base.HTTPBase object.

deprecated instance-attribute

deprecated

Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..

route_map instance-attribute

route_map = {}

operation_id instance-attribute

operation_id = None

methods instance-attribute

methods = []

is_method_allowed classmethod

is_method_allowed(name, base, method, error_message=None)
PARAMETER DESCRIPTION
name

String referring to the http verb (method) being validated.

Example: get, post.

TYPE: str

base

The base class being checked against. Internally, Esmerald checks against the bases of the class upon the __new__ is called.

TYPE: Any

method

Uusally referred to a handler being validated.

TYPE: Callable[..., Any]

error_message

An error message to be displayed upon the error being thrown.

TYPE: Union[str, None] DEFAULT: None

Source code in esmerald/routing/apis/_mixins.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@classmethod
def is_method_allowed(
    cls,
    name: Annotated[
        str,
        Doc(
            """
            String referring to the http verb (method) being validated.

            Example: `get`, `post`.
            """
        ),
    ],
    base: Annotated[
        Any,
        Doc(
            """
            The base class being checked against.
            Internally, Esmerald checks against the bases of the class
            upon the `__new__` is called.
            """
        ),
    ],
    method: Annotated[
        Callable[..., Any],
        Doc(
            """
            Uusally referred to a [handler](https://esmerald.dev/routing/handlers/)
            being validated.
            """
        ),
    ],
    error_message: Annotated[
        Union[str, None],
        Doc(
            """
            An error message to be displayed upon the error being thrown.
            """
        ),
    ] = None,
) -> bool:
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if name not in dir(base) and isinstance(
        method,
        (HTTPHandler, WebSocketHandler, WebhookHandler),
    ):
        if (
            hasattr(cls, "extra_allowed")
            and cls.extra_allowed is not None
            and name.lower() in cls.extra_allowed
        ):
            return True

        if name.lower() not in cls.http_allowed_methods:
            if error_message is None:
                error_message = ", ".join(cls.http_allowed_methods)

            raise ImproperlyConfigured(
                f"{cls.__name__} only allows functions with the name(s) `{error_message}` to be implemented, got `{name.lower()}` instead."
            )
        elif name.lower() != method.__type__.lower():
            raise ImproperlyConfigured(
                f"The function '{name.lower()}' must implement the '{name.lower()}()' handler, got '{method.__type__.lower()}()' instead."
            )
    return True

get_route_middleware

get_route_middleware(handler)

Gets the list of extended middlewares for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

The handler being checked against.

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_route_middleware(
    self,
    handler: Annotated[
        Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) being checked against.
            """
        ),
    ],
) -> None:
    """
    Gets the list of extended middlewares for the handler starting from the last
    to the first by reversing the list
    """
    for middleware in reversed(self.middleware):
        handler.middleware.insert(0, middleware)

get_exception_handlers

get_exception_handlers(handler)

Gets the dict of extended exception handlers for the handler starting from the last to the first by reversing the list

PARAMETER DESCRIPTION
handler

TYPE: Union[HTTPHandler, WebSocketHandler, WebhookHandler]

Source code in esmerald/routing/apis/base.py
340
341
342
343
344
345
346
347
348
def get_exception_handlers(
    self, handler: Union["HTTPHandler", "WebSocketHandler", "WebhookHandler"]
) -> "ExceptionHandlerMap":
    """
    Gets the dict of extended exception handlers for the handler starting from the last
    to the first by reversing the list
    """
    exception_handlers = {**self.exception_handlers, **handler.exception_handlers}
    return cast("ExceptionHandlerMap", exception_handlers)

get_routes

get_routes(path=None, name=None, middleware=None, permissions=None, interceptors=None, exception_handlers=None, include_in_schema=None)

Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.

PARAMETER DESCRIPTION
path

TYPE: Union[str, None] DEFAULT: None

name

TYPE: Union[str, None] DEFAULT: None

middleware

TYPE: Union[Sequence[Middleware], List[Middleware], None] DEFAULT: None

permissions

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

interceptors

TYPE: Union[Sequence[Interceptor], List[Interceptor], None] DEFAULT: None

exception_handlers

TYPE: Union[ExceptionHandlerMap, None] DEFAULT: None

include_in_schema

TYPE: Union[bool, None] DEFAULT: None

Source code in esmerald/routing/apis/base.py
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
def get_routes(
    self,
    path: Union[str, None] = None,
    name: Union[str, None] = None,
    middleware: Union[Sequence["Middleware"], List["Middleware"], None] = None,
    permissions: Union[Sequence["Permission"], Any, None] = None,
    interceptors: Union[Sequence["Interceptor"], List["Interceptor"], None] = None,
    exception_handlers: Union["ExceptionHandlerMap", None] = None,
    include_in_schema: Union[bool, None] = None,
) -> List[Union["Gateway", "WebSocketGateway"]]:
    """
    Builds the routes and wraps them in a list containing the Gateway and WebSocketGateway.
    """
    from esmerald.routing.gateways import Gateway, WebSocketGateway
    from esmerald.routing.router import HTTPHandler, WebhookHandler, WebSocketHandler

    if path is None:
        path = "/"

    route_handlers: List[Union[HTTPHandler, WebSocketHandler, WebhookHandler]] = (
        self.get_route_handlers()
    )
    handlers: List[Union[Gateway, WebSocketGateway]] = []

    for route_handler in route_handlers:
        route_path: Union[Gateway, WebSocketGateway]

        route_kwargs = {
            "path": path,
            "handler": route_handler,
            "name": name or route_handler.fn.__name__,
            "middleware": middleware,
            "interceptors": interceptors,
            "permissions": permissions,
            "exception_handlers": exception_handlers,
        }
        route_path = (
            Gateway(**route_kwargs)  # type: ignore
            if isinstance(route_handler, HTTPHandler)
            else WebSocketGateway(**route_kwargs)  # type: ignore
        )

        if isinstance(route_path, Gateway):
            if include_in_schema is None:
                route_path.include_in_schema = (
                    route_handler.include_in_schema
                    if route_handler.include_in_schema is not None
                    else include_in_schema
                )
            else:
                route_path.include_in_schema = include_in_schema

        handlers.append(route_path)
    return handlers