Serialise UUID to string not UUID object

We need to serialise the template to JSON to store it in Redis. Python’s
built in JSON serialiser doesn’t know what to do with a UUID object, so
we need to manually cast it to a string instead.
This commit is contained in:
Chris Hill-Scott
2020-06-18 15:23:43 +01:00
parent 87afc439fe
commit 2f4470edca

View File

@@ -13,6 +13,7 @@ from marshmallow import (
post_dump
)
from marshmallow_sqlalchemy import field_for
from uuid import UUID
from notifications_utils.recipients import (
validate_email_address,
@@ -58,6 +59,14 @@ def _validate_datetime_not_in_past(dte, msg="Date cannot be in the past"):
raise ValidationError(msg)
class UUIDsAsStringsMixin:
@post_dump()
def __post_dump(self, data):
for key, value in data.items():
if isinstance(value, UUID):
data[key] = str(value)
class BaseSchema(ma.ModelSchema):
def __init__(self, load_json=False, *args, **kwargs):
@@ -341,7 +350,7 @@ class BaseTemplateSchema(BaseSchema):
strict = True
class TemplateSchema(BaseTemplateSchema):
class TemplateSchema(BaseTemplateSchema, UUIDsAsStringsMixin):
created_by_id = field_for(
models.Template, 'created_by_id', dump_to='created_by', dump_only=True