add encoding

This commit is contained in:
huangsong
2022-01-18 15:52:10 +08:00
parent 02df4300dd
commit bf6ee9ce35
3 changed files with 18 additions and 2 deletions

View File

@ -1,6 +1,8 @@
import base64 import base64
from typing import Any, TYPE_CHECKING, Type from typing import Any, TYPE_CHECKING, Type
from ormar.queryset.utils import to_str
try: try:
import orjson as json import orjson as json
except ImportError: # pragma: no cover except ImportError: # pragma: no cover
@ -42,7 +44,7 @@ class JsonDescriptor:
def __set__(self, instance: "Model", value: Any) -> None: def __set__(self, instance: "Model", value: Any) -> None:
if not isinstance(value, str): if not isinstance(value, str):
value = json.dumps(value) value = json.dumps(value)
value = value.decode("utf-8") if isinstance(value, bytes) else value value = to_str(value)
instance._internal_set(self.name, value) instance._internal_set(self.name, value)
instance.set_save_status(False) instance.set_save_status(False)

View File

@ -20,7 +20,7 @@ if TYPE_CHECKING: # pragma no cover
def to_str(val: Union[bytes, str]): def to_str(val: Union[bytes, str]):
""" convert bytes to str simply """ """ convert bytes to str simply """
if isinstance(val, bytes): if isinstance(val, bytes):
return val.decode() return val.decode("utf-8")
return str(val) return str(val)

View File

@ -0,0 +1,14 @@
import json
from ormar.queryset.utils import to_str
def test_to_str():
expected_str = "[]"
val = json.dumps([])
assert expected_str == to_str(val)
expected_bytes = expected_str.encode()
assert isinstance(expected_bytes, bytes)
assert isinstance(to_str(expected_bytes), str)