Use orjson to parse json faster (#32153)

* [recorder] Use orjson to parse json faster

* Remove from http manifest

* Bump to orjson 2.5.1

* Empty commit to trigger CI

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
Ruslan Sayfutdinov 2020-02-25 18:20:51 +00:00 committed by GitHub
parent 5c12fa0daa
commit 2365e2e8cf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 14 additions and 6 deletions

View File

@ -3,6 +3,7 @@ from datetime import datetime
import json import json
import logging import logging
import orjson
from sqlalchemy import ( from sqlalchemy import (
Boolean, Boolean,
Column, Column,
@ -63,7 +64,7 @@ class Events(Base): # type: ignore
try: try:
return Event( return Event(
self.event_type, self.event_type,
json.loads(self.event_data), orjson.loads(self.event_data),
EventOrigin(self.origin), EventOrigin(self.origin),
_process_timestamp(self.time_fired), _process_timestamp(self.time_fired),
context=context, context=context,
@ -133,7 +134,7 @@ class States(Base): # type: ignore
return State( return State(
self.entity_id, self.entity_id,
self.state, self.state,
json.loads(self.attributes), orjson.loads(self.attributes),
_process_timestamp(self.last_changed), _process_timestamp(self.last_changed),
_process_timestamp(self.last_updated), _process_timestamp(self.last_updated),
context=context, context=context,

View File

@ -9,6 +9,7 @@ from aiohttp import web
from aiohttp.hdrs import CONTENT_TYPE, USER_AGENT from aiohttp.hdrs import CONTENT_TYPE, USER_AGENT
from aiohttp.web_exceptions import HTTPBadGateway, HTTPGatewayTimeout from aiohttp.web_exceptions import HTTPBadGateway, HTTPGatewayTimeout
import async_timeout import async_timeout
import orjson
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE, __version__ from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE, __version__
from homeassistant.core import Event, callback from homeassistant.core import Event, callback
@ -67,6 +68,7 @@ def async_create_clientsession(
loop=hass.loop, loop=hass.loop,
connector=connector, connector=connector,
headers={USER_AGENT: SERVER_SOFTWARE}, headers={USER_AGENT: SERVER_SOFTWARE},
json_serialize=lambda x: orjson.dumps(x).decode(),
**kwargs, **kwargs,
) )

View File

@ -16,6 +16,7 @@ home-assistant-frontend==20200220.1
importlib-metadata==1.5.0 importlib-metadata==1.5.0
jinja2>=2.10.3 jinja2>=2.10.3
netdisco==2.6.0 netdisco==2.6.0
orjson==2.5.1
pip>=8.0.3 pip>=8.0.3
python-slugify==4.0.0 python-slugify==4.0.0
pytz>=2019.03 pytz>=2019.03

View File

@ -6,6 +6,8 @@ import os
import tempfile import tempfile
from typing import Any, Dict, List, Optional, Type, Union from typing import Any, Dict, List, Optional, Type, Union
import orjson
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -28,7 +30,7 @@ def load_json(
""" """
try: try:
with open(filename, encoding="utf-8") as fdesc: with open(filename, encoding="utf-8") as fdesc:
return json.loads(fdesc.read()) # type: ignore return orjson.loads(fdesc.read()) # type: ignore
except FileNotFoundError: except FileNotFoundError:
# This is not a fatal error # This is not a fatal error
_LOGGER.debug("JSON file not found: %s", filename) _LOGGER.debug("JSON file not found: %s", filename)
@ -97,7 +99,7 @@ def find_paths_unserializable_data(bad_data: Any) -> List[str]:
obj, obj_path = to_process.popleft() obj, obj_path = to_process.popleft()
try: try:
json.dumps(obj) orjson.dumps(obj)
continue continue
except TypeError: except TypeError:
pass pass
@ -106,7 +108,7 @@ def find_paths_unserializable_data(bad_data: Any) -> List[str]:
for key, value in obj.items(): for key, value in obj.items():
try: try:
# Is key valid? # Is key valid?
json.dumps({key: None}) orjson.dumps({key: None})
except TypeError: except TypeError:
invalid.append(f"{obj_path}<key: {key}>") invalid.append(f"{obj_path}<key: {key}>")
else: else:

View File

@ -5,7 +5,7 @@ ignore=tests
jobs=2 jobs=2
load-plugins=pylint_strict_informational load-plugins=pylint_strict_informational
persistent=no persistent=no
extension-pkg-whitelist=ciso8601 extension-pkg-whitelist=ciso8601,orjson
[BASIC] [BASIC]
good-names=id,i,j,k,ex,Run,_,fp good-names=id,i,j,k,ex,Run,_,fp

View File

@ -10,6 +10,7 @@ importlib-metadata==1.5.0
jinja2>=2.10.3 jinja2>=2.10.3
PyJWT==1.7.1 PyJWT==1.7.1
cryptography==2.8 cryptography==2.8
orjson==2.5.1
pip>=8.0.3 pip>=8.0.3
python-slugify==4.0.0 python-slugify==4.0.0
pytz>=2019.03 pytz>=2019.03

View File

@ -44,6 +44,7 @@ REQUIRES = [
"PyJWT==1.7.1", "PyJWT==1.7.1",
# PyJWT has loose dependency. We want the latest one. # PyJWT has loose dependency. We want the latest one.
"cryptography==2.8", "cryptography==2.8",
"orjson==2.5.1",
"pip>=8.0.3", "pip>=8.0.3",
"python-slugify==4.0.0", "python-slugify==4.0.0",
"pytz>=2019.03", "pytz>=2019.03",