Skip to content

Commit ab7501b

Browse files
Merge pull request #232 from phenobarbital/bugfix-optional-list-str
homologate datamodel json functions and QS json functions
2 parents 36421d0 + 58f6301 commit ab7501b

File tree

2 files changed

+37
-6
lines changed

2 files changed

+37
-6
lines changed

datamodel/parsers/json.pyx

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
JSON Encoder, Decoder.
66
"""
77
import uuid
8+
from pathlib import PosixPath, PurePath, Path
9+
from datetime import datetime
810
from asyncpg.pgproto import pgproto
11+
from psycopg2 import Binary
912
from dataclasses import _MISSING_TYPE, MISSING
1013
from typing import Any, Union
1114
from decimal import Decimal
15+
from enum import Enum, EnumType
1216
from ..exceptions cimport ParserError
1317
from ..fields import Field
1418
import orjson
@@ -18,9 +22,6 @@ cdef class JSONContent:
1822
"""
1923
Basic Encoder using orjson
2024
"""
21-
# def __init__(self, **kwargs):
22-
# # eventually take into consideration when serializing
23-
# self.options = kwargs
2425
def __call__(self, object obj, **kwargs):
2526
return self.encode(obj, **kwargs)
2627

@@ -29,12 +30,19 @@ cdef class JSONContent:
2930
return float(obj)
3031
elif hasattr(obj, "isoformat"):
3132
return obj.isoformat()
33+
elif isinstance(obj, datetime):
34+
return str(obj)
3235
elif isinstance(obj, pgproto.UUID):
3336
return str(obj)
3437
elif isinstance(obj, uuid.UUID):
3538
return obj
39+
elif isinstance(obj, (PosixPath, PurePath, Path)):
40+
return str(obj)
3641
elif hasattr(obj, "hex"):
37-
return obj.hex
42+
if isinstance(obj, bytes):
43+
return obj.hex()
44+
else:
45+
return obj.hex
3846
elif hasattr(obj, 'lower'): # asyncPg Range:
3947
up = obj.upper
4048
if isinstance(up, int):
@@ -46,9 +54,20 @@ cdef class JSONContent:
4654
return None
4755
elif obj is MISSING:
4856
return None
57+
elif isinstance(obj, (Enum, EnumType)):
58+
if obj is None:
59+
return None
60+
if hasattr(obj, 'value'):
61+
return obj.value
62+
else:
63+
return obj.name
64+
elif isinstance(obj, Binary): # Handle bytea column from PostgreSQL
65+
return str(obj) # Convert Binary object to string
4966
elif isinstance(obj, Field):
5067
return obj.to_dict()
51-
raise TypeError(f"{obj!r} is not JSON serializable")
68+
raise TypeError(
69+
f'{obj!r} of Type {type(obj)} is not JSON serializable'
70+
)
5271

5372
def encode(self, object obj, **kwargs) -> str:
5473
# decode back to str, as orjson returns bytes
@@ -96,3 +115,15 @@ cpdef str json_encoder(object obj):
96115

97116
cpdef object json_decoder(object obj):
98117
return JSONContent().loads(obj)
118+
119+
120+
cdef class BaseEncoder:
121+
"""
122+
Encoder replacement for json.dumps but using orjson
123+
"""
124+
def __init__(self, *args, **kwargs):
125+
# Filter/adapt JSON arguments to ORJSON ones
126+
rjargs = ()
127+
rjkwargs = {}
128+
encoder = JSONContent(*rjargs, **rjkwargs)
129+
self.encode = encoder.__call__

datamodel/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
'simple library based on python +3.8 to use Dataclass-syntax'
77
'for interacting with Data'
88
)
9-
__version__ = '0.8.15'
9+
__version__ = '0.8.16'
1010
__copyright__ = 'Copyright (c) 2020-2024 Jesus Lara'
1111
__author__ = 'Jesus Lara'
1212
__author_email__ = '[email protected]'

0 commit comments

Comments
 (0)