From 03e3ebb2380f34943e9ff3feae57855f23863ef3 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 14 Jul 2022 22:37:12 +0200 Subject: [PATCH] Use json_loads by default for the aiohttp helper (#75214) --- homeassistant/helpers/aiohttp_client.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/homeassistant/helpers/aiohttp_client.py b/homeassistant/helpers/aiohttp_client.py index 2ef96091d152c3..f44b59ff0779b7 100644 --- a/homeassistant/helpers/aiohttp_client.py +++ b/homeassistant/helpers/aiohttp_client.py @@ -7,7 +7,7 @@ from ssl import SSLContext import sys from types import MappingProxyType -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast import aiohttp from aiohttp import web @@ -22,7 +22,11 @@ from homeassistant.util import ssl as ssl_util from .frame import warn_use -from .json import json_dumps +from .json import json_dumps, json_loads + +if TYPE_CHECKING: + from aiohttp.typedefs import JSONDecoder + DATA_CONNECTOR = "aiohttp_connector" DATA_CONNECTOR_NOTVERIFY = "aiohttp_connector_notverify" @@ -35,6 +39,19 @@ WARN_CLOSE_MSG = "closes the Home Assistant aiohttp session" +class HassClientResponse(aiohttp.ClientResponse): + """aiohttp.ClientResponse with a json method that uses json_loads by default.""" + + async def json( + self, + *args: Any, + loads: JSONDecoder = json_loads, + **kwargs: Any, + ) -> Any: + """Send a json request and parse the json response.""" + return await super().json(*args, loads=loads, **kwargs) + + @callback @bind_hass def async_get_clientsession( @@ -99,6 +116,7 @@ def _async_create_clientsession( clientsession = aiohttp.ClientSession( connector=_async_get_connector(hass, verify_ssl), json_serialize=json_dumps, + response_class=HassClientResponse, **kwargs, ) # Prevent packages accidentally overriding our default headers