Rest fixes (#61296)

pull/61302/head
Paulus Schoutsen 2021-12-08 14:35:50 -08:00 committed by GitHub
parent af603d0427
commit 17cf53677c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 26 additions and 50 deletions

View File

@ -25,7 +25,6 @@ from homeassistant.const import (
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.template import Template
_LOGGER = logging.getLogger(__name__)
_ENDPOINT = "https://pvoutput.org/service/r2/getstatus.jsp"
@ -60,10 +59,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
method = "GET"
payload = auth = None
verify_ssl = DEFAULT_VERIFY_SSL
headers = {
"X-Pvoutput-Apikey": Template(api_key, hass),
"X-Pvoutput-SystemId": Template(system_id, hass),
}
headers = {"X-Pvoutput-Apikey": api_key, "X-Pvoutput-SystemId": system_id}
rest = RestData(hass, method, _ENDPOINT, auth, headers, None, payload, verify_ssl)
await rest.async_update()

View File

@ -25,7 +25,7 @@ from homeassistant.const import (
SERVICE_RELOAD,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import discovery
from homeassistant.helpers import discovery, template
from homeassistant.helpers.entity_component import (
DEFAULT_SCAN_INTERVAL,
EntityComponent,
@ -37,7 +37,6 @@ from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import COORDINATOR, DOMAIN, PLATFORM_IDX, REST, REST_DATA, REST_IDX
from .data import RestData
from .schema import CONFIG_SCHEMA # noqa: F401
from .utils import inject_hass_in_templates_list
_LOGGER = logging.getLogger(__name__)
@ -161,7 +160,8 @@ def create_rest_data_from_config(hass, config):
resource_template.hass = hass
resource = resource_template.async_render(parse_result=False)
inject_hass_in_templates_list(hass, [headers, params])
template.attach(hass, headers)
template.attach(hass, params)
if username and password:
if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:

View File

@ -3,7 +3,7 @@ import logging
import httpx
from homeassistant.components.rest.utils import render_templates
from homeassistant.helpers import template
from homeassistant.helpers.httpx_client import get_async_client
DEFAULT_TIMEOUT = 10
@ -52,8 +52,8 @@ class RestData:
self._hass, verify_ssl=self._verify_ssl
)
rendered_headers = render_templates(self._headers, False)
rendered_params = render_templates(self._params, True)
rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_params = template.render_complex(self._params)
_LOGGER.debug("Updating from %s", self._resource)
try:

View File

@ -24,10 +24,8 @@ from homeassistant.const import (
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.helpers import config_validation as cv, template
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from .utils import inject_hass_in_templates_list, render_templates
_LOGGER = logging.getLogger(__name__)
CONF_BODY_OFF = "body_off"
@ -92,7 +90,9 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
body_on.hass = hass
if body_off is not None:
body_off.hass = hass
inject_hass_in_templates_list(hass, [headers, params])
template.attach(hass, headers)
template.attach(hass, params)
timeout = config.get(CONF_TIMEOUT)
try:
@ -207,8 +207,8 @@ class RestSwitch(SwitchEntity):
"""Send a state update to the device."""
websession = async_get_clientsession(self.hass, self._verify_ssl)
rendered_headers = render_templates(self._headers, False)
rendered_params = render_templates(self._params, True)
rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_params = template.render_complex(self._params)
async with async_timeout.timeout(self._timeout):
req = await getattr(websession, self._method)(
@ -233,8 +233,8 @@ class RestSwitch(SwitchEntity):
"""Get the latest data from REST API and update the state."""
websession = async_get_clientsession(hass, self._verify_ssl)
rendered_headers = render_templates(self._headers, False)
rendered_params = render_templates(self._params, True)
rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_params = template.render_complex(self._params)
async with async_timeout.timeout(self._timeout):
req = await websession.get(

View File

@ -1,27 +0,0 @@
"""Reusable utilities for the Rest component."""
from __future__ import annotations
from homeassistant.core import HomeAssistant
from homeassistant.helpers.template import Template
def inject_hass_in_templates_list(
hass: HomeAssistant, tpl_dict_list: list[dict[str, Template] | None]
):
"""Inject hass in a list of dict of templates."""
for tpl_dict in tpl_dict_list:
if tpl_dict is not None:
for tpl in tpl_dict.values():
tpl.hass = hass
def render_templates(tpl_dict: dict[str, Template] | None, parse_result: bool):
"""Render a dict of templates."""
if tpl_dict is None:
return None
rendered_items = {}
for item_name, template in tpl_dict.items():
if (value := template.async_render(parse_result=parse_result)) is not None:
rendered_items[item_name] = value
return rendered_items

View File

@ -110,18 +110,25 @@ def attach(hass: HomeAssistant, obj: Any) -> None:
def render_complex(
value: Any, variables: TemplateVarsType = None, limited: bool = False
value: Any,
variables: TemplateVarsType = None,
limited: bool = False,
parse_result: bool = True,
) -> Any:
"""Recursive template creator helper function."""
if isinstance(value, list):
return [render_complex(item, variables) for item in value]
return [
render_complex(item, variables, limited, parse_result) for item in value
]
if isinstance(value, collections.abc.Mapping):
return {
render_complex(key, variables): render_complex(item, variables)
render_complex(key, variables, limited, parse_result): render_complex(
item, variables, limited, parse_result
)
for key, item in value.items()
}
if isinstance(value, Template):
return value.async_render(variables, limited=limited)
return value.async_render(variables, limited=limited, parse_result=parse_result)
return value