Improve the readability of the config flow code (#42169)

This commit is contained in:
Paulus Schoutsen 2020-10-22 13:00:55 +02:00 committed by GitHub
parent 05a65bb612
commit e7b6903ef4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -10,7 +10,7 @@ from .const import DOMAIN # pylint:disable=unused-import
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# TODO adjust the data schema to the data that you need # TODO adjust the data schema to the data that you need
DATA_SCHEMA = vol.Schema({"host": str, "username": str, "password": str}) STEP_USER_DATA_SCHEMA = vol.Schema({"host": str, "username": str, "password": str})
class PlaceholderHub: class PlaceholderHub:
@ -31,7 +31,7 @@ class PlaceholderHub:
async def validate_input(hass: core.HomeAssistant, data): async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect. """Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user. Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
""" """
# TODO validate the data can be used to set up a connection. # TODO validate the data can be used to set up a connection.
@ -64,22 +64,27 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):
"""Handle the initial step.""" """Handle the initial step."""
errors = {} if user_input is None:
if user_input is not None: return self.async_show_form(
try: step_id="user", data_schema=STEP_USER_DATA_SCHEMA
info = await validate_input(self.hass, user_input) )
return self.async_create_entry(title=info["title"], data=user_input) errors = {}
except CannotConnect:
errors["base"] = "cannot_connect" try:
except InvalidAuth: info = await validate_input(self.hass, user_input)
errors["base"] = "invalid_auth" except CannotConnect:
except Exception: # pylint: disable=broad-except errors["base"] = "cannot_connect"
_LOGGER.exception("Unexpected exception") except InvalidAuth:
errors["base"] = "unknown" errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form( return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
) )