Skip to content

Include class

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

How to import

from esmerald import Include

esmerald.Include

Include(path=None, app=None, name=None, routes=None, namespace=None, pattern=None, parent=None, dependencies=None, interceptors=None, permissions=None, exception_handlers=None, middleware=None, before_request=None, after_request=None, include_in_schema=True, deprecated=None, security=None, tags=None, redirect_slashes=True)

Bases: Include

Include object class that allows scalability and modularity to happen with elegance.

Read more about the Include to understand what can be done.

Include manages routes as a list or as a namespace but not both or a ImproperlyConfigured is raised.

PARAMETER DESCRIPTION
path

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

Example

Include()

Example with parameters

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

TYPE: Optional[str] DEFAULT: None

app

An application can be anything that is treated as an ASGI application. For example, it can be a ChildEsmerald, another Esmerald, a Router or even an external WSGI application (Django, Flask...)

The app is a parameter that makes the Include extremely powerful when it comes to integrate with ease with whatever Python stack you want and need.

Example

from esmerald import Esmerald, ChildEsmerald, Include

Esmerald(
    routes=[
        Include('/child', app=ChildEsmerald(...))
    ]
)

Example with a WSGI framework

from flask import Flask, escape, request

from esmerald import Esmerald, Gateway, Include, Request, get
from esmerald.middleware.wsgi import WSGIMiddleware

flask_app = Flask(__name__)


@flask_app.route("/")
def flask_main():
    name = request.args.get("name", "Esmerald")
    return f"Hello, {escape(name)} from your Flask integrated!"


@get("/home/{name:str}")
async def home(request: Request) -> dict:
    name = request.path_params["name"]
    return {"name": escape(name)}


app = Esmerald(
    routes=[
        Gateway(handler=home),
        Include("/flask", WSGIMiddleware(flask_app)),
    ]
)

TYPE: ASGIApp | str DEFAULT: None

name

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

TYPE: Optional[str] DEFAULT: None

routes

A global list of esmerald routes. Those routes may vary and those can be Gateway, WebSocketGateWay or even another Include.

This is also an entry-point for the routes of the Include but it does not rely on only one level.

Read more about how to use and leverage the Esmerald routing system.

Example

from esmerald import Esmerald, Gateway, Request, get, Include


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


@get()
async def another(request: Request) -> str:
    return "Hello, another!"

app = Esmerald(
    routes=[
        Gateway(handler=homepage)
        Include("/nested", routes=[
            Gateway(handler=another)
        ])
    ]
)

Note

The Include is very powerful and this example is not enough to understand what more things you can do. Read in more detail about this.

TYPE: Optional[Sequence[Union[APIGateHandler, Include, HTTPHandler, WebSocketHandler]]] DEFAULT: None

namespace

A string with a qualified namespace from where the URLs should be loaded.

The namespace is an alternative to routes parameter. When a namespace is specified and a routes as well, an ImproperlyCOnfigured exception is raised as it can only be one or another.

The namespace can be extremely useful as it avoids the imports from the top of the file that can lead to partially imported errors.

When using a namespace, the Include will look for the default route_patterns list in the imported namespace (object) unless a different pattern is specified.

Example

Assuming there is a file with some routes located at myapp/auth/urls.py.

myapp/auth/urls.py
from esmerald import Gateway
from .view import welcome, create_user

route_patterns = [
    Gateway(handler=welcome, name="welcome"),
    Gateway(handler=create_user, name="create-user"),
]

Using the namespace to import the URLs.

from esmerald import Include

Include("/auth", namespace="myapp.auth.urls")

TYPE: Optional[str] DEFAULT: None

pattern

A string pattern information from where the urls shall be read from.

By default, the when using the namespace it will lookup for a route_patterns but somethimes you might want to opt for a different name and this is where the pattern comes along.

Example

Assuming there is a file with some routes located at myapp/auth/urls.py. The urls will be placed inside a urls list.

myapp/auth/urls.py
from esmerald import Gateway
from .view import welcome, create_user

urls = [
    Gateway(handler=welcome, name="welcome"),
    Gateway(handler=create_user, name="create-user"),
]

Using the namespace to import the URLs.

from esmerald import Include

Include("/auth", namespace="myapp.auth.urls", pattern="urls")

TYPE: Optional[str] DEFAULT: None

parent

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

This is directly related with the application levels.

TYPE: Optional[ParentType] DEFAULT: None

dependencies

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

TYPE: Optional[Dependencies] DEFAULT: None

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

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.

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

before_request

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

Read more about the events.

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

after_request

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

Read more about the events.

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

include_in_schema

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

This will add all the routes of the Include even those nested (Include containing more Includes.)

TYPE: bool DEFAULT: True

deprecated

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

TYPE: Optional[bool] DEFAULT: None

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

redirect_slashes

Boolean flag indicating if the redirect slashes are enabled for the routes or not.

TYPE: Optional[bool] DEFAULT: True

Source code in esmerald/routing/router.py
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
def __init__(
    self,
    path: Annotated[
        Optional[str],
        Doc(
            """
            Relative path of the `Include`.
            The path can contain parameters in a dictionary like format
            and if the path is not provided, it will default to `/`.

            **Example**

            ```python
            Include()
            ```

            **Example with parameters**

            ```python
            Include(path="/{age: int}")
            ```
            """
        ),
    ] = None,
    app: Annotated[
        ASGIApp | str,
        Doc(
            """
            An application can be anything that is treated as an ASGI application.
            For example, it can be a [ChildEsmerald](https://esmerald.dev/routing/router/#child-esmerald-application), another `Esmerald`, a [Router](https://esmerald.dev/routing/router/#router-class) or even an external [WSGI application](https://esmerald.dev/wsgi/) (Django, Flask...)

            The app is a parameter that makes the Include extremely powerful when it comes
            to integrate with ease with whatever Python stack you want and need.

            **Example**

            ```python
            from esmerald import Esmerald, ChildEsmerald, Include

            Esmerald(
                routes=[
                    Include('/child', app=ChildEsmerald(...))
                ]
            )
            ```

            **Example with a WSGI framework**

            ```python
            from flask import Flask, escape, request

            from esmerald import Esmerald, Gateway, Include, Request, get
            from esmerald.middleware.wsgi import WSGIMiddleware

            flask_app = Flask(__name__)


            @flask_app.route("/")
            def flask_main():
                name = request.args.get("name", "Esmerald")
                return f"Hello, {escape(name)} from your Flask integrated!"


            @get("/home/{name:str}")
            async def home(request: Request) -> dict:
                name = request.path_params["name"]
                return {"name": escape(name)}


            app = Esmerald(
                routes=[
                    Gateway(handler=home),
                    Include("/flask", WSGIMiddleware(flask_app)),
                ]
            )
            ```

            """
        ),
    ] = None,
    name: Annotated[
        Optional[str],
        Doc(
            """
            The name for the Gateway. The name can be reversed by `path_for()`.
            """
        ),
    ] = None,
    routes: Annotated[
        Optional[Sequence[Union[APIGateHandler, Include, HTTPHandler, WebSocketHandler]]],
        Doc(
            """
            A global `list` of esmerald routes. Those routes may vary and those can
            be `Gateway`, `WebSocketGateWay` or even another `Include`.

            This is also an entry-point for the routes of the Include
            but it **does not rely on only one [level](https://esmerald.dev/application/levels/)**.

            Read more about how to use and leverage
            the [Esmerald routing system](https://esmerald.dev/routing/routes/).

            **Example**

            ```python
            from esmerald import Esmerald, Gateway, Request, get, Include


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


            @get()
            async def another(request: Request) -> str:
                return "Hello, another!"

            app = Esmerald(
                routes=[
                    Gateway(handler=homepage)
                    Include("/nested", routes=[
                        Gateway(handler=another)
                    ])
                ]
            )
            ```

            !!! Note
                The Include is very powerful and this example
                is not enough to understand what more things you can do.
                Read in [more detail](https://esmerald.dev/routing/routes/#include) about this.
            """
        ),
    ] = None,
    namespace: Annotated[
        Optional[str],
        Doc(
            """
            A string with a qualified namespace from where the URLs should be loaded.

            The namespace is an alternative to `routes` parameter. When a `namespace` is
            specified and a routes as well, an `ImproperlyCOnfigured` exception is raised as
            it can only be one or another.

            The `namespace` can be extremely useful as it avoids the imports from the top
            of the file that can lead to `partially imported` errors.

            When using a `namespace`, the `Include` will look for the default `route_patterns` list in the imported namespace (object) unless a different `pattern` is specified.

            **Example**

            Assuming there is a file with some routes located at `myapp/auth/urls.py`.

            ```python title="myapp/auth/urls.py"
            from esmerald import Gateway
            from .view import welcome, create_user

            route_patterns = [
                Gateway(handler=welcome, name="welcome"),
                Gateway(handler=create_user, name="create-user"),
            ]
            ```

            Using the `namespace` to import the URLs.

            ```python
            from esmerald import Include

            Include("/auth", namespace="myapp.auth.urls")
            ```
            """
        ),
    ] = None,
    pattern: Annotated[
        Optional[str],
        Doc(
            """
            A string `pattern` information from where the urls shall be read from.

            By default, the when using the `namespace` it will lookup for a `route_patterns`
            but somethimes you might want to opt for a different name and this is where the
            `pattern` comes along.

            **Example**

            Assuming there is a file with some routes located at `myapp/auth/urls.py`.
            The urls will be placed inside a `urls` list.

            ```python title="myapp/auth/urls.py"
            from esmerald import Gateway
            from .view import welcome, create_user

            urls = [
                Gateway(handler=welcome, name="welcome"),
                Gateway(handler=create_user, name="create-user"),
            ]
            ```

            Using the `namespace` to import the URLs.

            ```python
            from esmerald import Include

            Include("/auth", namespace="myapp.auth.urls", pattern="urls")
            ```
            """
        ),
    ] = None,
    parent: Annotated[
        Optional[ParentType],
        Doc(
            """
            Who owns the Gateway. If not specified, the application automatically it assign it.

            This is directly related with the [application levels](https://esmerald.dev/application/levels/).
            """
        ),
    ] = None,
    dependencies: Annotated[
        Optional[Dependencies],
        Doc(
            """
            A dictionary of string and [Inject](https://esmerald.dev/dependencies/) instances enable application level dependency injection.
            """
        ),
    ] = None,
    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,
    middleware: Annotated[
        Optional[List[Middleware]],
        Doc(
            """
            A list of middleware to run for every request. The middlewares of an Include 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,
    before_request: Annotated[
        Union[Sequence[Callable[..., Any]], None],
        Doc(
            """
            A `list` of events that are trigger after the application
            processes the request.

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

            Read more about the [events](https://lilya.dev/lifespan/).
            """
        ),
    ] = None,
    include_in_schema: Annotated[
        bool,
        Doc(
            """
            Boolean flag indicating if it should be added to the OpenAPI docs.

            This will add all the routes of the Include even those nested (Include containing more Includes.)
            """
        ),
    ] = True,
    deprecated: Annotated[
        Optional[bool],
        Doc(
            """
            Boolean flag for indicating the deprecation of the Include and all of its routes and to display it in the OpenAPI documentation..
            """
        ),
    ] = None,
    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,
    redirect_slashes: Annotated[
        Optional[bool],
        Doc(
            """
            Boolean flag indicating if the redirect slashes are enabled for the
            routes or not.
            """
        ),
    ] = True,
) -> None:
    self.path = path
    if not path:
        self.path = "/"

    if namespace and routes:
        raise ImproperlyConfigured("It can only be namespace or routes, not both.")

    if namespace and not isinstance(namespace, str):
        raise ImproperlyConfigured("Namespace must be a string. Example: 'myapp.routes'.")

    if pattern and not isinstance(pattern, str):
        raise ImproperlyConfigured("Pattern must be a string. Example: 'route_patterns'.")

    if pattern and routes:
        raise ImproperlyConfigured("Pattern must be used only with namespace.")

    if namespace:
        routes = include(namespace, pattern)

    # Add the middleware to the include
    self.middleware = middleware or []
    include_middleware: Sequence[Middleware] = []

    for _middleware in self.middleware:
        if isinstance(_middleware, DefineMiddleware):  # pragma: no cover
            include_middleware.append(_middleware)
        else:
            include_middleware.append(  # type: ignore
                DefineMiddleware(cast("Type[DefineMiddleware]", _middleware))
            )

    if isinstance(app, str):
        app = import_string(app)

    self.app = self.resolve_app_parent(app=app)

    self.dependencies = dependencies or {}
    self.interceptors: Sequence[Interceptor] = interceptors or []
    self.response_class = None
    self.response_cookies = None
    self.response_headers = None
    self.parent = parent
    self.security = security or []
    self.tags = tags or []

    if namespace:
        routes = include(namespace, pattern)

    if routes:
        routes = self.resolve_route_path_handler(routes)

    self.__base_permissions__ = permissions or []
    self.__lilya_permissions__ = [
        wrap_permission(permission)
        for permission in self.__base_permissions__ or []
        if not is_esmerald_permission(permission)
    ]
    super().__init__(
        path=self.path,
        app=self.app,
        routes=routes,
        name=name,
        middleware=include_middleware,
        exception_handlers=exception_handlers,
        deprecated=deprecated,
        include_in_schema=include_in_schema,
        redirect_slashes=redirect_slashes,
        permissions=self.__lilya_permissions__,  # type: ignore
        before_request=before_request,
        after_request=after_request,
    )

    # Making sure Esmerald uses the Esmerald permission system and not Lilya's.
    self.permissions: Sequence[Permission] = [
        permission
        for permission in self.__base_permissions__ or []
        if is_esmerald_permission(permission)
    ]  # type: ignore

path instance-attribute

path = path

app instance-attribute

app = resolve_app_parent(app=app)

name instance-attribute

name = name

routes property

routes

Returns a list of declared path objects.

parent instance-attribute

parent = parent

dependencies instance-attribute

dependencies = dependencies or {}

exception_handlers instance-attribute

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

interceptors instance-attribute

interceptors = interceptors or []

permissions instance-attribute

permissions = [permission for permission in __base_permissions__ or [] if is_esmerald_permission(permission)]

middleware instance-attribute

middleware = middleware or []

include_in_schema instance-attribute

include_in_schema = include_in_schema

deprecated instance-attribute

deprecated = deprecated

security instance-attribute

security = security or []

tags instance-attribute

tags = tags or []