Skip to content

Commit

Permalink
If Enum column is also subclass of str use default JSON serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
mrevutskyi committed Jan 19, 2024
1 parent 87c55ae commit 8de809f
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 5 deletions.
7 changes: 6 additions & 1 deletion CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ Changelog
Changes in Flask-Restless-NG
============================

Version 3.2.0
Version 3.2.0 (2024-01-19)
-------------
- If Enum column is also subclass of `str` use default JSON serialization


Version 3.2.0 (2024-01-19)
-------------
- Dropped savalidation support
- Added a parameter to serializer to skip primary key check (not recommended)
Expand Down
2 changes: 1 addition & 1 deletion flask_restless/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""
#: The current version of this extension.
__version__ = '3.2.0'
__version__ = '3.2.1'


# The following names are available as part of the public API for Flask-Restless-NG.
Expand Down
2 changes: 1 addition & 1 deletion flask_restless/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ def serialize_attributes(self, instance, only=None) -> Dict[str, Any]:
elif isinstance(value, timedelta):
attributes[key] = value.total_seconds()
# Enums are not serializable by default, use 'name' property
elif isinstance(value, enum.Enum):
elif isinstance(value, enum.Enum) and not isinstance(value, str):
attributes[key] = value.name

return attributes
Expand Down
12 changes: 10 additions & 2 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ class MyEnum(enum.Enum):
three = 3


class MyEnumStr(str, enum.Enum):
one = "One"
two = "Two"


class Model(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
Expand All @@ -51,6 +56,7 @@ class Model(Base):
interval_field = Column(Interval())
time_field = Column(Time())
enum_field = Column(Enum(MyEnum))
enum_str_field = Column(Enum(MyEnumStr))


def test_serialize_attributes():
Expand All @@ -67,7 +73,8 @@ def test_serialize_attributes():
datetime_field=datetime.datetime(year=2021, month=1, day=1, hour=12, minute=0, second=0),
time_field=datetime.time(12, 0, 0),
interval_field=datetime.timedelta(minutes=1),
enum_field=MyEnum.two
enum_field=MyEnum.two,
enum_str_field=MyEnumStr.one
)

serialized = serializer.serialize_attributes(instance)
Expand All @@ -85,7 +92,8 @@ def test_serialize_attributes():
'datetime_field': '2021-01-01T12:00:00',
'time_field': '12:00:00',
'interval_field': 60.0,
'enum_field': 'two'
'enum_field': 'two',
'enum_str_field': 'One',
}


Expand Down

0 comments on commit 8de809f

Please sign in to comment.