Home Assistant Unofficial Reference 2024.12.1
utils.py
Go to the documentation of this file.
1 """Util functions for OpenWeatherMap."""
2 
3 from typing import Any
4 
5 from pyopenweathermap import RequestError, create_owm_client
6 
7 from homeassistant.const import CONF_LANGUAGE, CONF_MODE
8 
9 from .const import DEFAULT_LANGUAGE, DEFAULT_OWM_MODE
10 
11 OPTION_DEFAULTS = {CONF_LANGUAGE: DEFAULT_LANGUAGE, CONF_MODE: DEFAULT_OWM_MODE}
12 
13 
14 async def validate_api_key(api_key, mode):
15  """Validate API key."""
16  api_key_valid = None
17  errors, description_placeholders = {}, {}
18  try:
19  owm_client = create_owm_client(api_key, mode)
20  api_key_valid = await owm_client.validate_key()
21  except RequestError as error:
22  errors["base"] = "cannot_connect"
23  description_placeholders["error"] = str(error)
24 
25  if api_key_valid is False:
26  errors["base"] = "invalid_api_key"
27 
28  return errors, description_placeholders
29 
30 
32  combined_data: dict[str, Any],
33 ) -> tuple[dict[str, Any], dict[str, Any]]:
34  """Split combined data and options."""
35  data = {k: v for k, v in combined_data.items() if k not in OPTION_DEFAULTS}
36  options = {
37  option: combined_data.get(option, default)
38  for option, default in OPTION_DEFAULTS.items()
39  }
40  return (data, options)
tuple[dict[str, Any], dict[str, Any]] build_data_and_options(dict[str, Any] combined_data)
Definition: utils.py:33