url_safe.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import zlib
  2. from ._json import _CompactJSON
  3. from .encoding import base64_decode
  4. from .encoding import base64_encode
  5. from .exc import BadPayload
  6. from .serializer import Serializer
  7. from .timed import TimedSerializer
  8. class URLSafeSerializerMixin(object):
  9. """Mixed in with a regular serializer it will attempt to zlib
  10. compress the string to make it shorter if necessary. It will also
  11. base64 encode the string so that it can safely be placed in a URL.
  12. """
  13. default_serializer = _CompactJSON
  14. def load_payload(self, payload, *args, **kwargs):
  15. decompress = False
  16. if payload.startswith(b"."):
  17. payload = payload[1:]
  18. decompress = True
  19. try:
  20. json = base64_decode(payload)
  21. except Exception as e:
  22. raise BadPayload(
  23. "Could not base64 decode the payload because of an exception",
  24. original_error=e,
  25. )
  26. if decompress:
  27. try:
  28. json = zlib.decompress(json)
  29. except Exception as e:
  30. raise BadPayload(
  31. "Could not zlib decompress the payload before decoding the payload",
  32. original_error=e,
  33. )
  34. return super(URLSafeSerializerMixin, self).load_payload(json, *args, **kwargs)
  35. def dump_payload(self, obj):
  36. json = super(URLSafeSerializerMixin, self).dump_payload(obj)
  37. is_compressed = False
  38. compressed = zlib.compress(json)
  39. if len(compressed) < (len(json) - 1):
  40. json = compressed
  41. is_compressed = True
  42. base64d = base64_encode(json)
  43. if is_compressed:
  44. base64d = b"." + base64d
  45. return base64d
  46. class URLSafeSerializer(URLSafeSerializerMixin, Serializer):
  47. """Works like :class:`.Serializer` but dumps and loads into a URL
  48. safe string consisting of the upper and lowercase character of the
  49. alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
  50. """
  51. class URLSafeTimedSerializer(URLSafeSerializerMixin, TimedSerializer):
  52. """Works like :class:`.TimedSerializer` but dumps and loads into a
  53. URL safe string consisting of the upper and lowercase character of
  54. the alphabet as well as ``'_'``, ``'-'`` and ``'.'``.
  55. """