| 1 |
import base64 |
| 2 |
import json |
| 3 |
|
| 4 |
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured |
| 5 |
from django.core.files.base import ContentFile |
| 6 |
from django.core.serializers.json import DjangoJSONEncoder |
| 7 |
from django.db.models import FileField |
| 8 |
from django.db.models.fields import BinaryField, DateField, DateTimeField, TimeField |
| 9 |
from django.utils import dateparse |
| 10 |
from django.utils.encoding import force_bytes, force_str |
| 11 |
|
| 12 |
|
| 13 |
SERIALIZED_DB_FIELD_PREFIX = "_db_" |
| 14 |
|
| 15 |
|
| 16 |
def serialize_instance(instance) -> dict: |
| 17 |
""" |
| 18 |
Since Django 1.6 items added to the session are no longer pickled, |
| 19 |
but JSON encoded by default. We are storing partially complete models |
| 20 |
in the session (user, account, token, ...). We cannot use standard |
| 21 |
Django serialization, as these are models are not "complete" yet. |
| 22 |
Serialization will start complaining about missing relations et al. |
| 23 |
""" |
| 24 |
data = {} |
| 25 |
for k, v in instance.__dict__.items(): |
| 26 |
if k.startswith("_") or callable(v): |
| 27 |
continue |
| 28 |
try: |
| 29 |
field = instance._meta.get_field(k) |
| 30 |
if isinstance(field, BinaryField): |
| 31 |
if v is not None: |
| 32 |
v = force_str(base64.b64encode(v)) |
| 33 |
elif isinstance(field, FileField): |
| 34 |
if v and not isinstance(v, str): |
| 35 |
v = { |
| 36 |
"name": v.name, |
| 37 |
"content": base64.b64encode(v.read()).decode("ascii"), |
| 38 |
} |
| 39 |
# Check if the field is serializable. If not, we'll fall back |
| 40 |
# to serializing the DB values which should cover most use cases. |
| 41 |
try: |
| 42 |
json.dumps(v, cls=DjangoJSONEncoder) |
| 43 |
except TypeError: |
| 44 |
v = field.get_prep_value(v) |
| 45 |
k = SERIALIZED_DB_FIELD_PREFIX + k |
| 46 |
except FieldDoesNotExist: |
| 47 |
pass |
| 48 |
data[k] = v |
| 49 |
return json.loads(json.dumps(data, cls=DjangoJSONEncoder)) |
| 50 |
|
| 51 |
|
| 52 |
def deserialize_instance(model, data): |
| 53 |
if not isinstance(data, dict): |
| 54 |
raise ValueError() |
| 55 |
ret = model() |
| 56 |
for k, v in data.items(): |
| 57 |
is_db_value = False |
| 58 |
if k.startswith(SERIALIZED_DB_FIELD_PREFIX): |
| 59 |
k = k[len(SERIALIZED_DB_FIELD_PREFIX) :] |
| 60 |
is_db_value = True |
| 61 |
if v is not None: |
| 62 |
try: |
| 63 |
f = model._meta.get_field(k) |
| 64 |
if isinstance(f, DateTimeField): |
| 65 |
v = dateparse.parse_datetime(v) |
| 66 |
elif isinstance(f, TimeField): |
| 67 |
v = dateparse.parse_time(v) |
| 68 |
elif isinstance(f, DateField): |
| 69 |
v = dateparse.parse_date(v) |
| 70 |
elif isinstance(f, BinaryField): |
| 71 |
v = force_bytes(base64.b64decode(force_bytes(v))) |
| 72 |
elif isinstance(f, FileField): |
| 73 |
if isinstance(v, dict): |
| 74 |
v = ContentFile(base64.b64decode(v["content"]), name=v["name"]) |
| 75 |
elif is_db_value: |
| 76 |
try: |
| 77 |
# This is quite an ugly hack, but will cover most |
| 78 |
# use cases... |
| 79 |
# The signature of `from_db_value` changed in Django 3 |
| 80 |
# https://docs.djangoproject.com/en/3.0/releases/3.0/#features-removed-in-3-0 |
| 81 |
v = f.from_db_value(v, None, None) |
| 82 |
except Exception: |
| 83 |
raise ImproperlyConfigured( |
| 84 |
f"Unable to auto serialize field '{k}', custom serialization override required" |
| 85 |
) |
| 86 |
except FieldDoesNotExist: |
| 87 |
pass |
| 88 |
setattr(ret, k, v) |
| 89 |
return ret |