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

Gateway 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 Gateway that contains all the parameters, attributes and functions.

How to import

from esmerald import Gateway

esmerald.Gateway

Gateway(path=None, *, handler, name=None, include_in_schema=True, parent=None, dependencies=None, middleware=None, interceptors=None, permissions=None, exception_handlers=None, deprecated=None, is_from_router=False, security=None, tags=None, operation_id=None)

Bases: Path, Dispatcher, BaseMiddleware, GatewayUtil

Gateway object class used by Esmerald routes.

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

Read more about Gateway and how to use it.

Example

from esmerald import Esmerald. get

@get()
async def home() -> str:
    return "Hello, World!"

Gateway(path="/home", handler=home)
PARAMETER DESCRIPTION
path

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

Example

Gateway()

Example with parameters

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

TYPE: Optional[str] DEFAULT: None

handler

An instance of handler.

TYPE: Union[HTTPHandler, View]

name

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

TYPE: Optional[str] DEFAULT: None

include_in_schema

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

TYPE: bool DEFAULT: True

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

deprecated

Boolean flag for indicating the deprecation of the Gateway and to display it in the OpenAPI documentation..

TYPE: Optional[bool] 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

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.

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

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.

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

operation_id

Unique operation id that allows distinguishing the same handler in different Gateways.

Used for OpenAPI purposes.

TYPE: Optional[str] DEFAULT: None

Source code in esmerald/routing/gateways.py
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __init__(
    self,
    path: Annotated[
        Optional[str],
        Doc(
            """
            Relative path of the `Gateway`.
            The path can contain parameters in a dictionary like format
            and if the path is not provided, it will default to `/`.

            **Example**

            ```python
            Gateway()
            ```

            **Example with parameters**

            ```python
            Gateway(path="/{age: int}")
            ```
            """
        ),
    ] = None,
    *,
    handler: Annotated[
        Union["HTTPHandler", View],
        Doc(
            """
        An instance of [handler](https://esmerald.dev/routing/handlers/#http-handlers).
        """
        ),
    ],
    name: Annotated[
        Optional[str],
        Doc(
            """
            The name for the Gateway. The name can be reversed by `path_for()`.
            """
        ),
    ] = None,
    include_in_schema: Annotated[
        bool,
        Doc(
            """
            Boolean flag indicating if it should be added to the OpenAPI docs.
            """
        ),
    ] = True,
    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,
    deprecated: Annotated[
        Optional[bool],
        Doc(
            """
            Boolean flag for indicating the deprecation of the Gateway and to display it
            in the OpenAPI documentation..
            """
        ),
    ] = 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,
    security: Annotated[
        Optional[Sequence["SecurityScheme"]],
        Doc(
            """
            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](https://esmerald.dev/openapi/) is available to automatically used.

            The security can be applied also on a [level basis](https://esmerald.dev/application/levels/).

            For custom security objects, you **must** subclass
            `esmerald.openapi.security.base.HTTPBase` object.
            """
        ),
    ] = None,
    tags: Annotated[
        Optional[Sequence[str]],
        Doc(
            """
            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](https://esmerald.dev/application/levels/), which means
            these tags on a Esmerald instance, means it will be added to every route even
            if those routes also contain tags.
            """
        ),
    ] = None,
    operation_id: Annotated[
        Optional[str],
        Doc(
            """
            Unique operation id that allows distinguishing the same handler in different Gateways.

            Used for OpenAPI purposes.
            """
        ),
    ] = None,
) -> None:
    if not path:
        path = "/"
    if is_class_and_subclass(handler, View):
        handler = handler(parent=self)  # type: ignore

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

    self.methods = getattr(handler, "http_methods", None)

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

    # Handle middleware
    self.middleware = middleware or []
    self._middleware: List["Middleware"] = self.handle_middleware(
        handler=handler, base_middleware=self.middleware
    )
    super().__init__(
        path=self.path,
        handler=cast(Callable, handler),
        include_in_schema=include_in_schema,
        name=name,
        methods=self.methods,
        middleware=self._middleware,
        exception_handlers=exception_handlers,
    )
    """
    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._interceptors: Union[List["Interceptor"], "VoidType"] = Void
    self.name = name
    self.handler = cast("Callable", handler)
    self.dependencies = dependencies or {}
    self.interceptors: Sequence["Interceptor"] = interceptors or []
    self.permissions: Sequence["Permission"] = permissions or []  # type: ignore
    self.response_class = None
    self.response_cookies = None
    self.response_headers = None
    self.deprecated = deprecated
    self.parent = parent
    self.security = security
    self.tags = tags or []
    (handler.path_regex, handler.path_format, handler.param_convertors, _) = compile_path(
        self.path
    )
    self.operation_id = operation_id

    if self.is_handler(self.handler):  # type: ignore
        self.handler.name = self.name

        if self.operation_id or handler.operation_id is not None:
            handler_id = self.generate_operation_id(
                name=self.name, handler=self.handler  # type: ignore
            )
            self.operation_id = f"{operation_id}_{handler_id}" if operation_id else handler_id

        elif not handler.operation_id:
            handler.operation_id = self.generate_operation_id(
                name=self.name, handler=self.handler  # type: ignore
            )

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 = permissions or []

exception_handlers instance-attribute

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

include_in_schema instance-attribute

include_in_schema = include_in_schema

deprecated instance-attribute

deprecated = deprecated

security instance-attribute

security = security

tags instance-attribute

tags = tags or []