Convert rest sensors to async using httpx (#41973)

This commit is contained in:
J. Nick Koston authored and GitHub committed 2020-10-16 19:21:13 -05:00
1 parent 39adf14079
commit ad6ce5fa83
12 files changed
+1094 -970

No files matched your search

+40 -22
View File
@@ -3,10 +3,8 @@ import json
import logging
from xml.parsers.expat import ExpatError
import httpx
from jsonpath import jsonpath
import requests
from requests import Session
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import voluptuous as vol
import xmltodict
@@ -33,7 +31,7 @@ from homeassistant.const import (
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.reload import setup_reload_service
from homeassistant.helpers.reload import async_setup_reload_service
from . import DOMAIN, PLATFORMS
@@ -79,9 +77,9 @@ PLATFORM_SCHEMA = vol.All(
)
def setup_platform(hass, config, add_entities, discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the RESTful sensor."""
setup_reload_service(hass, DOMAIN, PLATFORMS)
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
name = config.get(CONF_NAME)
resource = config.get(CONF_RESOURCE)
@@ -109,19 +107,20 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if username and password:
if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
auth = HTTPDigestAuth(username, password)
auth = httpx.DigestAuth(username, password)
else:
auth = HTTPBasicAuth(username, password)
auth = (username, password)
else:
auth = None
rest = RestData(method, resource, auth, headers, payload, verify_ssl, timeout)
rest.update()
await rest.async_update()
if rest.data is None:
raise PlatformNotReady
# Must update the sensor now (including fetching the rest resource) to
# ensure it's updating its state.
add_entities(
async_add_entities(
[
RestSensor(
hass,
@@ -200,12 +199,13 @@ class RestSensor(Entity):
"""Force update."""
return self._force_update
def update(self):
async def async_update(self):
"""Get the latest data from REST API and update the state."""
if self._resource_template is not None:
self.rest.set_url(self._resource_template.render())
self.rest.update()
await self.rest.async_update()
value = self.rest.data
_LOGGER.debug("Data fetched from resource: %s", value)
if self.rest.headers is not None:
@@ -250,13 +250,21 @@ class RestSensor(Entity):
except ValueError:
_LOGGER.warning("REST result could not be parsed as JSON")
_LOGGER.debug("Erroneous JSON: %s", value)
else:
_LOGGER.warning("Empty reply found when expecting JSON data")
if value is not None and self._value_template is not None:
value = self._value_template.render_with_possible_json_value(value, None)
value = self._value_template.async_render_with_possible_json_value(
value, None
)
self._state = value
async def async_will_remove_from_hass(self):
"""Shutdown the session."""
await self.rest.async_remove()
@property
def device_state_attributes(self):
"""Return the state attributes."""
@@ -267,7 +275,14 @@ class RestData:
"""Class for handling the data retrieval."""
def __init__(
self, method, resource, auth, headers, data, verify_ssl, timeout=DEFAULT_TIMEOUT
self,
method,
resource,
auth,
headers,
data,
verify_ssl,
timeout=DEFAULT_TIMEOUT,
):
"""Initialize the data object."""
self._method = method
@@ -275,36 +290,39 @@ class RestData:
self._auth = auth
self._headers = headers
self._request_data = data
self._verify_ssl = verify_ssl
self._timeout = timeout
self._http_session = Session()
self._verify_ssl = verify_ssl
self._async_client = None
self.data = None
self.headers = None
def __del__(self):
async def async_remove(self):
"""Destroy the http session on destroy."""
self._http_session.close()
if self._async_client:
await self._async_client.aclose()
def set_url(self, url):
"""Set url."""
self._resource = url
def update(self):
async def async_update(self):
"""Get the latest data from REST service with provided method."""
if not self._async_client:
self._async_client = httpx.AsyncClient(verify=self._verify_ssl)
_LOGGER.debug("Updating from %s", self._resource)
try:
response = self._http_session.request(
response = await self._async_client.request(
self._method,
self._resource,
headers=self._headers,
auth=self._auth,
data=self._request_data,
timeout=self._timeout,
verify=self._verify_ssl,
)
self.data = response.text
self.headers = response.headers
except requests.exceptions.RequestException as ex:
except httpx.RequestError as ex:
_LOGGER.error("Error fetching data: %s failed with %s", self._resource, ex)
self.data = None
self.headers = None