Skip to content

Context class

Importing the Context from esmerald is as simple as:

from esmerald import Context

esmerald.Context

Context(__handler__, __request__)

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 get, Esmerald, Context


@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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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:
    self.__handler__ = copy.copy(__handler__)
    self.__request__ = __request__

handler property

handler

request property

request

user property

user

settings property

settings

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 esmerald import Esmerald, Context, get

async def get_data(context: Context) -> Any:
    context.update{"name": "Esmerald"}
    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 esmerald/context.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 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
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 esmerald import Esmerald, Context, get

    async def get_data(context: Context) -> Any:
        context.update{"name": "Esmerald"}
        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 esmerald/context.py
125
126
127
128
129
130
131
132
133
134
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

url_for

url_for(name, **path_params)
PARAMETER DESCRIPTION
name

The name given in a Gateway or Include objects.

Example

from esmerald import Esmerald, 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 esmerald/context.py
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
def url_for(
    self,
    name: Annotated[
        str,
        Doc(
            """
            The `name` given in a `Gateway` or `Include` objects.

            **Example**

            ```python
            from esmerald import Esmerald, 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.
            """
        ),
    ],
) -> Any:
    url: URL = self.request.url_for(name, **path_params)
    return str(url)