Skip to content

Commit

Permalink
feat: use orjson if its installed (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Jan 24, 2025
1 parent e78f6da commit cbb8a14
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/aioharmony/hubconnector_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from aioharmony.const import ConnectorCallbackType
from aioharmony.helpers import call_callback

from .json import json_dumps, json_loads

DEFAULT_DOMAIN = "svcs.myharmony.com"
DEFAULT_TIMEOUT = 5

Expand Down Expand Up @@ -100,7 +102,7 @@ def _session(self):

session_timeout = aiohttp.ClientTimeout(connect=DEFAULT_TIMEOUT)
self._aiohttp_session = aiohttp.ClientSession(
connector=conn, timeout=session_timeout
connector=conn, timeout=session_timeout, json_serialize=json_dumps
)
return self._aiohttp_session

Expand Down Expand Up @@ -316,7 +318,7 @@ async def hub_send(

_LOGGER.debug("%s: Sending payload: %s", self._ip_address, payload)
try:
await self._websocket.send_json(payload)
await self._websocket.send_json(payload, dumps=json_dumps)
except aiohttp.ClientError as exc:
_LOGGER.error("%s: Exception sending payload: %s", self._ip_address, exc)
return
Expand All @@ -330,7 +332,7 @@ async def hub_post(self, url, json_request, headers=None) -> Optional[dict]:
async with self._session.post(
url, json=json_request, headers=headers
) as response:
json_response = await response.json(content_type=None)
json_response = await response.json(content_type=None, loads=json_loads)
_LOGGER.debug("%s: Post response: %s", self._ip_address, json_response)
except aiohttp.ClientError as exc:
_LOGGER.error("%s: Exception on post: %s", self._ip_address, exc)
Expand Down Expand Up @@ -391,7 +393,7 @@ async def _listener(self, websocket=None) -> None:
if response.type is not aiohttp.WSMsgType.TEXT:
continue

response_json = response.json()
response_json = response.json(loads=json_loads)
if not response_json:
continue

Expand Down
16 changes: 16 additions & 0 deletions src/aioharmony/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from functools import partial
from typing import Any

try:
import orjson

json_loads = orjson.loads

def json_dumps(obj: Any) -> str:
return orjson.dumps(obj).decode()

except ImportError:
import json

json_dumps = partial(json.dumps, separators=(",", ":"))
json_loads = json.loads
9 changes: 9 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from aioharmony.json import json_dumps, json_loads


def test_json_dumps():
assert json_dumps({"foo": "bar"}) == '{"foo":"bar"}'


def test_json_loads():
assert json_loads('{"foo":"bar"}') == {"foo": "bar"}

0 comments on commit cbb8a14

Please sign in to comment.