File: structures.py

package info (click to toggle)
python-falcon 4.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,172 kB
  • sloc: python: 33,608; javascript: 92; sh: 50; makefile: 50
file content (340 lines) | stat: -rw-r--r-- 11,126 bytes parent folder | download
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# Copied from the Requests library by Kenneth Reitz et al.
#
# Copyright 2013 Kenneth Reitz
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.


"""Data structures.

This module provides additional data structures not found in the
standard library. These classes are hoisted into the `falcon` module
for convenience::

    import falcon

    things = falcon.CaseInsensitiveDict()
"""

from __future__ import annotations

from collections.abc import Mapping
from collections.abc import MutableMapping
from typing import (
    Any,
    Dict,
    ItemsView,
    Iterable,
    Iterator,
    KeysView,
    Optional,
    Tuple,
    TYPE_CHECKING,
    ValuesView,
)


# TODO(kgriffs): If we ever diverge from what is upstream in Requests,
# then we will need write tests and remove the "no cover" pragma.
class CaseInsensitiveDict(MutableMapping):  # pragma: no cover
    """A case-insensitive ``dict``-like object.

    Implements all methods and operations of
    ``collections.abc.MutableMapping`` as well as dict's `copy`. Also
    provides `lower_items`.

    All keys are expected to be strings. The structure remembers the
    case of the last key to be set, and ``iter(instance)``,
    ``keys()``, and ``items()``
    will contain case-sensitive keys. However, querying and contains
    testing is case insensitive:

        cid = CaseInsensitiveDict()
        cid['Accept'] = 'application/json'
        cid['aCCEPT'] == 'application/json'  # True
        list(cid) == ['Accept']  # True

    For example, ``headers['content-encoding']`` will return the
    value of a ``'Content-Encoding'`` response header, regardless
    of how the header name was originally stored.

    If the constructor, ``.update``, or equality comparison
    operations are given keys that have equal ``.lower()``s, the
    behavior is undefined.

    """

    def __init__(self, data: Optional[Iterable[Tuple[str, Any]]] = None, **kwargs: Any):
        self._store: Dict[str, Tuple[str, Any]] = dict()
        if data is None:
            data = {}
        self.update(data, **kwargs)

    def __setitem__(self, key: str, value: Any) -> None:
        # Use the lowercased key for lookups, but store the actual
        # key alongside the value.
        self._store[key.lower()] = (key, value)

    def __getitem__(self, key: str) -> Any:
        return self._store[key.lower()][1]

    def __delitem__(self, key: str) -> None:
        del self._store[key.lower()]

    def __iter__(self) -> Iterator[str]:
        return (casedkey for casedkey, mappedvalue in self._store.values())

    def __len__(self) -> int:
        return len(self._store)

    def lower_items(self) -> Iterator[Tuple[str, Any]]:
        """Like iteritems(), but with all lowercase keys."""
        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Mapping):
            other = CaseInsensitiveDict(other)
        else:
            return NotImplemented
        # Compare insensitively
        return dict(self.lower_items()) == dict(other.lower_items())

    # Copy is required
    def copy(self) -> CaseInsensitiveDict:
        return CaseInsensitiveDict(self._store.values())

    def __repr__(self) -> str:
        return '%s(%r)' % (self.__class__.__name__, dict(self.items()))


# NOTE(vytas): Although Context is effectively implementing the MutableMapping
#   interface, we choose not to subclass MutableMapping to stress the fact that
#   Context is, by design, a bare class, and the mapping interface may be
#   removed in a future Falcon release.
class Context:
    """Convenience class to hold contextual information in its attributes.

    This class is used as the default :class:`~.Request` and :class:`~Response`
    context type (see
    :attr:`Request.context_type <falcon.Request.context_type>` and
    :attr:`Response.context_type <falcon.Response.context_type>`,
    respectively).

    In Falcon versions prior to 2.0, the default context type was ``dict``. To
    ease the migration to attribute-based context object approach, this class
    also implements the mapping interface; that is, object attributes are
    linked to dictionary items, and vice versa. For instance:

    >>> context = falcon.Context()
    >>> context.cache_strategy = 'lru'
    >>> context.get('cache_strategy')
    'lru'
    >>> 'cache_strategy' in context
    True
    """

    # NOTE(vytas): Define synthetic attr access methods (under TYPE_CHECKING)
    #   merely to let mypy know this is a namespace object.
    if TYPE_CHECKING:

        def __getattr__(self, name: str) -> Any: ...

        def __setattr__(self, name: str, value: Any) -> None: ...

        def __delattr__(self, name: str) -> None: ...

    def __contains__(self, key: str) -> bool:
        return self.__dict__.__contains__(key)

    def __getitem__(self, key: str) -> Optional[Any]:
        # PERF(vytas): On CPython, using this mapping interface (instead of a
        #   standard dict) to get, set and delete items incurs overhead
        #   approximately comparable to that of two function calls
        #   (per get/set/delete operation, that is).
        return self.__dict__.__getitem__(key)

    def __setitem__(self, key: str, value: Any) -> None:
        return self.__dict__.__setitem__(key, value)

    def __delitem__(self, key: str) -> None:
        self.__dict__.__delitem__(key)

    def __iter__(self) -> Iterator[str]:
        return self.__dict__.__iter__()

    def __len__(self) -> int:
        return self.__dict__.__len__()

    def __eq__(self, other: object) -> bool:
        if isinstance(other, type(self)):
            return self.__dict__.__eq__(other.__dict__)
        return self.__dict__.__eq__(other)

    def __ne__(self, other: object) -> bool:
        if isinstance(other, type(self)):
            return self.__dict__.__ne__(other.__dict__)
        return self.__dict__.__ne__(other)

    def __hash__(self) -> int:
        return hash(self.__dict__)

    def __repr__(self) -> str:
        return '{}({})'.format(type(self).__name__, self.__dict__.__repr__())

    def __str__(self) -> str:
        return '{}({})'.format(type(self).__name__, self.__dict__.__str__())

    def clear(self) -> None:
        return self.__dict__.clear()

    def copy(self) -> Context:
        ctx = type(self)()
        ctx.update(self.__dict__)
        return ctx

    def get(self, key: str, default: Optional[Any] = None) -> Optional[Any]:
        return self.__dict__.get(key, default)

    def items(self) -> ItemsView[str, Any]:
        return self.__dict__.items()

    def keys(self) -> KeysView[str]:
        return self.__dict__.keys()

    def pop(self, key: str, default: Optional[Any] = None) -> Optional[Any]:
        return self.__dict__.pop(key, default)

    def popitem(self) -> Tuple[str, Any]:
        return self.__dict__.popitem()

    def setdefault(
        self, key: str, default_value: Optional[Any] = None
    ) -> Optional[Any]:
        return self.__dict__.setdefault(key, default_value)

    def update(self, items: dict[str, Any]) -> None:
        self.__dict__.update(items)

    def values(self) -> ValuesView:
        return self.__dict__.values()


class ETag(str):
    """Convenience class to represent a parsed HTTP entity-tag.

    This class is simply a subclass of ``str`` with a few helper methods and
    an extra attribute to indicate whether the entity-tag is weak or strong. The
    value of the string is equivalent to what RFC 7232 calls an "opaque-tag",
    i.e. an entity-tag sans quotes and the weakness indicator.

    Note:

        Given that a weak entity-tag comparison can be performed by
        using the ``==`` operator (per the example below), only a
        :meth:`~.strong_compare` method is provided.

    Here is an example ``on_get()`` method that demonstrates how to use instances
    of this class::

        def on_get(self, req, resp):
            content_etag = self._get_content_etag()
            for etag in (req.if_none_match or []):
                if etag == '*' or etag == content_etag:
                    resp.status = falcon.HTTP_304
                    return

            # -- snip --

            resp.etag = content_etag
            resp.status = falcon.HTTP_200

    (See also: RFC 7232)
    """

    is_weak: bool = False
    """``True`` if the entity-tag is weak, otherwise ``False``."""

    def strong_compare(self, other: ETag) -> bool:
        """Perform a strong entity-tag comparison.

        Two entity-tags are equivalent if both are not weak and their
        opaque-tags match character-by-character.

        (See also: RFC 7232, Section 2.3.2)

        Arguments:
            other (ETag): The other :class:`~.ETag` to which you are comparing
            this one.

        Returns:
            bool: ``True`` if the two entity-tags match, otherwise ``False``.

        """

        return self == other and not (self.is_weak or other.is_weak)

    def dumps(self) -> str:
        """Serialize the ETag to a string suitable for use in a precondition header.

        (See also: RFC 7232, Section 2.3)

        Returns:
            str: An opaque quoted string, possibly prefixed by a weakness
            indicator ``W/``.
        """

        if self.is_weak:
            # PERF(kgriffs): Simple concatenation like this is slightly faster
            #   than %s string formatting.
            return 'W/"' + self + '"'

        return '"' + self + '"'

    @classmethod
    def loads(cls, etag_str: str) -> ETag:
        """Deserialize a single entity-tag string from a precondition header.

        Note:

            This method is meant to be used only for parsing a single
            entity-tag. It can not be used to parse a comma-separated list of
            values.

        (See also: RFC 7232, Section 2.3)

        Arguments:
            etag_str (str): An ASCII string representing a single entity-tag,
                as defined by RFC 7232.

        Returns:
            ETag: An instance of `~.ETag` representing the parsed entity-tag.

        """

        value = etag_str

        is_weak = False
        if value.startswith(('W/', 'w/')):
            is_weak = True
            value = value[2:]

        # NOTE(kgriffs): We allow for an unquoted entity-tag just in case,
        #   although it has been non-standard to do so since at least 1999
        #   with the advent of RFC 2616.
        if value[:1] == value[-1:] == '"':
            value = value[1:-1]

        t = cls(value)
        t.is_weak = is_weak

        return t