Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Open Exchange Rates integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Mapping
7 from typing import Any
8 
9 from aioopenexchangerates import (
10  Client,
11  OpenExchangeRatesAuthError,
12  OpenExchangeRatesClientError,
13 )
14 import voluptuous as vol
15 
16 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
17 from homeassistant.const import CONF_API_KEY, CONF_BASE
18 from homeassistant.core import HomeAssistant
19 from homeassistant.data_entry_flow import AbortFlow
20 from homeassistant.helpers.aiohttp_client import async_get_clientsession
21 
22 from .const import CLIENT_TIMEOUT, DEFAULT_BASE, DOMAIN, LOGGER
23 
24 
26  currencies: dict[str, str], existing_data: Mapping[str, str]
27 ) -> vol.Schema:
28  """Return a form schema."""
29  return vol.Schema(
30  {
31  vol.Required(CONF_API_KEY): str,
32  vol.Optional(
33  CONF_BASE, default=existing_data.get(CONF_BASE) or DEFAULT_BASE
34  ): vol.In(currencies),
35  }
36  )
37 
38 
39 async def validate_input(hass: HomeAssistant, data: dict[str, str]) -> dict[str, str]:
40  """Validate the user input allows us to connect."""
41  client = Client(data[CONF_API_KEY], async_get_clientsession(hass))
42 
43  async with asyncio.timeout(CLIENT_TIMEOUT):
44  await client.get_latest(base=data[CONF_BASE])
45 
46  return {"title": data[CONF_BASE]}
47 
48 
50  """Handle a config flow for Open Exchange Rates."""
51 
52  VERSION = 1
53 
54  def __init__(self) -> None:
55  """Initialize the config flow."""
56  self.currenciescurrencies: dict[str, str] = {}
57 
58  async def async_step_user(
59  self, user_input: dict[str, Any] | None = None
60  ) -> ConfigFlowResult:
61  """Handle the initial step."""
62  currencies = await self.async_get_currenciesasync_get_currencies()
63 
64  if user_input is None:
65  existing_data: Mapping[str, Any] = {}
66  if self.sourcesourcesourcesource == SOURCE_REAUTH:
67  existing_data = self._get_reauth_entry_get_reauth_entry().data
68  return self.async_show_formasync_show_formasync_show_form(
69  step_id="user",
70  data_schema=get_data_schema(currencies, existing_data),
71  description_placeholders={
72  "signup": "https://openexchangerates.org/signup"
73  },
74  )
75 
76  errors = {}
77 
78  try:
79  info = await validate_input(self.hass, user_input)
80  except OpenExchangeRatesAuthError:
81  errors["base"] = "invalid_auth"
82  except OpenExchangeRatesClientError:
83  errors["base"] = "cannot_connect"
84  except TimeoutError:
85  errors["base"] = "timeout_connect"
86  except Exception: # noqa: BLE001
87  LOGGER.exception("Unexpected exception")
88  errors["base"] = "unknown"
89  else:
90  self._async_abort_entries_match_async_abort_entries_match(
91  {
92  CONF_API_KEY: user_input[CONF_API_KEY],
93  CONF_BASE: user_input[CONF_BASE],
94  }
95  )
96 
97  if self.sourcesourcesourcesource == SOURCE_REAUTH:
98  return self.async_update_reload_and_abortasync_update_reload_and_abort(
99  self._get_reauth_entry_get_reauth_entry(), data_updates=user_input
100  )
101 
102  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
103 
104  return self.async_show_formasync_show_formasync_show_form(
105  step_id="user",
106  data_schema=get_data_schema(currencies, user_input),
107  description_placeholders={"signup": "https://openexchangerates.org/signup"},
108  errors=errors,
109  )
110 
111  async def async_step_reauth(
112  self, entry_data: Mapping[str, Any]
113  ) -> ConfigFlowResult:
114  """Handle reauth."""
115  return await self.async_step_userasync_step_userasync_step_user()
116 
117  async def async_get_currencies(self) -> dict[str, str]:
118  """Get the available currencies."""
119  if not self.currenciescurrencies:
120  client = Client("dummy-api-key", async_get_clientsession(self.hass))
121  try:
122  async with asyncio.timeout(CLIENT_TIMEOUT):
123  self.currenciescurrencies = await client.get_currencies()
124  except OpenExchangeRatesClientError as err:
125  raise AbortFlow("cannot_connect") from err
126  except TimeoutError as err:
127  raise AbortFlow("timeout_connect") from err
128  return self.currenciescurrencies
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:60
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:113
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
str|None source(self)
dict[str, str] validate_input(HomeAssistant hass, dict[str, str] data)
Definition: config_flow.py:39
vol.Schema get_data_schema(dict[str, str] currencies, Mapping[str, str] existing_data)
Definition: config_flow.py:27
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)