Skip to content

Commit 59ccef0

Browse files
committed
using orjson for JSON serialisation when using output(as_json=True) clause
1 parent a8edff5 commit 59ccef0

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

docs/src/piccolo/query_types/select.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ To return the data as a JSON string:
143143
>>> b.select().output(as_json=True).run_sync()
144144
'[{"name":"Pythonistas","manager":1,"popularity":1000,"id":1},{"name":"Rustaceans","manager":2,"popularity":500,"id":2}]'
145145
146+
Piccolo uses `orjson <https://github.com/ijl/orjson>`_ for JSON serialisation, which is blazing fast, and can handle most Python types, including dates, datetimes, and UUIDs.
147+
146148
where
147149
~~~~~
148150

piccolo/query/base.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
from time import time
44
import typing as t
55

6-
import ujson as json
6+
from asyncpg.pgproto.pgproto import UUID
7+
import orjson as json
78

89
from piccolo.querystring import QueryString
910
from piccolo.utils.sync import run_sync
@@ -21,6 +22,15 @@ def __exit__(self, exception_type, exception, traceback):
2122
print(f"Duration: {self.end - self.start}s")
2223

2324

25+
def default(obj):
26+
"""
27+
Used for handling edge cases which orjson can't serialise out of the box.
28+
"""
29+
if isinstance(obj, UUID):
30+
return str(obj)
31+
raise TypeError
32+
33+
2434
class Query:
2535

2636
__slots__ = ("table",)
@@ -70,7 +80,7 @@ async def _process_results(self, results):
7080
else:
7181
raw = list(itertools.chain(*[j.values() for j in raw]))
7282
if output._output.as_json:
73-
raw = json.dumps(raw)
83+
raw = json.dumps(raw, default=default)
7484

7585
return raw
7686

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@ asgiref==3.2.10
33
asyncpg==0.20.1
44
black==19.10b0
55
colorama==0.4.3
6-
ujson==3.0.0
6+
orjson==3.3.0
77
Jinja2==2.11.2
88
targ==0.1.*

0 commit comments

Comments
 (0)