2024-03-06 18:57:04 +00:00
|
|
|
|
from decimal import Decimal
|
2025-03-20 08:59:43 +00:00
|
|
|
|
from json import JSONEncoder
|
2024-03-06 18:57:04 +00:00
|
|
|
|
|
2025-03-20 08:55:21 +00:00
|
|
|
|
|
2025-03-20 08:59:43 +00:00
|
|
|
|
class CustomJSONEncoder(JSONEncoder):
|
2025-03-20 09:52:44 +00:00
|
|
|
|
"""
|
|
|
|
|
Расширенный JSON энкодер с поддержкой сериализации объектов SQLAlchemy.
|
|
|
|
|
|
|
|
|
|
Примеры:
|
|
|
|
|
>>> import json
|
|
|
|
|
>>> from decimal import Decimal
|
|
|
|
|
>>> from orm.topic import Topic
|
|
|
|
|
>>> json.dumps(Decimal("10.50"), cls=CustomJSONEncoder)
|
|
|
|
|
'"10.50"'
|
|
|
|
|
>>> topic = Topic(id=1, slug="test")
|
|
|
|
|
>>> json.dumps(topic, cls=CustomJSONEncoder)
|
|
|
|
|
'{"id": 1, "slug": "test", ...}'
|
|
|
|
|
"""
|
|
|
|
|
|
2024-03-06 18:57:04 +00:00
|
|
|
|
def default(self, obj):
|
|
|
|
|
if isinstance(obj, Decimal):
|
|
|
|
|
return str(obj)
|
2025-03-20 09:52:44 +00:00
|
|
|
|
|
|
|
|
|
# Проверяем, есть ли у объекта метод dict() (как у моделей SQLAlchemy)
|
|
|
|
|
if hasattr(obj, "dict") and callable(obj.dict):
|
|
|
|
|
return obj.dict()
|
|
|
|
|
|
2024-03-06 18:57:04 +00:00
|
|
|
|
return super().default(obj)
|