Skip to content
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

Just modify the Django UUIDField for our 32 digit hex representation. #163

Open
wants to merge 3 commits into
base: release-v0.6.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 11 additions & 40 deletions morango/models/fields/uuids.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,38 @@
import uuid

from django.db import models

from morango.utils import _assert


def sha2_uuid(*args):
return hashlib.sha256("::".join(args).encode("utf-8")).hexdigest()[:32]


class UUIDField(models.CharField):
class UUIDField(models.UUIDField):
"""
Adaptation of Django's UUIDField, but with 32-char hex representation as Python representation rather than a UUID instance.
"""

def __init__(self, *args, **kwargs):
kwargs["max_length"] = 32
super(UUIDField, self).__init__(*args, **kwargs)

def prepare_value(self, value):
if isinstance(value, uuid.UUID):
return value.hex
return value
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one doesn't seem to be captured in the parent class.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(and is an important part of having it return the 32 char value rather than a UUID object, from what I recall)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I think maybe specifically for cases where someone sets it on there as a UUID object and then reads it back, without it going through the database yet)

But it could probably call to_python here to be DRYer.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prepare_value is a form field method though, not a regular field: https://github.com/django/django/blob/stable/1.11.x/django/forms/fields.py#L129

I do wonder if that's where some of the original implementation errors came from, as it seems the original implementation here was a copy of the Django form field UUIDField: https://github.com/django/django/blob/stable/1.11.x/django/forms/fields.py#L1206 but then wrapped around the model CharField implementation instead of the form field.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is definitely something missing though, because during the serialization tests, it is returning as a UUID.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default Django serialization framework uses the value_to_string method, which we seem to have not defined here.

See: https://github.com/django/django/blob/stable/1.11.x/django/db/models/fields/__init__.py#L834

Although we're then not using that in the serialize method: https://github.com/learningequality/morango/blob/release-v0.6.x/morango/models/core.py#L939

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have now updated to add a value_from_object override that properly coerces the value to a 32 digit hex string.


def deconstruct(self):
name, path, args, kwargs = super(UUIDField, self).deconstruct()
del kwargs["max_length"]
return name, path, args, kwargs

def get_internal_type(self):
return "UUIDField"

def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
if not isinstance(value, uuid.UUID):
try:
value = uuid.UUID(value)
except AttributeError:
raise TypeError(self.error_messages["invalid"] % {"value": value})
value = super(UUIDField, self).to_python(value)

if connection.features.has_native_uuid_field:
return value
return value.hex
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm now not seeing a difference between this and the parent class implementation, other than the use of super, which doesn't seem necessary, since to_python isn't defined in this class, so it'll use the super's anyway. So I'm guessing this can be removed?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is, see below.


def from_db_value(self, value, expression, connection, context):
return self.to_python(value)

def to_python(self, value):
if isinstance(value, uuid.UUID):
return value.hex
return value

def get_default(self):
"""
Returns the default value for this field.
"""
if self.has_default():
if callable(self.default):
default = self.default()
if isinstance(default, uuid.UUID):
return default.hex
return default
if isinstance(self.default, uuid.UUID):
return self.default.hex
return self.default
return None
value = super(UUIDField, self).to_python(value)
return value.hex if isinstance(value, uuid.UUID) else value

def value_from_object(self, obj):
return self.to_python(super(UUIDField, self).value_from_object(obj))


class UUIDModelMixin(models.Model):
Expand Down
18 changes: 9 additions & 9 deletions tests/testapp/tests/sync/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -1063,9 +1063,11 @@ def setUp(self):
"content_id": uuid.uuid4().hex,
}

def serialize_to_store(self, Model, data):
def serialize_to_store(self, Model, data, post_serialization=None):
instance = Model(**data)
serialized = instance.serialize()
if post_serialization:
serialized.update(post_serialization)
Store.objects.create(
id=serialized["id"],
serialized=json.dumps(serialized),
Expand All @@ -1078,10 +1080,10 @@ def serialize_to_store(self, Model, data):
model_name=instance.morango_model_name,
)

def serialize_all_to_store(self):
self.serialize_to_store(MyUser, self.serialized_user)
self.serialize_to_store(SummaryLog, self.serialized_log1)
self.serialize_to_store(SummaryLog, self.serialized_log2)
def serialize_all_to_store(self, post_serialization=None):
self.serialize_to_store(MyUser, self.serialized_user, post_serialization=getattr(post_serialization, "user", {}))
self.serialize_to_store(SummaryLog, self.serialized_log1, post_serialization=getattr(post_serialization, "log1", {}))
self.serialize_to_store(SummaryLog, self.serialized_log2, post_serialization=getattr(post_serialization, "log2", {}))

def assert_deserialization(self, user_deserialized=True, log1_deserialized=True, log2_deserialized=True):
assert MyUser.objects.filter(id=self.serialized_user["id"]).exists() == user_deserialized
Expand Down Expand Up @@ -1121,15 +1123,13 @@ def test_deserialization_with_excessively_long_username(self):

def test_deserialization_with_invalid_content_id(self):

self.serialized_log1["content_id"] = "invalid"

self.serialize_all_to_store()
self.serialize_all_to_store({"log1": {"content_id": "invalid"}})

_deserialize_from_store(self.profile)

self.assert_deserialization(log1_deserialized=False)

def test_deserialization_with_invalid_log_user_id(self):
def test_deserialization_with_log_non_existent_user_id(self):

self.serialized_log1["user_id"] = uuid.uuid4().hex

Expand Down