Skip to content

Include class

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

How to import

from ravyn import Include

ravyn.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: Dispatcher, 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 ChildRavyn, another Ravyn, 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 ravyn import Ravyn, ChildRavyn, Include

Ravyn(
    routes=[
        Include('/child', app=ChildRavyn(...))
    ]
)

Example with a WSGI framework

from flask import Flask, escape, request

from ravyn import Ravyn, Gateway, Include, Request, get
from ravyn.middleware.wsgi import WSGIMiddleware

flask_app = Flask(__name__)


@flask_app.route("/")
def flask_main():
    name = request.args.get("name", "Ravyn")
    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 = Ravyn(
    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 url_path_for().

TYPE: Optional[str] DEFAULT: None

routes

A global list of ravyn 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 Ravyn routing system.

Example

from ravyn import Ravyn, 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 = Ravyn(
    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 ravyn 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 ravyn 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 ravyn 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 ravyn 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] | Any] 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. Ravyn offers some out of the box solutions where this is implemented.

The Ravyn security is available to automatically used.

The security can be applied also on a level basis.

For custom security objects, you must subclass ravyn.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 Ravyn can be done in levels, which means these tags on a Ravyn 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 ravyn/routing/router.py
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
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 [ChildRavyn](https://ravyn.dev/routing/router/#child-ravyn-application), another `Ravyn`, a [Router](https://ravyn.dev/routing/router/#router-class) or even an external [WSGI application](https://ravyn.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 ravyn import Ravyn, ChildRavyn, Include

            Ravyn(
                routes=[
                    Include('/child', app=ChildRavyn(...))
                ]
            )
            ```

            **Example with a WSGI framework**

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

            from ravyn import Ravyn, Gateway, Include, Request, get
            from ravyn.middleware.wsgi import WSGIMiddleware

            flask_app = Flask(__name__)


            @flask_app.route("/")
            def flask_main():
                name = request.args.get("name", "Ravyn")
                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 = Ravyn(
                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 `url_path_for()`.
            """
        ),
    ] = None,
    routes: Annotated[
        Optional[Sequence[Union[APIGateHandler, Include, HTTPHandler, WebSocketHandler]]],
        Doc(
            """
            A global `list` of ravyn 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://ravyn.dev/application/levels/)**.

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

            **Example**

            ```python
            from ravyn import Ravyn, 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 = Ravyn(
                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://ravyn.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 ravyn 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 ravyn 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 ravyn 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 ravyn 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://ravyn.dev/application/levels/).
            """
        ),
    ] = None,
    dependencies: Annotated[
        Optional[Dependencies],
        Doc(
            """
            A dictionary of string and [Inject](https://ravyn.dev/dependencies/) instances enable application level dependency injection.
            """
        ),
    ] = None,
    interceptors: Annotated[
        Optional[Sequence[Interceptor]],
        Doc(
            """
            A list of [interceptors](https://ravyn.dev/interceptors/) to serve the application incoming requests (HTTP and Websockets).
            """
        ),
    ] = None,
    permissions: Annotated[
        Optional[Sequence[Permission] | Any],
        Doc(
            """
            A list of [permissions](https://ravyn.dev/permissions/) to serve the application incoming requests (HTTP and Websockets).
            """
        ),
    ] = None,
    exception_handlers: Annotated[
        Optional[ExceptionHandlerMap],
        Doc(
            """
            A dictionary of [exception types](https://ravyn.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.
            Ravyn offers some out of the box solutions where this is implemented.

            The [Ravyn security](https://ravyn.dev/openapi/) is available to automatically used.

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

            For custom security objects, you **must** subclass
            `ravyn.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 Ravyn can be done in [levels](https://ravyn.dev/application/levels/), which means
            these tags on a Ravyn 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 = load(app)

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

    self.dependencies = dependencies or {}  # type: ignore
    self.interceptors: Sequence[Interceptor] = interceptors or []
    self._interceptors: Union[list["RavynInterceptor"], VoidType] = Void
    self._permissions_cache: dict[int, Any] | VoidType = Void
    self._lilya_permissions_cache: dict[int, Any] | VoidType = Void
    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_ravyn_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,
    )

    # Filter out the lilya unique permissions
    if self.__lilya_permissions__:
        self.lilya_permissions: Any = {
            index: permission in self.__lilya_permissions__
            for index, permission in enumerate(self.__lilya_permissions__)
        }
    else:
        self.lilya_permissions = {}

    # Making sure Ravyn uses the Ravyn permission system and not Lilya's.
    # Filter out the ravyn unique permissions
    if self.__base_permissions__:
        self.permissions: Any = {
            index: wrap_permission(permission)
            for index, permission in enumerate(permissions)
            if is_ravyn_permission(permission)
        }
    else:
        self.permissions = {}

    assert not (self.permissions and self.lilya_permissions), (
        "Use either `Ravyn permissions` OR `Lilya permissions`, not both."
    )

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 = {
    index: (wrap_permission(permission))
    for (index, permission) in (enumerate(permissions))
    if is_ravyn_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 []