summaryrefslogtreecommitdiff
path: root/venv/lib/python3.11/site-packages/litestar/utils/scope/state.py
blob: bed43940e2284081942e34bdddc225ef8c072901 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
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
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Final

from litestar.types import Empty, EmptyType
from litestar.utils.empty import value_or_default

if TYPE_CHECKING:
    from typing_extensions import Self

    from litestar.datastructures import URL, Accept, Headers
    from litestar.types.asgi_types import Scope

CONNECTION_STATE_KEY: Final = "_ls_connection_state"


@dataclass
class ScopeState:
    """An object for storing connection state.

    This is an internal API, and subject to change without notice.

    All types are a union with `EmptyType` and are seeded with the `Empty` value.
    """

    __slots__ = (
        "accept",
        "base_url",
        "body",
        "content_type",
        "cookies",
        "csrf_token",
        "dependency_cache",
        "do_cache",
        "form",
        "headers",
        "is_cached",
        "json",
        "log_context",
        "msgpack",
        "parsed_query",
        "response_compressed",
        "session_id",
        "url",
        "_compat_ns",
    )

    def __init__(self) -> None:
        self.accept = Empty
        self.base_url = Empty
        self.body = Empty
        self.content_type = Empty
        self.cookies = Empty
        self.csrf_token = Empty
        self.dependency_cache = Empty
        self.do_cache = Empty
        self.form = Empty
        self.headers = Empty
        self.is_cached = Empty
        self.json = Empty
        self.log_context: dict[str, Any] = {}
        self.msgpack = Empty
        self.parsed_query = Empty
        self.response_compressed = Empty
        self.session_id = Empty
        self.url = Empty
        self._compat_ns: dict[str, Any] = {}

    accept: Accept | EmptyType
    base_url: URL | EmptyType
    body: bytes | EmptyType
    content_type: tuple[str, dict[str, str]] | EmptyType
    cookies: dict[str, str] | EmptyType
    csrf_token: str | EmptyType
    dependency_cache: dict[str, Any] | EmptyType
    do_cache: bool | EmptyType
    form: dict[str, str | list[str]] | EmptyType
    headers: Headers | EmptyType
    is_cached: bool | EmptyType
    json: Any | EmptyType
    log_context: dict[str, Any]
    msgpack: Any | EmptyType
    parsed_query: tuple[tuple[str, str], ...] | EmptyType
    response_compressed: bool | EmptyType
    session_id: str | None | EmptyType
    url: URL | EmptyType
    _compat_ns: dict[str, Any]

    @classmethod
    def from_scope(cls, scope: Scope) -> Self:
        """Create a new `ConnectionState` object from a scope.

        Object is cached in the scope's state under the `SCOPE_STATE_NAMESPACE` key.

        Args:
            scope: The ASGI connection scope.

        Returns:
            A `ConnectionState` object.
        """
        base_scope_state = scope.setdefault("state", {})
        if (state := base_scope_state.get(CONNECTION_STATE_KEY)) is None:
            state = base_scope_state[CONNECTION_STATE_KEY] = cls()
        return state


def get_litestar_scope_state(scope: Scope, key: str, default: Any = None, pop: bool = False) -> Any:
    """Get an internal value from connection scope state.

    Args:
        scope: The connection scope.
        key: Key to get from internal namespace in scope state.
        default: Default value to return.
        pop: Boolean flag dictating whether the value should be deleted from the state.

    Returns:
        Value mapped to ``key`` in internal connection scope namespace.
    """
    scope_state = ScopeState.from_scope(scope)
    try:
        val = value_or_default(getattr(scope_state, key), default)
        if pop:
            setattr(scope_state, key, Empty)
        return val
    except AttributeError:
        if pop:
            return scope_state._compat_ns.pop(key, default)
        return scope_state._compat_ns.get(key, default)


def set_litestar_scope_state(scope: Scope, key: str, value: Any) -> None:
    """Set an internal value in connection scope state.

    Args:
        scope: The connection scope.
        key: Key to set under internal namespace in scope state.
        value: Value for key.
    """
    scope_state = ScopeState.from_scope(scope)
    if hasattr(scope_state, key):
        setattr(scope_state, key, value)
    else:
        scope_state._compat_ns[key] = value


def delete_litestar_scope_state(scope: Scope, key: str) -> None:
    """Delete an internal value from connection scope state.

    Args:
        scope: The connection scope.
        key: Key to set under internal namespace in scope state.
    """
    scope_state = ScopeState.from_scope(scope)
    if hasattr(scope_state, key):
        setattr(scope_state, key, Empty)
    else:
        del scope_state._compat_ns[key]