Skip to content

Context class

Importing the Context from esmerald is as simple as:

from esmerald import Context

esmerald.Context

Context(__handler__, __request__)

Bases: Context

Context class is used for the handlers context of the scope of the call.

When a context is passed through the handler, the context will be aware of the decoractor handler itself.

You will probably not need the context or change it but it is here in case you decide to use it.

Tip

The context only exists in the handlers and nothing else which you can also see it as request context sort of approach.

Example

from esmerald import Esmerald, Context, get


@get()
async def home(context: Context) -> None:
    ...
PARAMETER DESCRIPTION
__handler__

The handler where the context will be. placed.

To avoid any adulteration of the the original route handler, the context performs a shallow copy of the original handler itself.

TYPE: Union[HTTPHandler, WebSocketHandler]

__request__

A Request class object.

TYPE: Request

Source code in esmerald/context.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    __handler__: Annotated[
        Union["HTTPHandler", "WebSocketHandler"],
        Doc(
            """
            The [handler](https://esmerald.dev/routing/handlers/) where the context will be. placed.

            To avoid any adulteration of the the original route handler, the context performs
            a shallow copy of the original handler itself.
            """
        ),
    ],
    __request__: Annotated[
        "Request",
        Doc(
            """
            A [Request](https://esmerald.dev/references/request/) class object.
            """
        ),
    ],
) -> None:
    super().__init__(__handler__, __request__)

handler property

handler

request property

request

user property

user

settings property

settings

scope property

scope

app property

app

add_to_context

add_to_context(key, value)

Adds a key to the context of an handler.

This can be particularly useful if you are programatically building the handler or for any other specific and unique operation.

Example

from typing import Any
from lilya.context import Context

async def get_data(context: Context) -> Any:
    context.update{"name": "Lilya"}
    return context.get_context_data()
PARAMETER DESCRIPTION
key

The key value to be added to the context dictionary.

TYPE: Any

value

The value value to be added to the context dictionary and map with the key.

TYPE: Any

Source code in lilya/context.py
 94
 95
 96
 97
 98
 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
def add_to_context(
    self,
    key: Annotated[
        Any,
        Doc(
            """
            The key value to be added to the context dictionary.
            """
        ),
    ],
    value: Annotated[
        Any,
        Doc(
            """
            The value value to be added to the context dictionary and map with the key.
            """
        ),
    ],
) -> None:
    """
    Adds a key to the context of an handler.

    This can be particularly useful if you are programatically
    building the handler or for any other specific and unique operation.

    **Example**

    ```python
    from typing import Any
    from lilya.context import Context

    async def get_data(context: Context) -> Any:
        context.update{"name": "Lilya"}
        return context.get_context_data()
    ```
    """
    if key in self.__dict__:
        warnings.warn(
            f"The key: '{key} already exists in context and it will be overritten.",
            stacklevel=2,
        )
    setattr(self, key, value)

get_context_data

get_context_data(**kwargs)

Returns the context in a python dictionary like structure.

PARAMETER DESCRIPTION
**kwargs

TYPE: Any DEFAULT: {}

Source code in lilya/context.py
137
138
139
140
141
142
143
144
145
146
def get_context_data(self, **kwargs: Any) -> dict[Any, Any]:
    """
    Returns the context in a python dictionary like structure.
    """
    context_data = {
        k: v
        for k, v in self.__dict__.items()
        if not k.startswith("__") and not k.endswith("__")
    }
    return context_data

path_for

path_for(name, **path_params)
PARAMETER DESCRIPTION
name

The name given in a Gateway or Include objects.

Example

from lilya import Lilya, Gateway

Gateway(handler=..., name="view-users")

TYPE: str

**path_params

Any additional path_params declared in the URL of the handler and are needed to reverse the names and return the proper URL.

TYPE: Any DEFAULT: {}

Source code in lilya/context.py
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
def path_for(
    self,
    name: Annotated[
        str,
        Doc(
            """
            The `name` given in a `Gateway` or `Include` objects.

            **Example**

            ```python
            from lilya import Lilya, Gateway

            Gateway(handler=..., name="view-users")
            ```
            """
        ),
    ],
    **path_params: Annotated[
        Any,
        Doc(
            """
            Any additional *path_params* declared in the URL of the
            handler and are needed to *reverse* the names and return
            the proper URL.
            """
        ),
    ],
) -> str:
    url: URL = self.request.path_for(name, **path_params)
    return str(url)