Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use orjson instead of json #175

Merged
merged 4 commits into from
Dec 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ maintainers = [
dependencies = [
"async_timeout>=3.0.1;python_version<'3.11'",
"cryptography",
"orjson",
]
classifiers = [
"License :: OSI Approved :: Apache Software License",
Expand Down
18 changes: 9 additions & 9 deletions src/pylutron_caseta/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

import asyncio
import functools
import json
import logging
import socket
import ssl
import urllib.parse
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, AsyncIterator, List, Optional, TextIO
from typing import Any, AsyncIterator, List, Optional, TextIO, BinaryIO
from urllib.parse import urlparse

import orjson
import click
import xdg
from zeroconf import DNSQuestionType, InterfaceChoice, ServiceListener
Expand Down Expand Up @@ -271,7 +271,7 @@ async def _connect(
@click.option(
"-o",
"--output",
type=click.File("w", encoding="utf8"),
type=click.File("wb"),
default="-",
help="Save the response into a file.",
)
Expand All @@ -289,7 +289,7 @@ async def leap(
data: Optional[str],
paging: Optional[str],
fail: bool,
output: TextIO,
output: BinaryIO,
verbose: bool,
):
"""
Expand All @@ -298,8 +298,8 @@ async def leap(
LEAP is similar to JSON over HTTP, and this tool is similar to Curl.
"""
async with _connect(resource, cacert, cert, key) as connection:
body = json.loads(data) if data is not None else None
paging_json = json.loads(paging) if paging is not None else None
body = orjson.loads(data) if data is not None else None
paging_json = orjson.loads(paging) if paging is not None else None

res = resource.path
if resource.query is not None and len(resource.query) > 0:
Expand Down Expand Up @@ -328,8 +328,8 @@ async def leap(
if response.Header.Paging:
message["Header"]["Paging"] = response.Header.Paging

output.write(json.dumps(message))
output.write(orjson.dumps(message))
else:
output.write(json.dumps(response.Body))
output.write(orjson.dumps(response.Body))

output.write("\n")
output.write(b"\n")
9 changes: 5 additions & 4 deletions src/pylutron_caseta/leap.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""LEAP protocol layer."""

import asyncio
import json
import logging
import re
import uuid
from typing import Callable, Dict, List, Optional, Tuple

import orjson

from . import BridgeDisconnectedError
from .messages import Response

Expand Down Expand Up @@ -68,9 +69,9 @@ def clean_up(future):
future.add_done_callback(clean_up)

try:
text = json.dumps(cmd).encode("UTF-8")
text = orjson.dumps(cmd)
_LOG.debug("sending %s", text)
self._writer.write(text + b"\r\n")
self._writer.writelines((text, b"\r\n"))

return await future
finally:
Expand All @@ -84,7 +85,7 @@ async def run(self):
if received == b"":
break

resp_json = json.loads(received.decode("UTF-8"))
resp_json = orjson.loads(received)

if isinstance(resp_json, dict):
tag = resp_json.get("Header", {}).pop("ClientTag", None)
Expand Down
8 changes: 4 additions & 4 deletions src/pylutron_caseta/pairing.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""Guide the user through pairing and save the necessary files."""

import asyncio
import json
import logging
import socket
import ssl
import tempfile
from typing import Callable, Optional, Tuple, TypedDict
import os

import orjson
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
Expand Down Expand Up @@ -57,12 +57,12 @@ async def async_read_json(self, timeout):
return None

LOGGER.debug("received: %s", buffer)
return json.loads(buffer.decode("UTF-8"))
return orjson.loads(buffer)

async def async_write_json(self, obj):
"""Write an object."""
buffer = f"{json.dumps(obj)}\r\n".encode("ASCII")
self._writer.write(buffer)
buffer = orjson.dumps(obj)
self._writer.writelines((buffer, b"\r\n"))
LOGGER.debug("sent: %s", buffer)

def __del__(self):
Expand Down
22 changes: 11 additions & 11 deletions tests/test_leap.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Tests to validate low-level network interactions."""
import asyncio
import json
import orjson
from typing import AsyncGenerator, Iterable, NamedTuple, Tuple

import pytest
Expand Down Expand Up @@ -109,7 +109,7 @@ async def test_call(pipe: Pipe):
"""Test basic call and response."""
task = asyncio.create_task(pipe.leap.request("ReadRequest", "/test"))

received = json.loads((await pipe.test_reader.readline()).decode("utf-8"))
received = orjson.loads(await pipe.test_reader.readline())

# message should contain ClientTag
tag = received.get("Header", {}).pop("ClientTag", None)
Expand All @@ -123,7 +123,7 @@ async def test_call(pipe: Pipe):
"Header": {"ClientTag": tag, "StatusCode": "200 OK", "Url": "/test"},
"Body": {"ok": True},
}
response_bytes = f"{json.dumps(response_obj)}\r\n".encode("utf-8")
response_bytes = orjson.dumps(response_obj) + b"\r\n"
pipe.test_writer.write(response_bytes)

result = await task
Expand All @@ -148,7 +148,7 @@ async def test_read_invalid(pipe):
"""Test reading when invalid data is received."""
pipe.test_writer.write(b"?\r\n")

with pytest.raises(json.JSONDecodeError):
with pytest.raises(orjson.JSONDecodeError):
await pipe.leap_loop


Expand Down Expand Up @@ -190,7 +190,7 @@ def handler2(response):
"Header": {"StatusCode": "200 OK", "Url": "/test"},
"Body": {"Index": 0},
}
response_bytes = f"{json.dumps(response_dict)}\r\n".encode("utf-8")
response_bytes = orjson.dumps(response_dict) + b"\r\n"
pipe.test_writer.write(response_bytes)
response = Response.from_json(response_dict)

Expand All @@ -203,7 +203,7 @@ def handler2(response):
pipe.leap.unsubscribe_unsolicited(handler1)

response_dict["Body"]["Index"] = 1
response_bytes = f"{json.dumps(response_dict)}\r\n".encode("utf-8")
response_bytes = orjson.dumps(response_dict) + b"\r\n"
pipe.test_writer.write(response_bytes)
response = Response.from_json(response_dict)

Expand Down Expand Up @@ -232,7 +232,7 @@ def handler(response):

task = asyncio.create_task(pipe.leap.subscribe("/test", handler))

received = json.loads((await pipe.test_reader.readline()).decode("utf-8"))
received = orjson.loads(await pipe.test_reader.readline())

# message should contain ClientTag
tag = received.get("Header", {}).pop("ClientTag", None)
Expand All @@ -249,7 +249,7 @@ def handler(response):
"Header": {"ClientTag": tag, "StatusCode": "200 OK", "Url": "/test"},
"Body": {"ok": True},
}
response_bytes = f"{json.dumps(response_obj)}\r\n".encode("utf-8")
response_bytes = orjson.dumps(response_obj) + b"\r\n"
pipe.test_writer.write(response_bytes)

result, received_tag = await task
Expand All @@ -267,7 +267,7 @@ def handler(response):
"Header": {"ClientTag": tag, "StatusCode": "200 OK", "Url": "/test"},
"Body": {"ok": True},
}
response_bytes = f"{json.dumps(response_obj)}\r\n".encode("utf-8")
response_bytes = orjson.dumps(response_obj) + b"\r\n"
pipe.test_writer.write(response_bytes)

await asyncio.wait_for(handler_called.wait(), 1.0)
Expand All @@ -287,14 +287,14 @@ def _handler(_: Response):

task = asyncio.create_task(pipe.leap.subscribe("/test", _handler))

received = json.loads((await pipe.test_reader.readline()).decode("utf-8"))
received = orjson.loads(await pipe.test_reader.readline())

tag = received.get("Header", {}).pop("ClientTag", None)
response_obj = {
"CommuniqueType": "SubscribeResponse",
"Header": {"ClientTag": tag, "StatusCode": "404 Not Found", "Url": "/test"},
}
response_bytes = f"{json.dumps(response_obj)}\r\n".encode("utf-8")
response_bytes = orjson.dumps(response_obj) + b"\r\n"
pipe.test_writer.write(response_bytes)

result, _ = await task
Expand Down
4 changes: 2 additions & 2 deletions tests/test_smartbridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import asyncio
from collections import defaultdict
from datetime import timedelta
import json
import orjson
import logging
import os
import re
Expand Down Expand Up @@ -54,7 +54,7 @@ def response_from_json_file(filename: str) -> Response:
"""Fetch a response from a saved JSON file."""
responsedir = os.path.join(os.path.split(__file__)[0], "responses")
with open(os.path.join(responsedir, filename), "r", encoding="utf-8") as ifh:
return Response.from_json(json.load(ifh))
return Response.from_json(orjson.loads(ifh.read()))


class Request(NamedTuple):
Expand Down
Loading