forked from celery/kombu
-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Perform custom deserializations #1
Open
jbkkd
wants to merge
2
commits into
v5.2.4
Choose a base branch
from
v5.2.4-patched
base: v5.2.4
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,12 @@ | ||
"""JSON Serialization Utilities.""" | ||
|
||
import base64 | ||
import datetime | ||
import decimal | ||
from decimal import Decimal | ||
import json as stdjson | ||
import uuid | ||
from typing import Any, Callable, TypeVar | ||
|
||
|
||
try: | ||
from django.utils.functional import Promise as DjangoPromise | ||
|
@@ -69,7 +72,19 @@ def dumps(s, _dumps=json.dumps, cls=None, default_kwargs=None, **kwargs): | |
**dict(default_kwargs, **kwargs)) | ||
|
||
|
||
def loads(s, _loads=json.loads, decode_bytes=True): | ||
def object_hook(o: dict): | ||
"""Hook function to perform custom deserialization.""" | ||
if o.keys() == {"__type__", "__value__"}: | ||
decoder = _decoders.get(o["__type__"]) | ||
if decoder: | ||
return decoder(o["__value__"]) | ||
else: | ||
raise ValueError("Unsupported type", type, o) | ||
else: | ||
return o | ||
|
||
|
||
def loads(s, _loads=json.loads, decode_bytes=True, object_hook=object_hook): | ||
"""Deserialize json from string.""" | ||
# None of the json implementations supports decoding from | ||
# a buffer/memoryview, or even reading from a stream | ||
|
@@ -78,14 +93,51 @@ def loads(s, _loads=json.loads, decode_bytes=True): | |
# over. Note that pickle does support buffer/memoryview | ||
# </rant> | ||
if isinstance(s, memoryview): | ||
s = s.tobytes().decode('utf-8') | ||
s = s.tobytes().decode("utf-8") | ||
elif isinstance(s, bytearray): | ||
s = s.decode('utf-8') | ||
s = s.decode("utf-8") | ||
elif decode_bytes and isinstance(s, bytes): | ||
s = s.decode('utf-8') | ||
|
||
try: | ||
return _loads(s) | ||
except _DecodeError: | ||
# catch "Unpaired high surrogate" error | ||
return stdjson.loads(s) | ||
s = s.decode("utf-8") | ||
|
||
return _loads(s, object_hook=object_hook) | ||
|
||
|
||
DecoderT = EncoderT = Callable[[Any], Any] | ||
T = TypeVar("T") | ||
EncodedT = TypeVar("EncodedT") | ||
|
||
|
||
def register_type( | ||
t: type[T], | ||
marker: str, | ||
encoder: Callable[[T], EncodedT], | ||
decoder: Callable[[EncodedT], T], | ||
): | ||
"""Add support for serializing/deserializing native python type.""" | ||
_encoders[t] = (marker, encoder) | ||
_decoders[marker] = decoder | ||
|
||
|
||
_encoders: dict[type, tuple[str, EncoderT]] = {} | ||
_decoders: dict[str, DecoderT] = { | ||
"bytes": lambda o: o.encode("utf-8"), | ||
"base64": lambda o: base64.b64decode(o.encode("utf-8")), | ||
} | ||
|
||
# NOTE: datetime should be registered before date, | ||
# because datetime is also instance of date. | ||
register_type(datetime, "datetime", datetime.datetime.isoformat, datetime.datetime.fromisoformat) | ||
register_type( | ||
datetime.date, | ||
"date", | ||
lambda o: o.isoformat(), | ||
lambda o: datetime.datetime.fromisoformat(o).date(), | ||
) | ||
register_type(datetime.time, "time", lambda o: o.isoformat(), datetime.time.fromisoformat) | ||
register_type(Decimal, "decimal", str, Decimal) | ||
register_type( | ||
uuid.UUID, | ||
"uuid", | ||
lambda o: {"hex": o.hex}, | ||
lambda o: uuid.UUID(**o), | ||
) | ||
Comment on lines
+127
to
+143
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. given this is our fork of kombu you could remove this part since these registrations are overwritten by kraken anyway - and these contain the behavior we don't want - kombu de-coding into typed objects rather than strings. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
pytz>dev | ||
pytest~=7.0.1 | ||
pytest-sugar | ||
Pyro4 | ||
backports.zoneinfo>=0.2.1; python_version < '3.9' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No change necessary, but to save us the conditional handling of
ZoneInfo
, as we only want UTC we could use Python'sdatetime.timezone.utc
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am +1 on this, seems like a less risky change than introducing
zoneinfo
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right that we could do that, however this change is taken directly from kombu:
celery#1680
Seeing that ZoneInfo will be added once we upgrade regardless, we might as well do this now. I prefer sticking to whatever kombu is doing even if it isn't the best solution.