Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/itsdangerous/url_safe.py: 37%
38 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:35 +0000
1import typing as _t
2import zlib
4from ._json import _CompactJSON
5from .encoding import base64_decode
6from .encoding import base64_encode
7from .exc import BadPayload
8from .serializer import Serializer
9from .timed import TimedSerializer
12class URLSafeSerializerMixin(Serializer):
13 """Mixed in with a regular serializer it will attempt to zlib
14 compress the string to make it shorter if necessary. It will also
15 base64 encode the string so that it can safely be placed in a URL.
16 """
18 default_serializer = _CompactJSON
20 def load_payload(
21 self,
22 payload: bytes,
23 *args: _t.Any,
24 serializer: _t.Optional[_t.Any] = None,
25 **kwargs: _t.Any,
26 ) -> _t.Any:
27 decompress = False
29 if payload.startswith(b"."):
30 payload = payload[1:]
31 decompress = True
33 try:
34 json = base64_decode(payload)
35 except Exception as e:
36 raise BadPayload(
37 "Could not base64 decode the payload because of an exception",
38 original_error=e,
39 ) from e
41 if decompress:
42 try:
43 json = zlib.decompress(json)
44 except Exception as e:
45 raise BadPayload(
46 "Could not zlib decompress the payload before decoding the payload",
47 original_error=e,
48 ) from e
50 return super().load_payload(json, *args, **kwargs)
52 def dump_payload(self, obj: _t.Any) -> bytes:
53 json = super().dump_payload(obj)
54 is_compressed = False
55 compressed = zlib.compress(json)
57 if len(compressed) < (len(json) - 1):
58 json = compressed
59 is_compressed = True
61 base64d = base64_encode(json)
63 if is_compressed:
64 base64d = b"." + base64d
66 return base64d
69class URLSafeSerializer(URLSafeSerializerMixin, Serializer):
70 """Works like :class:`.Serializer` but dumps and loads into a URL
71 safe string consisting of the upper and lowercase character of the
72 alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
73 """
76class URLSafeTimedSerializer(URLSafeSerializerMixin, TimedSerializer):
77 """Works like :class:`.TimedSerializer` but dumps and loads into a
78 URL safe string consisting of the upper and lowercase character of
79 the alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
80 """