From 4c38e6cfa5c3eee5ca14bff6af83c793ffd0a1ec Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Thu, 9 Apr 2020 21:43:42 +0200 Subject: [PATCH] Use HTTP_BAD_REQUEST constant (#33797) --- homeassistant/components/abode/config_flow.py | 4 ++-- homeassistant/components/auth/__init__.py | 22 ++++++++++--------- homeassistant/components/auth/login_flow.py | 16 ++++++++------ homeassistant/components/calendar/__init__.py | 6 ++--- .../components/cloud/alexa_config.py | 4 ++-- homeassistant/components/cloud/http_api.py | 16 +++++++++----- homeassistant/components/config/__init__.py | 13 +++++++---- homeassistant/components/config/zwave.py | 4 ++-- .../components/free_mobile/notify.py | 3 ++- .../components/hassio/addon_panel.py | 3 ++- homeassistant/components/hassio/handler.py | 4 ++-- homeassistant/components/http/ban.py | 3 ++- .../components/http/data_validator.py | 8 +++++-- .../components/logi_circle/config_flow.py | 4 ++-- .../components/mobile_app/helpers.py | 4 ++-- homeassistant/components/nexia/__init__.py | 9 ++++++-- homeassistant/components/nexia/config_flow.py | 9 ++++++-- homeassistant/components/nuheat/__init__.py | 3 ++- .../components/nuheat/config_flow.py | 9 ++++++-- homeassistant/components/rest/notify.py | 3 ++- homeassistant/components/rest/switch.py | 3 ++- .../components/rest_command/__init__.py | 3 ++- homeassistant/components/tts/__init__.py | 16 ++++++++++---- homeassistant/components/xmpp/notify.py | 3 ++- 24 files changed, 111 insertions(+), 61 deletions(-) diff --git a/homeassistant/components/abode/config_flow.py b/homeassistant/components/abode/config_flow.py index 5c2c5e7b843..18146551a56 100644 --- a/homeassistant/components/abode/config_flow.py +++ b/homeassistant/components/abode/config_flow.py @@ -5,7 +5,7 @@ from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant import config_entries -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_BAD_REQUEST from homeassistant.core import callback from .const import DEFAULT_CACHEDB, DOMAIN, LOGGER # pylint: disable=unused-import @@ -46,7 +46,7 @@ class AbodeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): except (AbodeException, ConnectTimeout, HTTPError) as ex: LOGGER.error("Unable to connect to Abode: %s", str(ex)) - if ex.errcode == 400: + if ex.errcode == HTTP_BAD_REQUEST: return self._show_form({"base": "invalid_credentials"}) return self._show_form({"base": "connection_error"}) diff --git a/homeassistant/components/auth/__init__.py b/homeassistant/components/auth/__init__.py index 4c540cab843..5b1ca46c41b 100644 --- a/homeassistant/components/auth/__init__.py +++ b/homeassistant/components/auth/__init__.py @@ -132,7 +132,7 @@ from homeassistant.components.http.auth import async_sign_path from homeassistant.components.http.ban import log_invalid_auth from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.view import HomeAssistantView -from homeassistant.const import HTTP_FORBIDDEN, HTTP_OK +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_OK from homeassistant.core import HomeAssistant, callback from homeassistant.loader import bind_hass from homeassistant.util import dt as dt_util @@ -261,7 +261,9 @@ class TokenView(HomeAssistantView): hass, data, str(request[KEY_REAL_IP]) ) - return self.json({"error": "unsupported_grant_type"}, status_code=400) + return self.json( + {"error": "unsupported_grant_type"}, status_code=HTTP_BAD_REQUEST + ) async def _async_handle_revoke_token(self, hass, data): """Handle revoke token request.""" @@ -288,7 +290,7 @@ class TokenView(HomeAssistantView): if client_id is None or not indieauth.verify_client_id(client_id): return self.json( {"error": "invalid_request", "error_description": "Invalid client id"}, - status_code=400, + status_code=HTTP_BAD_REQUEST, ) code = data.get("code") @@ -296,7 +298,7 @@ class TokenView(HomeAssistantView): if code is None: return self.json( {"error": "invalid_request", "error_description": "Invalid code"}, - status_code=400, + status_code=HTTP_BAD_REQUEST, ) user = self._retrieve_user(client_id, RESULT_TYPE_USER, code) @@ -304,7 +306,7 @@ class TokenView(HomeAssistantView): if user is None or not isinstance(user, User): return self.json( {"error": "invalid_request", "error_description": "Invalid code"}, - status_code=400, + status_code=HTTP_BAD_REQUEST, ) # refresh user @@ -336,21 +338,21 @@ class TokenView(HomeAssistantView): if client_id is not None and not indieauth.verify_client_id(client_id): return self.json( {"error": "invalid_request", "error_description": "Invalid client id"}, - status_code=400, + status_code=HTTP_BAD_REQUEST, ) token = data.get("refresh_token") if token is None: - return self.json({"error": "invalid_request"}, status_code=400) + return self.json({"error": "invalid_request"}, status_code=HTTP_BAD_REQUEST) refresh_token = await hass.auth.async_get_refresh_token_by_token(token) if refresh_token is None: - return self.json({"error": "invalid_grant"}, status_code=400) + return self.json({"error": "invalid_grant"}, status_code=HTTP_BAD_REQUEST) if refresh_token.client_id != client_id: - return self.json({"error": "invalid_request"}, status_code=400) + return self.json({"error": "invalid_request"}, status_code=HTTP_BAD_REQUEST) access_token = hass.auth.async_create_access_token(refresh_token, remote_addr) @@ -386,7 +388,7 @@ class LinkUserView(HomeAssistantView): ) if credentials is None: - return self.json_message("Invalid code", status_code=400) + return self.json_message("Invalid code", status_code=HTTP_BAD_REQUEST) await hass.auth.async_link_user(user, credentials) return self.json_message("User linked") diff --git a/homeassistant/components/auth/login_flow.py b/homeassistant/components/auth/login_flow.py index 229cbb0c9df..c5d824ce617 100644 --- a/homeassistant/components/auth/login_flow.py +++ b/homeassistant/components/auth/login_flow.py @@ -79,7 +79,7 @@ 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_NOT_FOUND +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND from . import indieauth @@ -104,7 +104,7 @@ class AuthProvidersView(HomeAssistantView): if not hass.components.onboarding.async_is_user_onboarded(): return self.json_message( message="Onboarding not finished", - status_code=400, + status_code=HTTP_BAD_REQUEST, message_code="onboarding_required", ) @@ -170,7 +170,9 @@ class LoginFlowIndexView(HomeAssistantView): if not await indieauth.verify_redirect_uri( request.app["hass"], data["client_id"], data["redirect_uri"] ): - return self.json_message("invalid client id or redirect uri", 400) + return self.json_message( + "invalid client id or redirect uri", HTTP_BAD_REQUEST + ) if isinstance(data["handler"], list): handler = tuple(data["handler"]) @@ -188,7 +190,7 @@ class LoginFlowIndexView(HomeAssistantView): 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 init", 400) + return self.json_message("Handler does not support init", HTTP_BAD_REQUEST) if result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY: await process_success_login(request) @@ -222,7 +224,7 @@ class LoginFlowResourceView(HomeAssistantView): client_id = data.pop("client_id") if not indieauth.verify_client_id(client_id): - return self.json_message("Invalid client id", 400) + return self.json_message("Invalid client id", HTTP_BAD_REQUEST) try: # do not allow change ip during login flow @@ -230,13 +232,13 @@ class LoginFlowResourceView(HomeAssistantView): if flow["flow_id"] == flow_id and flow["context"][ "ip_address" ] != request.get(KEY_REAL_IP): - return self.json_message("IP address changed", 400) + return self.json_message("IP address changed", HTTP_BAD_REQUEST) result = await self._flow_mgr.async_configure(flow_id, data) 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) if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY: # @log_invalid_auth does not work here since it returns HTTP 200 diff --git a/homeassistant/components/calendar/__init__.py b/homeassistant/components/calendar/__init__.py index e930a0de597..6f7427a0234 100644 --- a/homeassistant/components/calendar/__init__.py +++ b/homeassistant/components/calendar/__init__.py @@ -6,7 +6,7 @@ import re from aiohttp import web from homeassistant.components import http -from homeassistant.const import STATE_OFF, STATE_ON +from homeassistant.const import HTTP_BAD_REQUEST, STATE_OFF, STATE_ON from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, @@ -182,12 +182,12 @@ class CalendarEventView(http.HomeAssistantView): start = request.query.get("start") end = request.query.get("end") if None in (start, end, entity): - return web.Response(status=400) + return web.Response(status=HTTP_BAD_REQUEST) try: start_date = dt.parse_datetime(start) end_date = dt.parse_datetime(end) except (ValueError, AttributeError): - return web.Response(status=400) + return web.Response(status=HTTP_BAD_REQUEST) event_list = await entity.async_get_events( request.app["hass"], start_date, end_date ) diff --git a/homeassistant/components/cloud/alexa_config.py b/homeassistant/components/cloud/alexa_config.py index 86b3532e00e..dc1f5c11b5d 100644 --- a/homeassistant/components/cloud/alexa_config.py +++ b/homeassistant/components/cloud/alexa_config.py @@ -13,7 +13,7 @@ from homeassistant.components.alexa import ( errors as alexa_errors, state_report as alexa_state_report, ) -from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES +from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES, HTTP_BAD_REQUEST from homeassistant.core import callback from homeassistant.helpers import entity_registry from homeassistant.helpers.event import async_call_later @@ -114,7 +114,7 @@ class AlexaConfig(alexa_config.AbstractConfig): resp = await cloud_api.async_alexa_access_token(self._cloud) body = await resp.json() - if resp.status == 400: + if resp.status == HTTP_BAD_REQUEST: if body["reason"] in ("RefreshTokenNotFound", "UnknownRegion"): if self.should_report_state: await self._prefs.async_update(alexa_report_state=False) diff --git a/homeassistant/components/cloud/http_api.py b/homeassistant/components/cloud/http_api.py index 8a30c4d9496..03fd8400dfa 100644 --- a/homeassistant/components/cloud/http_api.py +++ b/homeassistant/components/cloud/http_api.py @@ -19,7 +19,7 @@ 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_INTERNAL_SERVER_ERROR, HTTP_OK +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR, HTTP_OK from homeassistant.core import callback from .const import ( @@ -109,11 +109,17 @@ async def async_setup(hass): _CLOUD_ERRORS.update( { - auth.UserNotFound: (400, "User does not exist."), - auth.UserNotConfirmed: (400, "Email not confirmed."), - auth.UserExists: (400, "An account with the given email already exists."), + auth.UserNotFound: (HTTP_BAD_REQUEST, "User does not exist."), + auth.UserNotConfirmed: (HTTP_BAD_REQUEST, "Email not confirmed."), + auth.UserExists: ( + HTTP_BAD_REQUEST, + "An account with the given email already exists.", + ), auth.Unauthenticated: (401, "Authentication failed."), - auth.PasswordChangeRequired: (400, "Password change required."), + auth.PasswordChangeRequired: ( + HTTP_BAD_REQUEST, + "Password change required.", + ), asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."), aiohttp.ClientError: ( HTTP_INTERNAL_SERVER_ERROR, diff --git a/homeassistant/components/config/__init__.py b/homeassistant/components/config/__init__.py index 12a3adbd701..d7a257b1d9b 100644 --- a/homeassistant/components/config/__init__.py +++ b/homeassistant/components/config/__init__.py @@ -6,7 +6,12 @@ import os import voluptuous as vol from homeassistant.components.http import HomeAssistantView -from homeassistant.const import CONF_ID, EVENT_COMPONENT_LOADED, HTTP_NOT_FOUND +from homeassistant.const import ( + CONF_ID, + EVENT_COMPONENT_LOADED, + HTTP_BAD_REQUEST, + HTTP_NOT_FOUND, +) from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import ATTR_COMPONENT @@ -129,12 +134,12 @@ class BaseEditConfigView(HomeAssistantView): try: data = await request.json() except ValueError: - return self.json_message("Invalid JSON specified", 400) + return self.json_message("Invalid JSON specified", HTTP_BAD_REQUEST) try: self.key_schema(config_key) except vol.Invalid as err: - return self.json_message(f"Key malformed: {err}", 400) + return self.json_message(f"Key malformed: {err}", HTTP_BAD_REQUEST) hass = request.app["hass"] @@ -146,7 +151,7 @@ class BaseEditConfigView(HomeAssistantView): else: self.data_schema(data) except (vol.Invalid, HomeAssistantError) as err: - return self.json_message(f"Message malformed: {err}", 400) + return self.json_message(f"Message malformed: {err}", HTTP_BAD_REQUEST) path = hass.config.path(self.path) diff --git a/homeassistant/components/config/zwave.py b/homeassistant/components/config/zwave.py index 7e045934f7d..b8331d8192b 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_NOT_FOUND, HTTP_OK +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_OK import homeassistant.core as ha import homeassistant.helpers.config_validation as cv @@ -51,7 +51,7 @@ class ZWaveLogView(HomeAssistantView): try: lines = int(request.query.get("lines", 0)) except ValueError: - return Response(text="Invalid datetime", status=400) + return Response(text="Invalid datetime", status=HTTP_BAD_REQUEST) hass = request.app["hass"] response = await hass.async_add_job(self._get_log, hass, lines) diff --git a/homeassistant/components/free_mobile/notify.py b/homeassistant/components/free_mobile/notify.py index a2bee1f0037..a4351bfe678 100644 --- a/homeassistant/components/free_mobile/notify.py +++ b/homeassistant/components/free_mobile/notify.py @@ -8,6 +8,7 @@ from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationSer from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_USERNAME, + HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR, ) @@ -36,7 +37,7 @@ class FreeSMSNotificationService(BaseNotificationService): """Send a message to the Free Mobile user cell.""" resp = self.free_client.send_sms(message) - if resp.status_code == 400: + if resp.status_code == HTTP_BAD_REQUEST: _LOGGER.error("At least one parameter is missing") elif resp.status_code == 402: _LOGGER.error("Too much SMS send in a few time") diff --git a/homeassistant/components/hassio/addon_panel.py b/homeassistant/components/hassio/addon_panel.py index cb509cb19a1..d8616a82578 100644 --- a/homeassistant/components/hassio/addon_panel.py +++ b/homeassistant/components/hassio/addon_panel.py @@ -5,6 +5,7 @@ import logging from aiohttp import web from homeassistant.components.http import HomeAssistantView +from homeassistant.const import HTTP_BAD_REQUEST from homeassistant.helpers.typing import HomeAssistantType from .const import ATTR_ADMIN, ATTR_ENABLE, ATTR_ICON, ATTR_PANELS, ATTR_TITLE @@ -52,7 +53,7 @@ class HassIOAddonPanel(HomeAssistantView): # Panel exists for add-on slug if addon not in panels or not panels[addon][ATTR_ENABLE]: _LOGGER.error("Panel is not enable for %s", addon) - return web.Response(status=400) + return web.Response(status=HTTP_BAD_REQUEST) data = panels[addon] # Register panel diff --git a/homeassistant/components/hassio/handler.py b/homeassistant/components/hassio/handler.py index 91b36925542..d929f2d3e82 100644 --- a/homeassistant/components/hassio/handler.py +++ b/homeassistant/components/hassio/handler.py @@ -12,7 +12,7 @@ from homeassistant.components.http import ( CONF_SSL_CERTIFICATE, DEFAULT_SERVER_HOST, ) -from homeassistant.const import HTTP_OK, SERVER_PORT +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_OK, SERVER_PORT from .const import X_HASSIO @@ -167,7 +167,7 @@ class HassIO: headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")}, ) - if request.status not in (HTTP_OK, 400): + if request.status not in (HTTP_OK, HTTP_BAD_REQUEST): _LOGGER.error("%s return code %d.", command, request.status) raise HassioAPIError() diff --git a/homeassistant/components/http/ban.py b/homeassistant/components/http/ban.py index 7fffd19c467..8b8d2bc5671 100644 --- a/homeassistant/components/http/ban.py +++ b/homeassistant/components/http/ban.py @@ -10,6 +10,7 @@ from aiohttp.web_exceptions import HTTPForbidden, HTTPUnauthorized import voluptuous as vol from homeassistant.config import load_yaml_config_file +from homeassistant.const import HTTP_BAD_REQUEST from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv @@ -81,7 +82,7 @@ def log_invalid_auth(func): async def handle_req(view, request, *args, **kwargs): """Try to log failed login attempts if response status >= 400.""" resp = await func(view, request, *args, **kwargs) - if resp.status >= 400: + if resp.status >= HTTP_BAD_REQUEST: await process_wrong_login(request) return resp diff --git a/homeassistant/components/http/data_validator.py b/homeassistant/components/http/data_validator.py index 51b3b5617e4..84bdb4e1c17 100644 --- a/homeassistant/components/http/data_validator.py +++ b/homeassistant/components/http/data_validator.py @@ -4,6 +4,8 @@ import logging import voluptuous as vol +from homeassistant.const import HTTP_BAD_REQUEST + # mypy: allow-untyped-defs _LOGGER = logging.getLogger(__name__) @@ -38,14 +40,16 @@ class RequestDataValidator: except ValueError: if not self._allow_empty or (await request.content.read()) != b"": _LOGGER.error("Invalid JSON received.") - return view.json_message("Invalid JSON.", 400) + return view.json_message("Invalid JSON.", HTTP_BAD_REQUEST) data = {} try: kwargs["data"] = self._schema(data) except vol.Invalid as err: _LOGGER.error("Data does not match schema: %s", err) - return view.json_message(f"Message format incorrect: {err}", 400) + return view.json_message( + f"Message format incorrect: {err}", HTTP_BAD_REQUEST + ) result = await method(view, request, *args, **kwargs) return result diff --git a/homeassistant/components/logi_circle/config_flow.py b/homeassistant/components/logi_circle/config_flow.py index bc585153b64..527353eebf6 100644 --- a/homeassistant/components/logi_circle/config_flow.py +++ b/homeassistant/components/logi_circle/config_flow.py @@ -9,7 +9,7 @@ import voluptuous as vol from homeassistant import config_entries from homeassistant.components.http import HomeAssistantView -from homeassistant.const import CONF_SENSORS +from homeassistant.const import CONF_SENSORS, HTTP_BAD_REQUEST from homeassistant.core import callback from .const import ( @@ -207,5 +207,5 @@ class LogiCircleAuthCallbackView(HomeAssistantView): ) return self.json_message("Authorisation code saved") return self.json_message( - "Authorisation code missing from query string", status_code=400 + "Authorisation code missing from query string", status_code=HTTP_BAD_REQUEST ) diff --git a/homeassistant/components/mobile_app/helpers.py b/homeassistant/components/mobile_app/helpers.py index 7c7ceb3a827..b2cb3d22e4b 100644 --- a/homeassistant/components/mobile_app/helpers.py +++ b/homeassistant/components/mobile_app/helpers.py @@ -7,7 +7,7 @@ from aiohttp.web import Response, json_response from nacl.encoding import Base64Encoder from nacl.secret import SecretBox -from homeassistant.const import HTTP_OK +from homeassistant.const import HTTP_BAD_REQUEST, HTTP_OK from homeassistant.core import Context from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.typing import HomeAssistantType @@ -99,7 +99,7 @@ def empty_okay_response(headers: Dict = None, status: int = HTTP_OK) -> Response def error_response( - code: str, message: str, status: int = 400, headers: dict = None + code: str, message: str, status: int = HTTP_BAD_REQUEST, headers: dict = None ) -> Response: """Return an error Response.""" return json_response( diff --git a/homeassistant/components/nexia/__init__.py b/homeassistant/components/nexia/__init__.py index fd0b708576d..9a595ab7a94 100644 --- a/homeassistant/components/nexia/__init__.py +++ b/homeassistant/components/nexia/__init__.py @@ -9,7 +9,12 @@ from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR +from homeassistant.const import ( + CONF_PASSWORD, + CONF_USERNAME, + HTTP_BAD_REQUEST, + HTTP_INTERNAL_SERVER_ERROR, +) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady import homeassistant.helpers.config_validation as cv @@ -74,7 +79,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): raise ConfigEntryNotReady except HTTPError as http_ex: if ( - http_ex.response.status_code >= 400 + http_ex.response.status_code >= HTTP_BAD_REQUEST and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR ): _LOGGER.error( diff --git a/homeassistant/components/nexia/config_flow.py b/homeassistant/components/nexia/config_flow.py index 01d4dc406cf..d99be94aaf9 100644 --- a/homeassistant/components/nexia/config_flow.py +++ b/homeassistant/components/nexia/config_flow.py @@ -6,7 +6,12 @@ from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR +from homeassistant.const import ( + CONF_PASSWORD, + CONF_USERNAME, + HTTP_BAD_REQUEST, + HTTP_INTERNAL_SERVER_ERROR, +) from .const import DOMAIN # pylint:disable=unused-import @@ -35,7 +40,7 @@ async def validate_input(hass: core.HomeAssistant, data): except HTTPError as http_ex: _LOGGER.error("HTTP error from Nexia service: %s", http_ex) if ( - http_ex.response.status_code >= 400 + http_ex.response.status_code >= HTTP_BAD_REQUEST and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR ): raise InvalidAuth diff --git a/homeassistant/components/nuheat/__init__.py b/homeassistant/components/nuheat/__init__.py index 6b49a3b975b..4c7455be3c0 100644 --- a/homeassistant/components/nuheat/__init__.py +++ b/homeassistant/components/nuheat/__init__.py @@ -11,6 +11,7 @@ from homeassistant.const import ( CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME, + HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR, ) from homeassistant.core import HomeAssistant @@ -84,7 +85,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): raise ConfigEntryNotReady except requests.exceptions.HTTPError as ex: if ( - ex.response.status_code > 400 + ex.response.status_code > HTTP_BAD_REQUEST and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR ): _LOGGER.error("Failed to login to nuheat: %s", ex) diff --git a/homeassistant/components/nuheat/config_flow.py b/homeassistant/components/nuheat/config_flow.py index cf2f3398309..bdbdfe22ea3 100644 --- a/homeassistant/components/nuheat/config_flow.py +++ b/homeassistant/components/nuheat/config_flow.py @@ -6,7 +6,12 @@ import requests.exceptions import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR +from homeassistant.const import ( + CONF_PASSWORD, + CONF_USERNAME, + HTTP_BAD_REQUEST, + HTTP_INTERNAL_SERVER_ERROR, +) from .const import CONF_SERIAL_NUMBER from .const import DOMAIN # pylint:disable=unused-import @@ -35,7 +40,7 @@ async def validate_input(hass: core.HomeAssistant, data): raise CannotConnect except requests.exceptions.HTTPError as ex: if ( - ex.response.status_code > 400 + ex.response.status_code > HTTP_BAD_REQUEST and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR ): raise InvalidAuth diff --git a/homeassistant/components/rest/notify.py b/homeassistant/components/rest/notify.py index 60b000eae1e..9860334afbf 100644 --- a/homeassistant/components/rest/notify.py +++ b/homeassistant/components/rest/notify.py @@ -21,6 +21,7 @@ from homeassistant.const import ( CONF_RESOURCE, CONF_USERNAME, CONF_VERIFY_SSL, + HTTP_BAD_REQUEST, HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, HTTP_INTERNAL_SERVER_ERROR, @@ -197,7 +198,7 @@ class RestNotificationService(BaseNotificationService): "Server error. Response %d: %s:", response.status_code, response.reason ) elif ( - response.status_code >= 400 + response.status_code >= HTTP_BAD_REQUEST and response.status_code < HTTP_INTERNAL_SERVER_ERROR ): _LOGGER.exception( diff --git a/homeassistant/components/rest/switch.py b/homeassistant/components/rest/switch.py index 71df1852e7a..84d503bb09e 100644 --- a/homeassistant/components/rest/switch.py +++ b/homeassistant/components/rest/switch.py @@ -16,6 +16,7 @@ from homeassistant.const import ( CONF_TIMEOUT, CONF_USERNAME, CONF_VERIFY_SSL, + HTTP_BAD_REQUEST, HTTP_OK, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -95,7 +96,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= ) req = await switch.get_device_state(hass) - if req.status >= 400: + if req.status >= HTTP_BAD_REQUEST: _LOGGER.error("Got non-ok response from resource: %s", req.status) else: async_add_entities([switch]) diff --git a/homeassistant/components/rest_command/__init__.py b/homeassistant/components/rest_command/__init__.py index bb2ede6d555..dc7337c7569 100644 --- a/homeassistant/components/rest_command/__init__.py +++ b/homeassistant/components/rest_command/__init__.py @@ -15,6 +15,7 @@ from homeassistant.const import ( CONF_URL, CONF_USERNAME, CONF_VERIFY_SSL, + HTTP_BAD_REQUEST, ) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -119,7 +120,7 @@ async def async_setup(hass, config): timeout=timeout, ) as response: - if response.status < 400: + if response.status < HTTP_BAD_REQUEST: _LOGGER.debug( "Success. Url: %s. Status code: %d.", response.url, diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index 6eeab8d6b1e..1946207337b 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -22,7 +22,13 @@ from homeassistant.components.media_player.const import ( MEDIA_TYPE_MUSIC, SERVICE_PLAY_MEDIA, ) -from homeassistant.const import ATTR_ENTITY_ID, CONF_PLATFORM, HTTP_NOT_FOUND, HTTP_OK +from homeassistant.const import ( + ATTR_ENTITY_ID, + CONF_PLATFORM, + HTTP_BAD_REQUEST, + HTTP_NOT_FOUND, + HTTP_OK, +) from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform, discovery @@ -529,9 +535,11 @@ class TextToSpeechUrlView(HomeAssistantView): try: data = await request.json() except ValueError: - return self.json_message("Invalid JSON specified", 400) + return self.json_message("Invalid JSON specified", HTTP_BAD_REQUEST) if not data.get(ATTR_PLATFORM) and data.get(ATTR_MESSAGE): - return self.json_message("Must specify platform and message", 400) + return self.json_message( + "Must specify platform and message", HTTP_BAD_REQUEST + ) p_type = data[ATTR_PLATFORM] message = data[ATTR_MESSAGE] @@ -546,7 +554,7 @@ class TextToSpeechUrlView(HomeAssistantView): resp = self.json({"url": url}, HTTP_OK) except HomeAssistantError as err: _LOGGER.error("Error on init tts: %s", err) - resp = self.json({"error": err}, 400) + resp = self.json({"error": err}, HTTP_BAD_REQUEST) return resp diff --git a/homeassistant/components/xmpp/notify.py b/homeassistant/components/xmpp/notify.py index 28d42698657..0aba4a8bd15 100644 --- a/homeassistant/components/xmpp/notify.py +++ b/homeassistant/components/xmpp/notify.py @@ -29,6 +29,7 @@ from homeassistant.const import ( CONF_RESOURCE, CONF_ROOM, CONF_SENDER, + HTTP_BAD_REQUEST, ) import homeassistant.helpers.config_validation as cv import homeassistant.helpers.template as template_helper @@ -262,7 +263,7 @@ async def async_send_message( result = await hass.async_add_executor_job(get_url, url) - if result.status_code >= 400: + if result.status_code >= HTTP_BAD_REQUEST: _LOGGER.error("Could not load file from %s", url) return None