From db582bdc1b86b605b1d44cf828fca81bd38a6078 Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Tue, 15 Sep 2020 19:01:07 +0200 Subject: [PATCH] Use http status constants more, add HTTP_ACCEPTED and HTTP_BAD_GATEWAY (#39993) * Use http status codes and add HTTP_BAD_GATEWAY constant * Address review comments: - using constants in tado integration - using constant in media_player init.py * Add and use HTTP_ACCEPTED constant --- homeassistant/components/alexa/state_report.py | 6 +++--- homeassistant/components/auth/login_flow.py | 8 ++++++-- homeassistant/components/bloomsky/__init__.py | 11 ++++++++--- homeassistant/components/bond/config_flow.py | 9 +++++++-- homeassistant/components/clickatell/notify.py | 4 ++-- homeassistant/components/cloud/http_api.py | 17 +++++++++++++---- homeassistant/components/config/zwave.py | 6 ++++-- .../components/ddwrt/device_tracker.py | 3 ++- homeassistant/components/doorbird/__init__.py | 7 +++++-- .../components/doorbird/config_flow.py | 10 ++++++++-- homeassistant/components/foursquare/__init__.py | 9 +++++++-- .../components/google_assistant/http.py | 8 ++++++-- homeassistant/components/hassio/http.py | 3 ++- homeassistant/components/ios/notify.py | 5 +++-- homeassistant/components/lifx_cloud/scene.py | 10 ++++++++-- .../components/media_player/__init__.py | 5 +++-- .../components/melcloud/config_flow.py | 10 ++++++++-- homeassistant/components/mobile_app/notify.py | 11 ++++++++--- homeassistant/components/nest/local_auth.py | 3 ++- homeassistant/components/onvif/__init__.py | 3 ++- homeassistant/components/sendgrid/notify.py | 3 ++- homeassistant/components/shelly/config_flow.py | 9 +++++++-- homeassistant/components/sigfox/sensor.py | 4 ++-- .../components/smartthings/__init__.py | 3 ++- .../components/synology_chat/notify.py | 4 ++-- homeassistant/components/tesla/config_flow.py | 3 ++- .../components/thethingsnetwork/sensor.py | 4 ++-- .../components/tomato/device_tracker.py | 3 ++- homeassistant/components/verisure/__init__.py | 3 ++- homeassistant/components/withings/common.py | 3 ++- homeassistant/const.py | 2 ++ homeassistant/helpers/data_entry_flow.py | 6 +++--- 32 files changed, 137 insertions(+), 58 deletions(-) diff --git a/homeassistant/components/alexa/state_report.py b/homeassistant/components/alexa/state_report.py index a61dfc02d10..1d06422056d 100644 --- a/homeassistant/components/alexa/state_report.py +++ b/homeassistant/components/alexa/state_report.py @@ -6,7 +6,7 @@ import logging import aiohttp import async_timeout -from homeassistant.const import MATCH_ALL, STATE_ON +from homeassistant.const import HTTP_ACCEPTED, MATCH_ALL, STATE_ON import homeassistant.util.dt as dt_util from .const import API_CHANGE, Cause @@ -109,7 +109,7 @@ async def async_send_changereport_message( _LOGGER.debug("Sent: %s", json.dumps(message_serialized)) _LOGGER.debug("Received (%s): %s", response.status, response_text) - if response.status == 202: + if response.status == HTTP_ACCEPTED: return response_json = json.loads(response_text) @@ -240,7 +240,7 @@ async def async_send_doorbell_event_message(hass, config, alexa_entity): _LOGGER.debug("Sent: %s", json.dumps(message_serialized)) _LOGGER.debug("Received (%s): %s", response.status, response_text) - if response.status == 202: + if response.status == HTTP_ACCEPTED: return response_json = json.loads(response_text) diff --git a/homeassistant/components/auth/login_flow.py b/homeassistant/components/auth/login_flow.py index 31e3b7ea648..725450a0a12 100644 --- a/homeassistant/components/auth/login_flow.py +++ b/homeassistant/components/auth/login_flow.py @@ -80,7 +80,11 @@ from homeassistant.components.http.ban import ( ) from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.view import HomeAssistantView -from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND +from homeassistant.const import ( + HTTP_BAD_REQUEST, + HTTP_METHOD_NOT_ALLOWED, + HTTP_NOT_FOUND, +) from . import indieauth @@ -153,7 +157,7 @@ class LoginFlowIndexView(HomeAssistantView): async def get(self, request): """Do not allow index of flows in progress.""" - return web.Response(status=405) + return web.Response(status=HTTP_METHOD_NOT_ALLOWED) @RequestDataValidator( vol.Schema( diff --git a/homeassistant/components/bloomsky/__init__.py b/homeassistant/components/bloomsky/__init__.py index 929f8218144..cd993e0332a 100644 --- a/homeassistant/components/bloomsky/__init__.py +++ b/homeassistant/components/bloomsky/__init__.py @@ -6,7 +6,12 @@ from aiohttp.hdrs import AUTHORIZATION import requests import voluptuous as vol -from homeassistant.const import CONF_API_KEY, HTTP_OK +from homeassistant.const import ( + CONF_API_KEY, + HTTP_METHOD_NOT_ALLOWED, + HTTP_OK, + HTTP_UNAUTHORIZED, +) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle @@ -67,9 +72,9 @@ class BloomSky: headers={AUTHORIZATION: self._api_key}, timeout=10, ) - if response.status_code == 401: + if response.status_code == HTTP_UNAUTHORIZED: raise RuntimeError("Invalid API_KEY") - if response.status_code == 405: + if response.status_code == HTTP_METHOD_NOT_ALLOWED: _LOGGER.error("You have no bloomsky devices configured") return if response.status_code != HTTP_OK: diff --git a/homeassistant/components/bond/config_flow.py b/homeassistant/components/bond/config_flow.py index 49ca559685c..6666cd57ca3 100644 --- a/homeassistant/components/bond/config_flow.py +++ b/homeassistant/components/bond/config_flow.py @@ -7,7 +7,12 @@ from bond_api import Bond import voluptuous as vol from homeassistant import config_entries, exceptions -from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST, CONF_NAME +from homeassistant.const import ( + CONF_ACCESS_TOKEN, + CONF_HOST, + CONF_NAME, + HTTP_UNAUTHORIZED, +) from .const import CONF_BOND_ID from .const import DOMAIN # pylint:disable=unused-import @@ -31,7 +36,7 @@ async def _validate_input(data: Dict[str, Any]) -> str: except ClientConnectionError as error: raise InputValidationError("cannot_connect") from error except ClientResponseError as error: - if error.status == 401: + if error.status == HTTP_UNAUTHORIZED: raise InputValidationError("invalid_auth") from error raise InputValidationError("unknown") from error except Exception as error: diff --git a/homeassistant/components/clickatell/notify.py b/homeassistant/components/clickatell/notify.py index 966dbdee6e2..09096f44b74 100644 --- a/homeassistant/components/clickatell/notify.py +++ b/homeassistant/components/clickatell/notify.py @@ -5,7 +5,7 @@ import requests import voluptuous as vol from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService -from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT, HTTP_OK +from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT, HTTP_ACCEPTED, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -37,5 +37,5 @@ class ClickatellNotificationService(BaseNotificationService): data = {"apiKey": self.api_key, "to": self.recipient, "content": message} resp = requests.get(BASE_API_URL, params=data, timeout=5) - if (resp.status_code != HTTP_OK) or (resp.status_code != 202): + if (resp.status_code != HTTP_OK) or (resp.status_code != HTTP_ACCEPTED): _LOGGER.error("Error %s : %s", resp.status_code, resp.text) diff --git a/homeassistant/components/cloud/http_api.py b/homeassistant/components/cloud/http_api.py index 00a2ddb4663..3075f6a3f9d 100644 --- a/homeassistant/components/cloud/http_api.py +++ b/homeassistant/components/cloud/http_api.py @@ -19,7 +19,13 @@ from homeassistant.components.google_assistant import helpers as google_helpers from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.websocket_api import const as ws_const -from homeassistant.const import HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR, HTTP_OK +from homeassistant.const import ( + HTTP_BAD_GATEWAY, + HTTP_BAD_REQUEST, + HTTP_INTERNAL_SERVER_ERROR, + HTTP_OK, + HTTP_UNAUTHORIZED, +) from homeassistant.core import callback from .const import ( @@ -73,7 +79,10 @@ _CLOUD_ERRORS = { HTTP_INTERNAL_SERVER_ERROR, "Remote UI not compatible with 127.0.0.1/::1 as trusted proxies.", ), - asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."), + asyncio.TimeoutError: ( + HTTP_BAD_GATEWAY, + "Unable to reach the Home Assistant cloud.", + ), aiohttp.ClientError: ( HTTP_INTERNAL_SERVER_ERROR, "Error making internal request", @@ -122,7 +131,7 @@ async def async_setup(hass): HTTP_BAD_REQUEST, "An account with the given email already exists.", ), - auth.Unauthenticated: (401, "Authentication failed."), + auth.Unauthenticated: (HTTP_UNAUTHORIZED, "Authentication failed."), auth.PasswordChangeRequired: ( HTTP_BAD_REQUEST, "Password change required.", @@ -177,7 +186,7 @@ def _process_cloud_exception(exc, where): if err_info is None: _LOGGER.exception("Unexpected error processing request for %s", where) - err_info = (502, f"Unexpected error: {exc}") + err_info = (HTTP_BAD_GATEWAY, f"Unexpected error: {exc}") return err_info diff --git a/homeassistant/components/config/zwave.py b/homeassistant/components/config/zwave.py index edc2e9af42c..7a99d29c774 100644 --- a/homeassistant/components/config/zwave.py +++ b/homeassistant/components/config/zwave.py @@ -6,7 +6,7 @@ from aiohttp.web import Response from homeassistant.components.http import HomeAssistantView from homeassistant.components.zwave import DEVICE_CONFIG_SCHEMA_ENTRY, const -from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_OK +from homeassistant.const import HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_OK import homeassistant.core as ha import homeassistant.helpers.config_validation as cv @@ -254,7 +254,9 @@ class ZWaveProtectionView(HomeAssistantView): ) state = node.set_protection(value_id, selection) if not state: - return self.json_message("Protection setting did not complete", 202) + return self.json_message( + "Protection setting did not complete", HTTP_ACCEPTED + ) return self.json_message("Protection setting succsessfully set", HTTP_OK) return await hass.async_add_executor_job(_set_protection) diff --git a/homeassistant/components/ddwrt/device_tracker.py b/homeassistant/components/ddwrt/device_tracker.py index 9b6fd1bdb64..c324d6a5b64 100644 --- a/homeassistant/components/ddwrt/device_tracker.py +++ b/homeassistant/components/ddwrt/device_tracker.py @@ -17,6 +17,7 @@ from homeassistant.const import ( CONF_USERNAME, CONF_VERIFY_SSL, HTTP_OK, + HTTP_UNAUTHORIZED, ) import homeassistant.helpers.config_validation as cv @@ -155,7 +156,7 @@ class DdWrtDeviceScanner(DeviceScanner): return if response.status_code == HTTP_OK: return _parse_ddwrt_response(response.text) - if response.status_code == 401: + if response.status_code == HTTP_UNAUTHORIZED: # Authentication error _LOGGER.exception( "Failed to authenticate, check your username and password" diff --git a/homeassistant/components/doorbird/__init__.py b/homeassistant/components/doorbird/__init__.py index 43ab0c96153..1f7e02e8569 100644 --- a/homeassistant/components/doorbird/__init__.py +++ b/homeassistant/components/doorbird/__init__.py @@ -19,6 +19,7 @@ from homeassistant.const import ( CONF_TOKEN, CONF_USERNAME, HTTP_OK, + HTTP_UNAUTHORIZED, ) from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady @@ -127,7 +128,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): status = await hass.async_add_executor_job(device.ready) info = await hass.async_add_executor_job(device.info) except urllib.error.HTTPError as err: - if err.code == 401: + if err.code == HTTP_UNAUTHORIZED: _LOGGER.error( "Authorization rejected by DoorBird for %s@%s", username, device_ip ) @@ -357,7 +358,9 @@ class DoorBirdRequestView(HomeAssistantView): device = get_doorstation_by_token(hass, token) if device is None: - return web.Response(status=401, text="Invalid token provided.") + return web.Response( + status=HTTP_UNAUTHORIZED, text="Invalid token provided." + ) if device: event_data = device.get_event_data() diff --git a/homeassistant/components/doorbird/config_flow.py b/homeassistant/components/doorbird/config_flow.py index 07b753da6ee..8e3f661254d 100644 --- a/homeassistant/components/doorbird/config_flow.py +++ b/homeassistant/components/doorbird/config_flow.py @@ -7,7 +7,13 @@ from doorbirdpy import DoorBird import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import ( + CONF_HOST, + CONF_NAME, + CONF_PASSWORD, + CONF_USERNAME, + HTTP_UNAUTHORIZED, +) from homeassistant.core import callback from homeassistant.util.network import is_link_local @@ -39,7 +45,7 @@ async def validate_input(hass: core.HomeAssistant, data): status = await hass.async_add_executor_job(device.ready) info = await hass.async_add_executor_job(device.info) except urllib.error.HTTPError as err: - if err.code == 401: + if err.code == HTTP_UNAUTHORIZED: raise InvalidAuth from err raise CannotConnect from err except OSError as err: diff --git a/homeassistant/components/foursquare/__init__.py b/homeassistant/components/foursquare/__init__.py index bae0336a63e..6f33c9ff591 100644 --- a/homeassistant/components/foursquare/__init__.py +++ b/homeassistant/components/foursquare/__init__.py @@ -5,7 +5,12 @@ import requests import voluptuous as vol from homeassistant.components.http import HomeAssistantView -from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_BAD_REQUEST, HTTP_OK +from homeassistant.const import ( + CONF_ACCESS_TOKEN, + HTTP_BAD_REQUEST, + HTTP_CREATED, + HTTP_OK, +) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -55,7 +60,7 @@ def setup(hass, config): url = f"https://api.foursquare.com/v2/checkins/add?oauth_token={config[CONF_ACCESS_TOKEN]}&v=20160802&m=swarm" response = requests.post(url, data=call.data, timeout=10) - if response.status_code not in (HTTP_OK, 201): + if response.status_code not in (HTTP_OK, HTTP_CREATED): _LOGGER.exception( "Error checking in user. Response %d: %s:", response.status_code, diff --git a/homeassistant/components/google_assistant/http.py b/homeassistant/components/google_assistant/http.py index 7b75a36f8bb..4bf0df8b933 100644 --- a/homeassistant/components/google_assistant/http.py +++ b/homeassistant/components/google_assistant/http.py @@ -10,7 +10,11 @@ import jwt # Typing imports from homeassistant.components.http import HomeAssistantView -from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES, HTTP_INTERNAL_SERVER_ERROR +from homeassistant.const import ( + CLOUD_NEVER_EXPOSED_ENTITIES, + HTTP_INTERNAL_SERVER_ERROR, + HTTP_UNAUTHORIZED, +) from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.util import dt as dt_util @@ -200,7 +204,7 @@ class GoogleConfig(AbstractConfig): try: return await _call() except ClientResponseError as error: - if error.status == 401: + if error.status == HTTP_UNAUTHORIZED: _LOGGER.warning( "Request for %s unauthorized, renewing token and retrying", url ) diff --git a/homeassistant/components/hassio/http.py b/homeassistant/components/hassio/http.py index be2cec5ae9c..6dccdeb2101 100644 --- a/homeassistant/components/hassio/http.py +++ b/homeassistant/components/hassio/http.py @@ -12,6 +12,7 @@ from aiohttp.web_exceptions import HTTPBadGateway import async_timeout from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView +from homeassistant.const import HTTP_UNAUTHORIZED from .const import X_HASS_IS_ADMIN, X_HASS_USER_ID, X_HASSIO @@ -53,7 +54,7 @@ class HassIOView(HomeAssistantView): ) -> Union[web.Response, web.StreamResponse]: """Route data to Hass.io.""" if _need_auth(path) and not request[KEY_AUTHENTICATED]: - return web.Response(status=401) + return web.Response(status=HTTP_UNAUTHORIZED) return await self._command_proxy(path, request) diff --git a/homeassistant/components/ios/notify.py b/homeassistant/components/ios/notify.py index 62dd72973da..f9c682bf527 100644 --- a/homeassistant/components/ios/notify.py +++ b/homeassistant/components/ios/notify.py @@ -12,6 +12,7 @@ from homeassistant.components.notify import ( ATTR_TITLE_DEFAULT, BaseNotificationService, ) +from homeassistant.const import HTTP_CREATED, HTTP_TOO_MANY_REQUESTS import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) @@ -90,13 +91,13 @@ class iOSNotificationService(BaseNotificationService): req = requests.post(PUSH_URL, json=data, timeout=10) - if req.status_code != 201: + if req.status_code != HTTP_CREATED: fallback_error = req.json().get("errorMessage", "Unknown error") fallback_message = ( f"Internal server error, please try again later: {fallback_error}" ) message = req.json().get("message", fallback_message) - if req.status_code == 429: + if req.status_code == HTTP_TOO_MANY_REQUESTS: _LOGGER.warning(message) log_rate_limits(self.hass, target, req.json(), 30) else: diff --git a/homeassistant/components/lifx_cloud/scene.py b/homeassistant/components/lifx_cloud/scene.py index 75ab4656794..cf39d70d89a 100644 --- a/homeassistant/components/lifx_cloud/scene.py +++ b/homeassistant/components/lifx_cloud/scene.py @@ -9,7 +9,13 @@ import async_timeout import voluptuous as vol from homeassistant.components.scene import Scene -from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN, HTTP_OK +from homeassistant.const import ( + CONF_PLATFORM, + CONF_TIMEOUT, + CONF_TOKEN, + HTTP_OK, + HTTP_UNAUTHORIZED, +) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -50,7 +56,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= devices = [LifxCloudScene(hass, headers, timeout, scene) for scene in data] async_add_entities(devices) return True - if status == 401: + if status == HTTP_UNAUTHORIZED: _LOGGER.error("Unauthorized (bad token?) on %s", url) return False diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index 348bc521a5a..47804fcc1cd 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -27,6 +27,7 @@ from homeassistant.const import ( HTTP_INTERNAL_SERVER_ERROR, HTTP_NOT_FOUND, HTTP_OK, + HTTP_UNAUTHORIZED, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, @@ -880,7 +881,7 @@ class MediaPlayerImageView(HomeAssistantView): """Start a get request.""" player = self.component.get_entity(entity_id) if player is None: - status = HTTP_NOT_FOUND if request[KEY_AUTHENTICATED] else 401 + status = HTTP_NOT_FOUND if request[KEY_AUTHENTICATED] else HTTP_UNAUTHORIZED return web.Response(status=status) authenticated = ( @@ -889,7 +890,7 @@ class MediaPlayerImageView(HomeAssistantView): ) if not authenticated: - return web.Response(status=401) + return web.Response(status=HTTP_UNAUTHORIZED) data, content_type = await player.async_get_media_image() diff --git a/homeassistant/components/melcloud/config_flow.py b/homeassistant/components/melcloud/config_flow.py index ed6fc31c414..8813883c151 100644 --- a/homeassistant/components/melcloud/config_flow.py +++ b/homeassistant/components/melcloud/config_flow.py @@ -9,7 +9,13 @@ import pymelcloud import voluptuous as vol from homeassistant import config_entries -from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME, HTTP_FORBIDDEN +from homeassistant.const import ( + CONF_PASSWORD, + CONF_TOKEN, + CONF_USERNAME, + HTTP_FORBIDDEN, + HTTP_UNAUTHORIZED, +) from .const import DOMAIN # pylint: disable=unused-import @@ -57,7 +63,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN): self.hass.helpers.aiohttp_client.async_get_clientsession(), ) except ClientResponseError as err: - if err.status == 401 or err.status == HTTP_FORBIDDEN: + if err.status == HTTP_UNAUTHORIZED or err.status == HTTP_FORBIDDEN: return self.async_abort(reason="invalid_auth") return self.async_abort(reason="cannot_connect") except (asyncio.TimeoutError, ClientError): diff --git a/homeassistant/components/mobile_app/notify.py b/homeassistant/components/mobile_app/notify.py index 62bb5fdf08d..04d308a5a05 100644 --- a/homeassistant/components/mobile_app/notify.py +++ b/homeassistant/components/mobile_app/notify.py @@ -12,7 +12,12 @@ from homeassistant.components.notify import ( ATTR_TITLE_DEFAULT, BaseNotificationService, ) -from homeassistant.const import HTTP_OK +from homeassistant.const import ( + HTTP_ACCEPTED, + HTTP_CREATED, + HTTP_OK, + HTTP_TOO_MANY_REQUESTS, +) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.util.dt as dt_util @@ -135,7 +140,7 @@ class MobileAppNotificationService(BaseNotificationService): response = await self._session.post(push_url, json=data) result = await response.json() - if response.status in [HTTP_OK, 201, 202]: + if response.status in [HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED]: log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result) continue @@ -152,7 +157,7 @@ class MobileAppNotificationService(BaseNotificationService): " This message is generated externally to Home Assistant." ) - if response.status == 429: + if response.status == HTTP_TOO_MANY_REQUESTS: _LOGGER.warning(message) log_rate_limits( self.hass, entry_data[ATTR_DEVICE_NAME], result, logging.WARNING diff --git a/homeassistant/components/nest/local_auth.py b/homeassistant/components/nest/local_auth.py index 8b0af5011ec..df03c054398 100644 --- a/homeassistant/components/nest/local_auth.py +++ b/homeassistant/components/nest/local_auth.py @@ -4,6 +4,7 @@ from functools import partial from nest.nest import AUTHORIZE_URL, AuthorizationError, NestAuth +from homeassistant.const import HTTP_UNAUTHORIZED from homeassistant.core import callback from . import config_flow @@ -42,7 +43,7 @@ async def resolve_auth_code(hass, client_id, client_secret, code): await hass.async_add_job(auth.login) return await result except AuthorizationError as err: - if err.response.status_code == 401: + if err.response.status_code == HTTP_UNAUTHORIZED: raise config_flow.CodeInvalid() raise config_flow.NestAuthError( f"Unknown error: {err} ({err.response.status_code})" diff --git a/homeassistant/components/onvif/__init__.py b/homeassistant/components/onvif/__init__.py index 964c7a70a6d..cf92f3df3ba 100644 --- a/homeassistant/components/onvif/__init__.py +++ b/homeassistant/components/onvif/__init__.py @@ -17,6 +17,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, + HTTP_UNAUTHORIZED, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady @@ -138,7 +139,7 @@ async def _get_snapshot_auth(hass, device, entry): try: response = await hass.async_add_executor_job(_get) - if response.status_code == 401: + if response.status_code == HTTP_UNAUTHORIZED: return HTTP_BASIC_AUTHENTICATION return HTTP_DIGEST_AUTHENTICATION diff --git a/homeassistant/components/sendgrid/notify.py b/homeassistant/components/sendgrid/notify.py index 6dbf4d5c2b7..8d8907f2dcf 100644 --- a/homeassistant/components/sendgrid/notify.py +++ b/homeassistant/components/sendgrid/notify.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_RECIPIENT, CONF_SENDER, CONTENT_TYPE_TEXT_PLAIN, + HTTP_ACCEPTED, ) import homeassistant.helpers.config_validation as cv @@ -65,5 +66,5 @@ class SendgridNotificationService(BaseNotificationService): } response = self._sg.client.mail.send.post(request_body=data) - if response.status_code != 202: + if response.status_code != HTTP_ACCEPTED: _LOGGER.error("Unable to send notification") diff --git a/homeassistant/components/shelly/config_flow.py b/homeassistant/components/shelly/config_flow.py index 6446d2dd2d2..0ebf70d2f00 100644 --- a/homeassistant/components/shelly/config_flow.py +++ b/homeassistant/components/shelly/config_flow.py @@ -8,7 +8,12 @@ import async_timeout import voluptuous as vol from homeassistant import config_entries, core -from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import ( + CONF_HOST, + CONF_PASSWORD, + CONF_USERNAME, + HTTP_UNAUTHORIZED, +) from homeassistant.helpers import aiohttp_client from .const import DOMAIN # pylint:disable=unused-import @@ -91,7 +96,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): try: device_info = await validate_input(self.hass, self.host, user_input) except aiohttp.ClientResponseError as error: - if error.status == 401: + if error.status == HTTP_UNAUTHORIZED: errors["base"] = "invalid_auth" else: errors["base"] = "cannot_connect" diff --git a/homeassistant/components/sigfox/sensor.py b/homeassistant/components/sigfox/sensor.py index 6df6e1d0c82..1de3cfeb8a0 100644 --- a/homeassistant/components/sigfox/sensor.py +++ b/homeassistant/components/sigfox/sensor.py @@ -8,7 +8,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_NAME, HTTP_OK +from homeassistant.const import CONF_NAME, HTTP_OK, HTTP_UNAUTHORIZED import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -67,7 +67,7 @@ class SigfoxAPI: url = urljoin(API_URL, "devicetypes") response = requests.get(url, auth=self._auth, timeout=10) if response.status_code != HTTP_OK: - if response.status_code == 401: + if response.status_code == HTTP_UNAUTHORIZED: _LOGGER.error("Invalid credentials for Sigfox API") else: _LOGGER.error( diff --git a/homeassistant/components/smartthings/__init__.py b/homeassistant/components/smartthings/__init__.py index 974cde35faf..d184a3ca6ce 100644 --- a/homeassistant/components/smartthings/__init__.py +++ b/homeassistant/components/smartthings/__init__.py @@ -14,6 +14,7 @@ from homeassistant.const import ( CONF_CLIENT_ID, CONF_CLIENT_SECRET, HTTP_FORBIDDEN, + HTTP_UNAUTHORIZED, ) from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -158,7 +159,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry): hass.data[DOMAIN][DATA_BROKERS][entry.entry_id] = broker except ClientResponseError as ex: - if ex.status in (401, HTTP_FORBIDDEN): + if ex.status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN): _LOGGER.exception( "Unable to setup configuration entry '%s' - please reconfigure the integration", entry.title, diff --git a/homeassistant/components/synology_chat/notify.py b/homeassistant/components/synology_chat/notify.py index c8f665cb408..df43c5668f3 100644 --- a/homeassistant/components/synology_chat/notify.py +++ b/homeassistant/components/synology_chat/notify.py @@ -10,7 +10,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONF_RESOURCE, CONF_VERIFY_SSL, HTTP_OK +from homeassistant.const import CONF_RESOURCE, CONF_VERIFY_SSL, HTTP_CREATED, HTTP_OK import homeassistant.helpers.config_validation as cv ATTR_FILE_URL = "file_url" @@ -57,7 +57,7 @@ class SynologyChatNotificationService(BaseNotificationService): self._resource, data=to_send, timeout=10, verify=self._verify_ssl ) - if response.status_code not in (HTTP_OK, 201): + if response.status_code not in (HTTP_OK, HTTP_CREATED): _LOGGER.exception( "Error sending message. Response %d: %s:", response.status_code, diff --git a/homeassistant/components/tesla/config_flow.py b/homeassistant/components/tesla/config_flow.py index 9e46a30972f..f21c8c76e23 100644 --- a/homeassistant/components/tesla/config_flow.py +++ b/homeassistant/components/tesla/config_flow.py @@ -11,6 +11,7 @@ from homeassistant.const import ( CONF_SCAN_INTERVAL, CONF_TOKEN, CONF_USERNAME, + HTTP_UNAUTHORIZED, ) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client, config_validation as cv @@ -140,7 +141,7 @@ async def validate_input(hass: core.HomeAssistant, data): test_login=True ) except TeslaException as ex: - if ex.code == 401: + if ex.code == HTTP_UNAUTHORIZED: _LOGGER.error("Invalid credentials: %s", ex) raise InvalidAuth() from ex _LOGGER.error("Unable to communicate with Tesla API: %s", ex) diff --git a/homeassistant/components/thethingsnetwork/sensor.py b/homeassistant/components/thethingsnetwork/sensor.py index 35a16d30f32..3555816213a 100644 --- a/homeassistant/components/thethingsnetwork/sensor.py +++ b/homeassistant/components/thethingsnetwork/sensor.py @@ -8,7 +8,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONTENT_TYPE_JSON, HTTP_NOT_FOUND +from homeassistant.const import CONTENT_TYPE_JSON, HTTP_NOT_FOUND, HTTP_UNAUTHORIZED from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -135,7 +135,7 @@ class TtnDataStorage: _LOGGER.error("The device is not available: %s", self._device_id) return None - if status == 401: + if status == HTTP_UNAUTHORIZED: _LOGGER.error("Not authorized for Application ID: %s", self._app_id) return None diff --git a/homeassistant/components/tomato/device_tracker.py b/homeassistant/components/tomato/device_tracker.py index 873da5a7864..ce660a60280 100644 --- a/homeassistant/components/tomato/device_tracker.py +++ b/homeassistant/components/tomato/device_tracker.py @@ -19,6 +19,7 @@ from homeassistant.const import ( CONF_USERNAME, CONF_VERIFY_SSL, HTTP_OK, + HTTP_UNAUTHORIZED, ) import homeassistant.helpers.config_validation as cv @@ -111,7 +112,7 @@ class TomatoDeviceScanner(DeviceScanner): self.last_results[param] = json.loads(value.replace("'", '"')) return True - if response.status_code == 401: + if response.status_code == HTTP_UNAUTHORIZED: # Authentication error _LOGGER.exception( "Failed to authenticate, please check your username and password" diff --git a/homeassistant/components/verisure/__init__.py b/homeassistant/components/verisure/__init__.py index 757e299792a..8cd8b0672cf 100644 --- a/homeassistant/components/verisure/__init__.py +++ b/homeassistant/components/verisure/__init__.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONF_SCAN_INTERVAL, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP, + HTTP_SERVICE_UNAVAILABLE, ) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv @@ -189,7 +190,7 @@ class VerisureHub: self.overview = self.session.get_overview() except verisure.ResponseError as ex: _LOGGER.error("Could not read overview, %s", ex) - if ex.status_code == 503: # Service unavailable + if ex.status_code == HTTP_SERVICE_UNAVAILABLE: # Service unavailable _LOGGER.info("Trying to log in again") self.login() else: diff --git a/homeassistant/components/withings/common.py b/homeassistant/components/withings/common.py index af81c0e68d3..067133f331f 100644 --- a/homeassistant/components/withings/common.py +++ b/homeassistant/components/withings/common.py @@ -29,6 +29,7 @@ from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_WEBHOOK_ID, + HTTP_UNAUTHORIZED, MASS_KILOGRAMS, PERCENTAGE, SPEED_METERS_PER_SECOND, @@ -54,7 +55,7 @@ from .const import Measurement _LOGGER = logging.getLogger(const.LOG_NAMESPACE) NOT_AUTHENTICATED_ERROR = re.compile( - "^401,.*", + f"^{HTTP_UNAUTHORIZED},.*", re.IGNORECASE, ) DATA_UPDATED_SIGNAL = "withings_entity_state_updated" diff --git a/homeassistant/const.py b/homeassistant/const.py index 81f2243bca3..fc44f6a8712 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -564,6 +564,7 @@ URL_API_TEMPLATE = "/api/template" HTTP_OK = 200 HTTP_CREATED = 201 +HTTP_ACCEPTED = 202 HTTP_MOVED_PERMANENTLY = 301 HTTP_BAD_REQUEST = 400 HTTP_UNAUTHORIZED = 401 @@ -573,6 +574,7 @@ HTTP_METHOD_NOT_ALLOWED = 405 HTTP_UNPROCESSABLE_ENTITY = 422 HTTP_TOO_MANY_REQUESTS = 429 HTTP_INTERNAL_SERVER_ERROR = 500 +HTTP_BAD_GATEWAY = 502 HTTP_SERVICE_UNAVAILABLE = 503 HTTP_BASIC_AUTHENTICATION = "basic" diff --git a/homeassistant/helpers/data_entry_flow.py b/homeassistant/helpers/data_entry_flow.py index 1cf1fa4545c..e686dd2ae4b 100644 --- a/homeassistant/helpers/data_entry_flow.py +++ b/homeassistant/helpers/data_entry_flow.py @@ -8,7 +8,7 @@ import voluptuous as vol from homeassistant import config_entries, data_entry_flow from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator -from homeassistant.const import HTTP_NOT_FOUND +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND import homeassistant.helpers.config_validation as cv @@ -76,7 +76,7 @@ class FlowManagerIndexView(_BaseFlowManagerView): except data_entry_flow.UnknownHandler: return self.json_message("Invalid handler specified", HTTP_NOT_FOUND) except data_entry_flow.UnknownStep: - return self.json_message("Handler does not support user", 400) + return self.json_message("Handler does not support user", HTTP_BAD_REQUEST) result = self._prepare_result_json(result) @@ -107,7 +107,7 @@ class FlowManagerResourceView(_BaseFlowManagerView): except data_entry_flow.UnknownFlow: return self.json_message("Invalid flow specified", HTTP_NOT_FOUND) except vol.Invalid: - return self.json_message("User input malformed", 400) + return self.json_message("User input malformed", HTTP_BAD_REQUEST) result = self._prepare_result_json(result)