From 8d61893c395a5841f06838a7117c6d74dc99f30f Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Wed, 8 Apr 2020 18:47:38 +0200 Subject: [PATCH] Use HTTP_OK constant (#33798) * Use http ok constant * Remove incorrect use * Run isort * Fix pylint by adding missing imports * Fix pylint by fixing one import --- homeassistant/components/aftership/sensor.py | 6 +++--- homeassistant/components/alexa/auth.py | 3 ++- homeassistant/components/api/__init__.py | 3 ++- homeassistant/components/arest/binary_sensor.py | 10 ++++++++-- homeassistant/components/arest/sensor.py | 3 ++- homeassistant/components/arest/switch.py | 14 +++++++------- homeassistant/components/auth/__init__.py | 7 ++++--- homeassistant/components/bloomsky/__init__.py | 4 ++-- homeassistant/components/bluesound/media_player.py | 5 +++-- homeassistant/components/buienradar/util.py | 4 ++-- homeassistant/components/clickatell/notify.py | 4 ++-- homeassistant/components/clicksend/notify.py | 5 +++-- homeassistant/components/clicksend_tts/notify.py | 5 +++-- homeassistant/components/cloud/client.py | 3 ++- homeassistant/components/cloud/google_config.py | 4 ++-- homeassistant/components/cloud/http_api.py | 3 ++- homeassistant/components/ddwrt/device_tracker.py | 3 ++- homeassistant/components/doorbird/__init__.py | 7 ++++--- homeassistant/components/downloader/__init__.py | 3 ++- .../components/dte_energy_bridge/sensor.py | 4 ++-- .../components/dublin_bus_transport/sensor.py | 4 ++-- homeassistant/components/emoncms/sensor.py | 3 ++- .../components/emoncms_history/__init__.py | 3 ++- homeassistant/components/facebook/notify.py | 4 ++-- homeassistant/components/flock/notify.py | 4 ++-- homeassistant/components/foursquare/__init__.py | 4 ++-- homeassistant/components/google_translate/tts.py | 3 ++- homeassistant/components/hangouts/hangouts_bot.py | 3 ++- homeassistant/components/hassio/auth.py | 5 +++-- homeassistant/components/hassio/handler.py | 4 ++-- homeassistant/components/haveibeenpwned/sensor.py | 4 ++-- .../components/hitron_coda/device_tracker.py | 12 +++++++++--- homeassistant/components/http/view.py | 10 ++++++---- homeassistant/components/ifttt/__init__.py | 4 ++-- homeassistant/components/lifx_cloud/scene.py | 4 ++-- .../components/linksys_smart/device_tracker.py | 6 +++--- .../components/llamalab_automate/notify.py | 4 ++-- homeassistant/components/lockitron/lock.py | 8 ++++---- homeassistant/components/london_air/sensor.py | 3 ++- homeassistant/components/media_player/__init__.py | 9 +++++---- homeassistant/components/mobile_app/helpers.py | 5 +++-- homeassistant/components/mobile_app/notify.py | 3 ++- homeassistant/components/nfandroidtv/notify.py | 4 ++-- homeassistant/components/nissan_leaf/__init__.py | 4 ++-- .../components/openalpr_cloud/image_processing.py | 4 ++-- .../components/openexchangerates/sensor.py | 3 ++- homeassistant/components/prowl/notify.py | 4 ++-- homeassistant/components/pushsafer/notify.py | 3 ++- homeassistant/components/rachio/config_flow.py | 6 +++--- homeassistant/components/rachio/device.py | 6 +++--- homeassistant/components/radarr/sensor.py | 3 ++- homeassistant/components/rest/notify.py | 3 ++- homeassistant/components/rest/switch.py | 5 +++-- homeassistant/components/rocketchat/notify.py | 10 ++++++++-- homeassistant/components/route53/__init__.py | 4 ++-- .../components/rss_feed_template/__init__.py | 5 ++++- homeassistant/components/sigfox/sensor.py | 4 ++-- homeassistant/components/sky_hub/device_tracker.py | 4 ++-- homeassistant/components/sonarr/sensor.py | 3 ++- .../components/squeezebox/media_player.py | 3 ++- homeassistant/components/startca/sensor.py | 3 ++- homeassistant/components/synology_chat/notify.py | 4 ++-- homeassistant/components/tado/device_tracker.py | 4 ++-- homeassistant/components/teksavvy/sensor.py | 3 ++- homeassistant/components/tomato/device_tracker.py | 3 ++- homeassistant/components/traccar/__init__.py | 2 +- homeassistant/components/tts/__init__.py | 6 +++--- homeassistant/components/twitter/notify.py | 10 +++++----- homeassistant/components/ubus/device_tracker.py | 4 ++-- homeassistant/components/uk_transport/sensor.py | 4 ++-- homeassistant/components/viaggiatreno/sensor.py | 4 ++-- homeassistant/components/voicerss/tts.py | 4 ++-- homeassistant/components/volumio/media_player.py | 3 ++- homeassistant/components/webhook/__init__.py | 7 ++++--- homeassistant/components/wsdot/sensor.py | 3 ++- homeassistant/components/xiaomi/device_tracker.py | 6 +++--- homeassistant/components/yandextts/tts.py | 4 ++-- homeassistant/components/yr/sensor.py | 3 ++- homeassistant/util/aiohttp.py | 4 +++- 79 files changed, 214 insertions(+), 154 deletions(-) diff --git a/homeassistant/components/aftership/sensor.py b/homeassistant/components/aftership/sensor.py index 9e0d8939da4..83ab52499da 100644 --- a/homeassistant/components/aftership/sensor.py +++ b/homeassistant/components/aftership/sensor.py @@ -6,7 +6,7 @@ from pyaftership.tracker import Tracking import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME +from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_NAME, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send @@ -66,7 +66,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= await aftership.get_trackings() - if not aftership.meta or aftership.meta["code"] != 200: + if not aftership.meta or aftership.meta["code"] != HTTP_OK: _LOGGER.error( "No tracking data found. Check API key is correct: %s", aftership.meta ) @@ -164,7 +164,7 @@ class AfterShipSensor(Entity): if not self.aftership.meta: _LOGGER.error("Unknown errors when querying") return - if self.aftership.meta["code"] != 200: + if self.aftership.meta["code"] != HTTP_OK: _LOGGER.error( "Errors when querying AfterShip. %s", str(self.aftership.meta) ) diff --git a/homeassistant/components/alexa/auth.py b/homeassistant/components/alexa/auth.py index 94789c33305..3b7984f56d3 100644 --- a/homeassistant/components/alexa/auth.py +++ b/homeassistant/components/alexa/auth.py @@ -7,6 +7,7 @@ import logging import aiohttp import async_timeout +from homeassistant.const import HTTP_OK from homeassistant.core import callback from homeassistant.helpers import aiohttp_client from homeassistant.util import dt @@ -118,7 +119,7 @@ class Auth: _LOGGER.debug("LWA response header: %s", response.headers) _LOGGER.debug("LWA response status: %s", response.status) - if response.status != 200: + if response.status != HTTP_OK: _LOGGER.error("Error calling LWA to get auth token.") return None diff --git a/homeassistant/components/api/__init__.py b/homeassistant/components/api/__init__.py index e11bc5e61f9..8d0cd44070c 100644 --- a/homeassistant/components/api/__init__.py +++ b/homeassistant/components/api/__init__.py @@ -17,6 +17,7 @@ from homeassistant.const import ( HTTP_BAD_REQUEST, HTTP_CREATED, HTTP_NOT_FOUND, + HTTP_OK, MATCH_ALL, URL_API, URL_API_COMPONENTS, @@ -250,7 +251,7 @@ class APIEntityStateView(HomeAssistantView): ) # Read the state back for our response - status_code = HTTP_CREATED if is_new_state else 200 + status_code = HTTP_CREATED if is_new_state else HTTP_OK resp = self.json(hass.states.get(entity_id), status_code) resp.headers.add("Location", f"/api/states/{entity_id}") diff --git a/homeassistant/components/arest/binary_sensor.py b/homeassistant/components/arest/binary_sensor.py index d84b79f1d4c..1b914f80aa7 100644 --- a/homeassistant/components/arest/binary_sensor.py +++ b/homeassistant/components/arest/binary_sensor.py @@ -10,7 +10,13 @@ from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDevice, ) -from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME, CONF_PIN, CONF_RESOURCE +from homeassistant.const import ( + CONF_DEVICE_CLASS, + CONF_NAME, + CONF_PIN, + CONF_RESOURCE, + HTTP_OK, +) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle @@ -74,7 +80,7 @@ class ArestBinarySensor(BinarySensorDevice): if self._pin is not None: request = requests.get(f"{self._resource}/mode/{self._pin}/i", timeout=10) - if request.status_code != 200: + if request.status_code != HTTP_OK: _LOGGER.error("Can't set mode of %s", self._resource) @property diff --git a/homeassistant/components/arest/sensor.py b/homeassistant/components/arest/sensor.py index b118422ef8c..638c0e2557a 100644 --- a/homeassistant/components/arest/sensor.py +++ b/homeassistant/components/arest/sensor.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONF_RESOURCE, CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE, + HTTP_OK, ) from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv @@ -149,7 +150,7 @@ class ArestSensor(Entity): if self._pin is not None: request = requests.get(f"{self._resource}/mode/{self._pin}/i", timeout=10) - if request.status_code != 200: + if request.status_code != HTTP_OK: _LOGGER.error("Can't set mode of %s", self._resource) @property diff --git a/homeassistant/components/arest/switch.py b/homeassistant/components/arest/switch.py index 298ac106dec..875211f5f0b 100644 --- a/homeassistant/components/arest/switch.py +++ b/homeassistant/components/arest/switch.py @@ -6,7 +6,7 @@ import requests import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice -from homeassistant.const import CONF_NAME, CONF_RESOURCE +from homeassistant.const import CONF_NAME, CONF_RESOURCE, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -116,7 +116,7 @@ class ArestSwitchFunction(ArestSwitchBase): request = requests.get(f"{self._resource}/{self._func}", timeout=10) - if request.status_code != 200: + if request.status_code != HTTP_OK: _LOGGER.error("Can't find function") return @@ -133,7 +133,7 @@ class ArestSwitchFunction(ArestSwitchBase): f"{self._resource}/{self._func}", timeout=10, params={"params": "1"} ) - if request.status_code == 200: + if request.status_code == HTTP_OK: self._state = True else: _LOGGER.error("Can't turn on function %s at %s", self._func, self._resource) @@ -144,7 +144,7 @@ class ArestSwitchFunction(ArestSwitchBase): f"{self._resource}/{self._func}", timeout=10, params={"params": "0"} ) - if request.status_code == 200: + if request.status_code == HTTP_OK: self._state = False else: _LOGGER.error( @@ -172,7 +172,7 @@ class ArestSwitchPin(ArestSwitchBase): self.invert = invert request = requests.get(f"{self._resource}/mode/{self._pin}/o", timeout=10) - if request.status_code != 200: + if request.status_code != HTTP_OK: _LOGGER.error("Can't set mode") self._available = False @@ -182,7 +182,7 @@ class ArestSwitchPin(ArestSwitchBase): request = requests.get( f"{self._resource}/digital/{self._pin}/{turn_on_payload}", timeout=10 ) - if request.status_code == 200: + if request.status_code == HTTP_OK: self._state = True else: _LOGGER.error("Can't turn on pin %s at %s", self._pin, self._resource) @@ -193,7 +193,7 @@ class ArestSwitchPin(ArestSwitchBase): request = requests.get( f"{self._resource}/digital/{self._pin}/{turn_off_payload}", timeout=10 ) - if request.status_code == 200: + if request.status_code == HTTP_OK: self._state = False else: _LOGGER.error("Can't turn off pin %s at %s", self._pin, self._resource) diff --git a/homeassistant/components/auth/__init__.py b/homeassistant/components/auth/__init__.py index 888ef98a582..6733361f5c3 100644 --- a/homeassistant/components/auth/__init__.py +++ b/homeassistant/components/auth/__init__.py @@ -132,6 +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_OK from homeassistant.core import HomeAssistant, callback from homeassistant.loader import bind_hass from homeassistant.util import dt as dt_util @@ -271,15 +272,15 @@ class TokenView(HomeAssistantView): token = data.get("token") if token is None: - return web.Response(status=200) + return web.Response(status=HTTP_OK) refresh_token = await hass.auth.async_get_refresh_token_by_token(token) if refresh_token is None: - return web.Response(status=200) + return web.Response(status=HTTP_OK) await hass.auth.async_remove_refresh_token(refresh_token) - return web.Response(status=200) + return web.Response(status=HTTP_OK) async def _async_handle_auth_code(self, hass, data, remote_addr): """Handle authorization code request.""" diff --git a/homeassistant/components/bloomsky/__init__.py b/homeassistant/components/bloomsky/__init__.py index ba10c5c7413..929f8218144 100644 --- a/homeassistant/components/bloomsky/__init__.py +++ b/homeassistant/components/bloomsky/__init__.py @@ -6,7 +6,7 @@ from aiohttp.hdrs import AUTHORIZATION import requests import voluptuous as vol -from homeassistant.const import CONF_API_KEY +from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle @@ -72,7 +72,7 @@ class BloomSky: if response.status_code == 405: _LOGGER.error("You have no bloomsky devices configured") return - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.error("Invalid HTTP response: %s", response.status_code) return # Create dictionary keyed off of the device unique id diff --git a/homeassistant/components/bluesound/media_player.py b/homeassistant/components/bluesound/media_player.py index a0f1d38ba77..eb1ce5f30dc 100644 --- a/homeassistant/components/bluesound/media_player.py +++ b/homeassistant/components/bluesound/media_player.py @@ -38,6 +38,7 @@ from homeassistant.const import ( CONF_PORT, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, + HTTP_OK, STATE_IDLE, STATE_OFF, STATE_PAUSED, @@ -354,7 +355,7 @@ class BluesoundPlayer(MediaPlayerDevice): with async_timeout.timeout(10): response = await websession.get(url) - if response.status == 200: + if response.status == HTTP_OK: result = await response.text() if result: data = xmltodict.parse(result) @@ -398,7 +399,7 @@ class BluesoundPlayer(MediaPlayerDevice): url, headers={CONNECTION: KEEP_ALIVE} ) - if response.status == 200: + if response.status == HTTP_OK: result = await response.text() self._is_online = True self._last_status_update = dt_util.utcnow() diff --git a/homeassistant/components/buienradar/util.py b/homeassistant/components/buienradar/util.py index 900b1caaf97..4c69678d215 100644 --- a/homeassistant/components/buienradar/util.py +++ b/homeassistant/components/buienradar/util.py @@ -25,7 +25,7 @@ from buienradar.constants import ( ) from buienradar.urls import JSON_FEED_URL, json_precipitation_forecast_url -from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE +from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util import dt as dt_util @@ -92,7 +92,7 @@ class BrData: result[STATUS_CODE] = resp.status result[CONTENT] = await resp.text() - if resp.status == 200: + if resp.status == HTTP_OK: result[SUCCESS] = True else: result[MESSAGE] = "Got http statuscode: %d" % (resp.status) diff --git a/homeassistant/components/clickatell/notify.py b/homeassistant/components/clickatell/notify.py index d59a553a4f6..f1a27be83b9 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 +from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT, 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 != 200) or (resp.status_code != 201): + if (resp.status_code != HTTP_OK) or (resp.status_code != 201): _LOGGER.error("Error %s : %s", resp.status_code, resp.text) diff --git a/homeassistant/components/clicksend/notify.py b/homeassistant/components/clicksend/notify.py index 42136e9a09c..18562260431 100644 --- a/homeassistant/components/clicksend/notify.py +++ b/homeassistant/components/clicksend/notify.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_SENDER, CONF_USERNAME, CONTENT_TYPE_JSON, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv @@ -80,7 +81,7 @@ class ClicksendNotificationService(BaseNotificationService): auth=(self.username, self.api_key), timeout=TIMEOUT, ) - if resp.status_code == 200: + if resp.status_code == HTTP_OK: return obj = json.loads(resp.text) @@ -100,6 +101,6 @@ def _authenticate(config): auth=(config[CONF_USERNAME], config[CONF_API_KEY]), timeout=TIMEOUT, ) - if resp.status_code != 200: + if resp.status_code != HTTP_OK: return False return True diff --git a/homeassistant/components/clicksend_tts/notify.py b/homeassistant/components/clicksend_tts/notify.py index 400e72a7d0c..0847f3fb907 100644 --- a/homeassistant/components/clicksend_tts/notify.py +++ b/homeassistant/components/clicksend_tts/notify.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONF_RECIPIENT, CONF_USERNAME, CONTENT_TYPE_JSON, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv @@ -87,7 +88,7 @@ class ClicksendNotificationService(BaseNotificationService): timeout=TIMEOUT, ) - if resp.status_code == 200: + if resp.status_code == HTTP_OK: return obj = json.loads(resp.text) response_msg = obj["response_msg"] @@ -107,7 +108,7 @@ def _authenticate(config): timeout=TIMEOUT, ) - if resp.status_code != 200: + if resp.status_code != HTTP_OK: return False return True diff --git a/homeassistant/components/cloud/client.py b/homeassistant/components/cloud/client.py index ef73d4356d5..a17f536db72 100644 --- a/homeassistant/components/cloud/client.py +++ b/homeassistant/components/cloud/client.py @@ -12,6 +12,7 @@ from homeassistant.components.alexa import ( smart_home as alexa_sh, ) from homeassistant.components.google_assistant import const as gc, smart_home as ga +from homeassistant.const import HTTP_OK from homeassistant.core import Context, callback from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType @@ -174,7 +175,7 @@ class CloudClient(Interface): break if found is None: - return {"status": 200} + return {"status": HTTP_OK} request = MockRequest( content=payload["body"].encode("utf-8"), diff --git a/homeassistant/components/cloud/google_config.py b/homeassistant/components/cloud/google_config.py index 1074aaa68b3..8420a1bea7e 100644 --- a/homeassistant/components/cloud/google_config.py +++ b/homeassistant/components/cloud/google_config.py @@ -6,7 +6,7 @@ from hass_nabucasa import cloud_api from hass_nabucasa.google_report_state import ErrorResponse from homeassistant.components.google_assistant.helpers import AbstractConfig -from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES +from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES, HTTP_OK from homeassistant.helpers import entity_registry from .const import ( @@ -124,7 +124,7 @@ class CloudGoogleConfig(AbstractConfig): async def _async_request_sync_devices(self, agent_user_id: str): """Trigger a sync with Google.""" if self._sync_entities_lock.locked(): - return 200 + return HTTP_OK async with self._sync_entities_lock: resp = await cloud_api.async_google_actions_request_sync(self._cloud) diff --git a/homeassistant/components/cloud/http_api.py b/homeassistant/components/cloud/http_api.py index c532a2063a7..09dae3efc24 100644 --- a/homeassistant/components/cloud/http_api.py +++ b/homeassistant/components/cloud/http_api.py @@ -19,6 +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_OK from homeassistant.core import callback from .const import ( @@ -321,7 +322,7 @@ async def websocket_subscription(hass, connection, msg): with async_timeout.timeout(REQUEST_TIMEOUT): response = await cloud.fetch_subscription_info() - if response.status != 200: + if response.status != HTTP_OK: connection.send_message( websocket_api.error_message( msg["id"], "request_failed", "Failed to request subscription" diff --git a/homeassistant/components/ddwrt/device_tracker.py b/homeassistant/components/ddwrt/device_tracker.py index a6bdb9c527b..27f6895fc43 100644 --- a/homeassistant/components/ddwrt/device_tracker.py +++ b/homeassistant/components/ddwrt/device_tracker.py @@ -16,6 +16,7 @@ from homeassistant.const import ( CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv @@ -152,7 +153,7 @@ class DdWrtDeviceScanner(DeviceScanner): except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out") return - if response.status_code == 200: + if response.status_code == HTTP_OK: return _parse_ddwrt_response(response.text) if response.status_code == 401: # Authentication error diff --git a/homeassistant/components/doorbird/__init__.py b/homeassistant/components/doorbird/__init__.py index bbbaa3d340c..b70b0a3061c 100644 --- a/homeassistant/components/doorbird/__init__.py +++ b/homeassistant/components/doorbird/__init__.py @@ -18,6 +18,7 @@ from homeassistant.const import ( CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME, + HTTP_OK, ) from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady @@ -71,7 +72,7 @@ async def async_setup(hass: HomeAssistant, config: dict): hass.async_create_task( hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_IMPORT}, data=doorstation_config, + DOMAIN, context={"source": SOURCE_IMPORT}, data=doorstation_config ) ) @@ -359,10 +360,10 @@ class DoorBirdRequestView(HomeAssistantView): hass.bus.async_fire(RESET_DEVICE_FAVORITES, {"token": token}) message = f"HTTP Favorites cleared for {device.slug}" - return web.Response(status=200, text=message) + return web.Response(status=HTTP_OK, text=message) hass.bus.async_fire(f"{DOMAIN}_{event}", event_data) log_entry(hass, f"Doorbird {event}", "event was fired.", DOMAIN) - return web.Response(status=200, text="OK") + return web.Response(status=HTTP_OK, text="OK") diff --git a/homeassistant/components/downloader/__init__.py b/homeassistant/components/downloader/__init__.py index 9054943ca52..0c87f04e3ab 100644 --- a/homeassistant/components/downloader/__init__.py +++ b/homeassistant/components/downloader/__init__.py @@ -7,6 +7,7 @@ import threading import requests import voluptuous as vol +from homeassistant.const import HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.util import sanitize_filename @@ -76,7 +77,7 @@ def setup(hass, config): req = requests.get(url, stream=True, timeout=10) - if req.status_code != 200: + if req.status_code != HTTP_OK: _LOGGER.warning( "downloading '%s' failed, status_code=%d", url, req.status_code ) diff --git a/homeassistant/components/dte_energy_bridge/sensor.py b/homeassistant/components/dte_energy_bridge/sensor.py index 826f9cf5acb..c0725219a9a 100644 --- a/homeassistant/components/dte_energy_bridge/sensor.py +++ b/homeassistant/components/dte_energy_bridge/sensor.py @@ -5,7 +5,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_NAME +from homeassistant.const import CONF_NAME, HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -85,7 +85,7 @@ class DteEnergyBridgeSensor(Entity): ) return - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.warning( "Invalid status_code from DTE Energy Bridge: %s (%s)", response.status_code, diff --git a/homeassistant/components/dublin_bus_transport/sensor.py b/homeassistant/components/dublin_bus_transport/sensor.py index e75775bf75f..41c7df7889e 100644 --- a/homeassistant/components/dublin_bus_transport/sensor.py +++ b/homeassistant/components/dublin_bus_transport/sensor.py @@ -11,7 +11,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, TIME_MINUTES +from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, HTTP_OK, TIME_MINUTES import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util @@ -148,7 +148,7 @@ class PublicTransportData: response = requests.get(_RESOURCE, params, timeout=10) - if response.status_code != 200: + if response.status_code != HTTP_OK: self.info = [ {ATTR_DUE_AT: "n/a", ATTR_ROUTE: self.route, ATTR_DUE_IN: "n/a"} ] diff --git a/homeassistant/components/emoncms/sensor.py b/homeassistant/components/emoncms/sensor.py index c0754405840..dca9c870022 100644 --- a/homeassistant/components/emoncms/sensor.py +++ b/homeassistant/components/emoncms/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_UNIT_OF_MEASUREMENT, CONF_URL, CONF_VALUE_TEMPLATE, + HTTP_OK, POWER_WATT, STATE_UNKNOWN, ) @@ -245,7 +246,7 @@ class EmonCmsData: _LOGGER.error(exception) return else: - if req.status_code == 200: + if req.status_code == HTTP_OK: self.data = req.json() else: _LOGGER.error( diff --git a/homeassistant/components/emoncms_history/__init__.py b/homeassistant/components/emoncms_history/__init__.py index fd38da1cac1..85b48c55755 100644 --- a/homeassistant/components/emoncms_history/__init__.py +++ b/homeassistant/components/emoncms_history/__init__.py @@ -10,6 +10,7 @@ from homeassistant.const import ( CONF_SCAN_INTERVAL, CONF_URL, CONF_WHITELIST, + HTTP_OK, STATE_UNAVAILABLE, STATE_UNKNOWN, ) @@ -58,7 +59,7 @@ def setup(hass, config): _LOGGER.error("Error saving data '%s' to '%s'", payload, fullurl) else: - if req.status_code != 200: + if req.status_code != HTTP_OK: _LOGGER.error( "Error saving data %s to %s (http status code = %d)", payload, diff --git a/homeassistant/components/facebook/notify.py b/homeassistant/components/facebook/notify.py index 34d5b14cf25..0ce2fbfc665 100644 --- a/homeassistant/components/facebook/notify.py +++ b/homeassistant/components/facebook/notify.py @@ -12,7 +12,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONTENT_TYPE_JSON +from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -76,7 +76,7 @@ class FacebookNotificationService(BaseNotificationService): headers={CONTENT_TYPE: CONTENT_TYPE_JSON}, timeout=10, ) - if resp.status_code != 200: + if resp.status_code != HTTP_OK: log_error(resp) diff --git a/homeassistant/components/flock/notify.py b/homeassistant/components/flock/notify.py index 107c837970d..7bdd1b33c5b 100644 --- a/homeassistant/components/flock/notify.py +++ b/homeassistant/components/flock/notify.py @@ -6,7 +6,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService -from homeassistant.const import CONF_ACCESS_TOKEN +from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -44,7 +44,7 @@ class FlockNotificationService(BaseNotificationService): response = await self._session.post(self._url, json=payload) result = await response.json() - if response.status != 200 or "error" in result: + if response.status != HTTP_OK or "error" in result: _LOGGER.error( "Flock service returned HTTP status %d, response %s", response.status, diff --git a/homeassistant/components/foursquare/__init__.py b/homeassistant/components/foursquare/__init__.py index 07d177ebf30..bae0336a63e 100644 --- a/homeassistant/components/foursquare/__init__.py +++ b/homeassistant/components/foursquare/__init__.py @@ -5,7 +5,7 @@ import requests import voluptuous as vol from homeassistant.components.http import HomeAssistantView -from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_BAD_REQUEST +from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_BAD_REQUEST, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -55,7 +55,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 (200, 201): + if response.status_code not in (HTTP_OK, 201): _LOGGER.exception( "Error checking in user. Response %d: %s:", response.status_code, diff --git a/homeassistant/components/google_translate/tts.py b/homeassistant/components/google_translate/tts.py index e35a229ab98..36543e0515e 100644 --- a/homeassistant/components/google_translate/tts.py +++ b/homeassistant/components/google_translate/tts.py @@ -11,6 +11,7 @@ import voluptuous as vol import yarl from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider +from homeassistant.const import HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOGGER = logging.getLogger(__name__) @@ -142,7 +143,7 @@ class GoogleProvider(Provider): GOOGLE_SPEECH_URL, params=url_param, headers=self.headers ) - if request.status != 200: + if request.status != HTTP_OK: _LOGGER.error( "Error %d on load URL %s", request.status, request.url ) diff --git a/homeassistant/components/hangouts/hangouts_bot.py b/homeassistant/components/hangouts/hangouts_bot.py index b3dfdecac2a..56045f0eb1c 100644 --- a/homeassistant/components/hangouts/hangouts_bot.py +++ b/homeassistant/components/hangouts/hangouts_bot.py @@ -7,6 +7,7 @@ import aiohttp import hangups from hangups import ChatMessageEvent, ChatMessageSegment, Client, get_auth, hangouts_pb2 +from homeassistant.const import HTTP_OK from homeassistant.core import callback from homeassistant.helpers import dispatcher, intent from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -273,7 +274,7 @@ class HangoutsBot: try: websession = async_get_clientsession(self.hass) async with websession.get(uri, timeout=5) as response: - if response.status != 200: + if response.status != HTTP_OK: _LOGGER.error( "Fetch image failed, %s, %s", response.status, response ) diff --git a/homeassistant/components/hassio/auth.py b/homeassistant/components/hassio/auth.py index f8474e0fd24..b95690641cd 100644 --- a/homeassistant/components/hassio/auth.py +++ b/homeassistant/components/hassio/auth.py @@ -15,6 +15,7 @@ from homeassistant.auth.models import User from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.const import KEY_HASS_USER, KEY_REAL_IP from homeassistant.components.http.data_validator import RequestDataValidator +from homeassistant.const import HTTP_OK from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv @@ -93,7 +94,7 @@ class HassIOAuth(HassIOBaseAuth): self._check_access(request) await self._check_login(data[ATTR_USERNAME], data[ATTR_PASSWORD]) - return web.Response(status=200) + return web.Response(status=HTTP_OK) async def _check_login(self, username, password): """Check User credentials.""" @@ -117,7 +118,7 @@ class HassIOPasswordReset(HassIOBaseAuth): self._check_access(request) await self._change_password(data[ATTR_USERNAME], data[ATTR_PASSWORD]) - return web.Response(status=200) + return web.Response(status=HTTP_OK) async def _change_password(self, username, password): """Check User credentials.""" diff --git a/homeassistant/components/hassio/handler.py b/homeassistant/components/hassio/handler.py index bb41e5335d7..91b36925542 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 SERVER_PORT +from homeassistant.const import 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 (200, 400): + if request.status not in (HTTP_OK, 400): _LOGGER.error("%s return code %d.", command, request.status) raise HassioAPIError() diff --git a/homeassistant/components/haveibeenpwned/sensor.py b/homeassistant/components/haveibeenpwned/sensor.py index 00a39aae8f4..51b06917142 100644 --- a/homeassistant/components/haveibeenpwned/sensor.py +++ b/homeassistant/components/haveibeenpwned/sensor.py @@ -7,7 +7,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_EMAIL +from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY, CONF_EMAIL, HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import track_point_in_time @@ -158,7 +158,7 @@ class HaveIBeenPwnedData: _LOGGER.error("Failed fetching data for %s", self._email) return - if req.status_code == 200: + if req.status_code == HTTP_OK: self.data[self._email] = sorted( req.json(), key=lambda k: k["AddedDate"], reverse=True ) diff --git a/homeassistant/components/hitron_coda/device_tracker.py b/homeassistant/components/hitron_coda/device_tracker.py index 12b03acbcc5..a49e3cc6d21 100644 --- a/homeassistant/components/hitron_coda/device_tracker.py +++ b/homeassistant/components/hitron_coda/device_tracker.py @@ -10,7 +10,13 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_TYPE, CONF_USERNAME +from homeassistant.const import ( + CONF_HOST, + CONF_PASSWORD, + CONF_TYPE, + CONF_USERNAME, + HTTP_OK, +) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -83,7 +89,7 @@ class HitronCODADeviceScanner(DeviceScanner): except requests.exceptions.Timeout: _LOGGER.error("Connection to the router timed out at URL %s", self._url) return False - if res.status_code != 200: + if res.status_code != HTTP_OK: _LOGGER.error("Connection failed with http code %s", res.status_code) return False try: @@ -109,7 +115,7 @@ class HitronCODADeviceScanner(DeviceScanner): except requests.exceptions.Timeout: _LOGGER.error("Connection to the router timed out at URL %s", self._url) return False - if res.status_code != 200: + if res.status_code != HTTP_OK: _LOGGER.error("Connection failed with http code %s", res.status_code) return False try: diff --git a/homeassistant/components/http/view.py b/homeassistant/components/http/view.py index bb7c5816c77..40ca43ff695 100644 --- a/homeassistant/components/http/view.py +++ b/homeassistant/components/http/view.py @@ -13,7 +13,7 @@ from aiohttp.web_exceptions import ( import voluptuous as vol from homeassistant import exceptions -from homeassistant.const import CONTENT_TYPE_JSON +from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK from homeassistant.core import Context, is_callback from homeassistant.helpers.json import JSONEncoder @@ -44,7 +44,7 @@ class HomeAssistantView: return Context(user_id=user.id) @staticmethod - def json(result, status_code=200, headers=None): + def json(result, status_code=HTTP_OK, headers=None): """Return a JSON response.""" try: msg = json.dumps( @@ -62,7 +62,9 @@ class HomeAssistantView: response.enable_compression() return response - def json_message(self, message, status_code=200, message_code=None, headers=None): + def json_message( + self, message, status_code=HTTP_OK, message_code=None, headers=None + ): """Return a JSON message response.""" data = {"message": message} if message_code is not None: @@ -132,7 +134,7 @@ def request_handler_factory(view, handler): # The method handler returned a ready-made Response, how nice of it return result - status_code = 200 + status_code = HTTP_OK if isinstance(result, tuple): result, status_code = result diff --git a/homeassistant/components/ifttt/__init__.py b/homeassistant/components/ifttt/__init__.py index c060c5f8815..cb1bb9f64cf 100644 --- a/homeassistant/components/ifttt/__init__.py +++ b/homeassistant/components/ifttt/__init__.py @@ -6,7 +6,7 @@ import pyfttt import requests import voluptuous as vol -from homeassistant.const import CONF_WEBHOOK_ID +from homeassistant.const import CONF_WEBHOOK_ID, HTTP_OK from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv @@ -75,7 +75,7 @@ async def async_setup(hass, config): for target, key in target_keys.items(): res = pyfttt.send_event(key, event, value1, value2, value3) - if res.status_code != 200: + if res.status_code != HTTP_OK: _LOGGER.error("IFTTT reported error sending event to %s.", target) except requests.exceptions.RequestException: _LOGGER.exception("Error communicating with IFTTT") diff --git a/homeassistant/components/lifx_cloud/scene.py b/homeassistant/components/lifx_cloud/scene.py index 08e044a46e0..7b0fca67bd6 100644 --- a/homeassistant/components/lifx_cloud/scene.py +++ b/homeassistant/components/lifx_cloud/scene.py @@ -8,7 +8,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.scene import Scene -from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN +from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -44,7 +44,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= return False status = scenes_resp.status - if status == 200: + if status == HTTP_OK: data = await scenes_resp.json() devices = [] for scene in data: diff --git a/homeassistant/components/linksys_smart/device_tracker.py b/homeassistant/components/linksys_smart/device_tracker.py index a2a8e317133..1f31ddc03a1 100644 --- a/homeassistant/components/linksys_smart/device_tracker.py +++ b/homeassistant/components/linksys_smart/device_tracker.py @@ -9,7 +9,7 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import CONF_HOST +from homeassistant.const import CONF_HOST, HTTP_OK import homeassistant.helpers.config_validation as cv DEFAULT_TIMEOUT = 10 @@ -37,7 +37,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner): # Check if the access point is accessible response = self._make_request() - if not response.status_code == 200: + if not response.status_code == HTTP_OK: raise ConnectionError("Cannot connect to Linksys Access Point") def scan_devices(self): @@ -56,7 +56,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner): self.last_results = {} response = self._make_request() - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.error( "Got HTTP status code %d when getting device list", response.status_code ) diff --git a/homeassistant/components/llamalab_automate/notify.py b/homeassistant/components/llamalab_automate/notify.py index 5a3d4e0df38..f093edbbc6b 100644 --- a/homeassistant/components/llamalab_automate/notify.py +++ b/homeassistant/components/llamalab_automate/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_DEVICE +from homeassistant.const import CONF_API_KEY, CONF_DEVICE, HTTP_OK from homeassistant.helpers import config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -51,5 +51,5 @@ class AutomateNotificationService(BaseNotificationService): } response = requests.post(_RESOURCE, json=data) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.error("Error sending message: %s", response) diff --git a/homeassistant/components/lockitron/lock.py b/homeassistant/components/lockitron/lock.py index 8ff8f430355..7d34bb02472 100644 --- a/homeassistant/components/lockitron/lock.py +++ b/homeassistant/components/lockitron/lock.py @@ -5,7 +5,7 @@ import requests import voluptuous as vol from homeassistant.components.lock import PLATFORM_SCHEMA, LockDevice -from homeassistant.const import CONF_ACCESS_TOKEN, CONF_ID +from homeassistant.const import CONF_ACCESS_TOKEN, CONF_ID, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -25,7 +25,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): response = requests.get( f"{BASE_URL}/v2/locks/{device_id}?access_token={access_token}", timeout=5 ) - if response.status_code == 200: + if response.status_code == HTTP_OK: add_entities([Lockitron(response.json()["state"], access_token, device_id)]) else: _LOGGER.error("Error retrieving lock status during init: %s", response.text) @@ -67,7 +67,7 @@ class Lockitron(LockDevice): f"{BASE_URL}/v2/locks/{self.device_id}?access_token={self.access_token}", timeout=5, ) - if response.status_code == 200: + if response.status_code == HTTP_OK: self._state = response.json()["state"] else: _LOGGER.error("Error retrieving lock status: %s", response.text) @@ -78,7 +78,7 @@ class Lockitron(LockDevice): f"{BASE_URL}/v2/locks/{self.device_id}?access_token={self.access_token}&state={requested_state}", timeout=5, ) - if response.status_code == 200: + if response.status_code == HTTP_OK: return response.json()["state"] _LOGGER.error( diff --git a/homeassistant/components/london_air/sensor.py b/homeassistant/components/london_air/sensor.py index 7eb410cacab..c7104ac19ad 100644 --- a/homeassistant/components/london_air/sensor.py +++ b/homeassistant/components/london_air/sensor.py @@ -6,6 +6,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA +from homeassistant.const import HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -83,7 +84,7 @@ class APIData: def update(self): """Get the latest data from TFL.""" response = requests.get(URL, timeout=10) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.warning("Invalid response from API") else: self.data = parse_api_response(response.json()) diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index 757dd00897d..86b5d758149 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -18,6 +18,7 @@ import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.const import ( + HTTP_OK, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, @@ -211,7 +212,7 @@ async def async_setup(hass, config): SERVICE_TURN_OFF, {}, "async_turn_off", [SUPPORT_TURN_OFF] ) component.async_register_entity_service( - SERVICE_TOGGLE, {}, "async_toggle", [SUPPORT_TURN_OFF | SUPPORT_TURN_ON], + SERVICE_TOGGLE, {}, "async_toggle", [SUPPORT_TURN_OFF | SUPPORT_TURN_ON] ) component.async_register_entity_service( SERVICE_VOLUME_UP, @@ -241,7 +242,7 @@ async def async_setup(hass, config): SERVICE_MEDIA_STOP, {}, "async_media_stop", [SUPPORT_STOP] ) component.async_register_entity_service( - SERVICE_MEDIA_NEXT_TRACK, {}, "async_media_next_track", [SUPPORT_NEXT_TRACK], + SERVICE_MEDIA_NEXT_TRACK, {}, "async_media_next_track", [SUPPORT_NEXT_TRACK] ) component.async_register_entity_service( SERVICE_MEDIA_PREVIOUS_TRACK, @@ -250,7 +251,7 @@ async def async_setup(hass, config): [SUPPORT_PREVIOUS_TRACK], ) component.async_register_entity_service( - SERVICE_CLEAR_PLAYLIST, {}, "async_clear_playlist", [SUPPORT_CLEAR_PLAYLIST], + SERVICE_CLEAR_PLAYLIST, {}, "async_clear_playlist", [SUPPORT_CLEAR_PLAYLIST] ) component.async_register_entity_service( SERVICE_VOLUME_SET, @@ -832,7 +833,7 @@ async def _async_fetch_image(hass, url): with async_timeout.timeout(10): response = await websession.get(url) - if response.status == 200: + if response.status == HTTP_OK: content = await response.read() content_type = response.headers.get(CONTENT_TYPE) if content_type: diff --git a/homeassistant/components/mobile_app/helpers.py b/homeassistant/components/mobile_app/helpers.py index 400ff31be89..7c7ceb3a827 100644 --- a/homeassistant/components/mobile_app/helpers.py +++ b/homeassistant/components/mobile_app/helpers.py @@ -7,6 +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.core import Context from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.typing import HomeAssistantType @@ -90,7 +91,7 @@ def registration_context(registration: Dict) -> Context: return Context(user_id=registration[CONF_USER_ID]) -def empty_okay_response(headers: Dict = None, status: int = 200) -> Response: +def empty_okay_response(headers: Dict = None, status: int = HTTP_OK) -> Response: """Return a Response with empty JSON object and a 200.""" return Response( text="{}", status=status, content_type="application/json", headers=headers @@ -144,7 +145,7 @@ def savable_state(hass: HomeAssistantType) -> Dict: def webhook_response( - data, *, registration: Dict, status: int = 200, headers: Dict = None + data, *, registration: Dict, status: int = HTTP_OK, headers: Dict = None ) -> Response: """Return a encrypted response if registration supports it.""" data = json.dumps(data, cls=JSONEncoder) diff --git a/homeassistant/components/mobile_app/notify.py b/homeassistant/components/mobile_app/notify.py index 00f4577ad9e..f3c79103111 100644 --- a/homeassistant/components/mobile_app/notify.py +++ b/homeassistant/components/mobile_app/notify.py @@ -12,6 +12,7 @@ from homeassistant.components.notify import ( ATTR_TITLE_DEFAULT, BaseNotificationService, ) +from homeassistant.const import HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.util.dt as dt_util @@ -134,7 +135,7 @@ class MobileAppNotificationService(BaseNotificationService): response = await self._session.post(push_url, json=data) result = await response.json() - if response.status in [200, 201, 202]: + if response.status in [HTTP_OK, 201, 202]: log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result) continue diff --git a/homeassistant/components/nfandroidtv/notify.py b/homeassistant/components/nfandroidtv/notify.py index 280733affd2..db2b22650ef 100644 --- a/homeassistant/components/nfandroidtv/notify.py +++ b/homeassistant/components/nfandroidtv/notify.py @@ -14,7 +14,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONF_HOST, CONF_TIMEOUT, UNIT_PERCENTAGE +from homeassistant.const import CONF_HOST, CONF_TIMEOUT, HTTP_OK, UNIT_PERCENTAGE import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -238,7 +238,7 @@ class NFAndroidTVNotificationService(BaseNotificationService): try: _LOGGER.debug("Payload: %s", str(payload)) response = requests.post(self._target, files=payload, timeout=self._timeout) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.error("Error sending message: %s", str(response)) except requests.exceptions.ConnectionError as err: _LOGGER.error("Error communicating with %s: %s", self._target, str(err)) diff --git a/homeassistant/components/nissan_leaf/__init__.py b/homeassistant/components/nissan_leaf/__init__.py index f5f23f2f114..a1e6d74b4f3 100644 --- a/homeassistant/components/nissan_leaf/__init__.py +++ b/homeassistant/components/nissan_leaf/__init__.py @@ -7,7 +7,7 @@ import sys from pycarwings2 import CarwingsError, Session import voluptuous as vol -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_OK from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform @@ -287,7 +287,7 @@ class LeafDataStore: if server_response is not None: _LOGGER.debug("Server Response: %s", server_response.__dict__) - if server_response.answer["status"] == 200: + if server_response.answer["status"] == HTTP_OK: self.data[DATA_BATTERY] = server_response.battery_percent # pycarwings2 library doesn't always provide cruising rnages diff --git a/homeassistant/components/openalpr_cloud/image_processing.py b/homeassistant/components/openalpr_cloud/image_processing.py index 41a631937d7..8f04b0838fe 100644 --- a/homeassistant/components/openalpr_cloud/image_processing.py +++ b/homeassistant/components/openalpr_cloud/image_processing.py @@ -17,7 +17,7 @@ from homeassistant.components.image_processing import ( from homeassistant.components.openalpr_local.image_processing import ( ImageProcessingAlprEntity, ) -from homeassistant.const import CONF_API_KEY +from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.core import split_entity_id from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -121,7 +121,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity): data = await request.json() - if request.status != 200: + if request.status != HTTP_OK: _LOGGER.error("Error %d -> %s.", request.status, data.get("error")) return diff --git a/homeassistant/components/openexchangerates/sensor.py b/homeassistant/components/openexchangerates/sensor.py index cc6da709dff..9846e305291 100644 --- a/homeassistant/components/openexchangerates/sensor.py +++ b/homeassistant/components/openexchangerates/sensor.py @@ -12,6 +12,7 @@ from homeassistant.const import ( CONF_BASE, CONF_NAME, CONF_QUOTE, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -49,7 +50,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): rest = OpenexchangeratesData(_RESOURCE, parameters, quote) response = requests.get(_RESOURCE, params=parameters, timeout=10) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.error("Check your OpenExchangeRates API key") return False diff --git a/homeassistant/components/prowl/notify.py b/homeassistant/components/prowl/notify.py index d5167ebfdc9..ada7fbb5f34 100644 --- a/homeassistant/components/prowl/notify.py +++ b/homeassistant/components/prowl/notify.py @@ -12,7 +12,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONF_API_KEY +from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -57,7 +57,7 @@ class ProwlNotificationService(BaseNotificationService): response = await session.post(url, data=payload) result = await response.text() - if response.status != 200 or "error" in result: + if response.status != HTTP_OK or "error" in result: _LOGGER.error( "Prowl service returned http status %d, response %s", response.status, diff --git a/homeassistant/components/pushsafer/notify.py b/homeassistant/components/pushsafer/notify.py index 436191ab864..12735764b4b 100644 --- a/homeassistant/components/pushsafer/notify.py +++ b/homeassistant/components/pushsafer/notify.py @@ -15,6 +15,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) +from homeassistant.const import HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -118,7 +119,7 @@ class PushsaferNotificationService(BaseNotificationService): for target in targets: payload["d"] = target response = requests.post(_RESOURCE, data=payload, timeout=CONF_TIMEOUT) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.error("Pushsafer failed with: %s", response.text) else: _LOGGER.debug("Push send: %s", response.json()) diff --git a/homeassistant/components/rachio/config_flow.py b/homeassistant/components/rachio/config_flow.py index 64e78a24f4a..2f5835ad614 100644 --- a/homeassistant/components/rachio/config_flow.py +++ b/homeassistant/components/rachio/config_flow.py @@ -5,7 +5,7 @@ from rachiopy import Rachio import voluptuous as vol from homeassistant import config_entries, core, exceptions -from homeassistant.const import CONF_API_KEY +from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.core import callback from .const import ( @@ -33,13 +33,13 @@ async def validate_input(hass: core.HomeAssistant, data): try: data = await hass.async_add_executor_job(rachio.person.getInfo) _LOGGER.debug("rachio.person.getInfo: %s", data) - if int(data[0][KEY_STATUS]) != 200: + if int(data[0][KEY_STATUS]) != HTTP_OK: raise InvalidAuth rachio_id = data[1][KEY_ID] data = await hass.async_add_executor_job(rachio.person.get, rachio_id) _LOGGER.debug("rachio.person.get: %s", data) - if int(data[0][KEY_STATUS]) != 200: + if int(data[0][KEY_STATUS]) != HTTP_OK: raise CannotConnect username = data[1][KEY_USERNAME] diff --git a/homeassistant/components/rachio/device.py b/homeassistant/components/rachio/device.py index 7ff47f7a221..f7357a1b2dc 100644 --- a/homeassistant/components/rachio/device.py +++ b/homeassistant/components/rachio/device.py @@ -3,7 +3,7 @@ import logging from typing import Optional -from homeassistant.const import EVENT_HOMEASSISTANT_STOP +from homeassistant.const import EVENT_HOMEASSISTANT_STOP, HTTP_OK from .const import ( KEY_DEVICES, @@ -40,12 +40,12 @@ class RachioPerson: def setup(self, hass): """Rachio device setup.""" response = self.rachio.person.getInfo() - assert int(response[0][KEY_STATUS]) == 200, "API key error" + assert int(response[0][KEY_STATUS]) == HTTP_OK, "API key error" self._id = response[1][KEY_ID] # Use user ID to get user data data = self.rachio.person.get(self._id) - assert int(data[0][KEY_STATUS]) == 200, "User ID error" + assert int(data[0][KEY_STATUS]) == HTTP_OK, "User ID error" self.username = data[1][KEY_USERNAME] devices = data[1][KEY_DEVICES] for controller in devices: diff --git a/homeassistant/components/radarr/sensor.py b/homeassistant/components/radarr/sensor.py index 6cfdd53653d..30051d929db 100644 --- a/homeassistant/components/radarr/sensor.py +++ b/homeassistant/components/radarr/sensor.py @@ -23,6 +23,7 @@ from homeassistant.const import ( DATA_TERABYTES, DATA_YOTTABYTES, DATA_ZETTABYTES, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -193,7 +194,7 @@ class RadarrSensor(Entity): self._state = None return - if res.status_code == 200: + if res.status_code == HTTP_OK: if self.type in ["upcoming", "movies", "commands"]: self.data = res.json() self._state = len(self.data) diff --git a/homeassistant/components/rest/notify.py b/homeassistant/components/rest/notify.py index 4f3de14b731..b9739841130 100644 --- a/homeassistant/components/rest/notify.py +++ b/homeassistant/components/rest/notify.py @@ -23,6 +23,7 @@ from homeassistant.const import ( CONF_VERIFY_SSL, HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv @@ -195,7 +196,7 @@ class RestNotificationService(BaseNotificationService): _LOGGER.exception( "Client error. Response %d: %s:", response.status_code, response.reason ) - elif response.status_code >= 200 and response.status_code < 300: + elif response.status_code >= HTTP_OK and response.status_code < 300: _LOGGER.debug( "Success. Response %d: %s:", response.status_code, response.reason ) diff --git a/homeassistant/components/rest/switch.py b/homeassistant/components/rest/switch.py index fe409a46be7..71df1852e7a 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_OK, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -153,7 +154,7 @@ class RestSwitch(SwitchDevice): try: req = await self.set_device_state(body_on_t) - if req.status == 200: + if req.status == HTTP_OK: self._state = True else: _LOGGER.error( @@ -168,7 +169,7 @@ class RestSwitch(SwitchDevice): try: req = await self.set_device_state(body_off_t) - if req.status == 200: + if req.status == HTTP_OK: self._state = False else: _LOGGER.error( diff --git a/homeassistant/components/rocketchat/notify.py b/homeassistant/components/rocketchat/notify.py index 2b5b8dcd235..efb2288f4d8 100644 --- a/homeassistant/components/rocketchat/notify.py +++ b/homeassistant/components/rocketchat/notify.py @@ -13,7 +13,13 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONF_PASSWORD, CONF_ROOM, CONF_URL, CONF_USERNAME +from homeassistant.const import ( + CONF_PASSWORD, + CONF_ROOM, + CONF_URL, + CONF_USERNAME, + HTTP_OK, +) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -62,7 +68,7 @@ class RocketChatNotificationService(BaseNotificationService): """Send a message to Rocket.Chat.""" data = kwargs.get(ATTR_DATA) or {} resp = self._server.chat_post_message(message, channel=self._room, **data) - if resp.status_code == 200: + if resp.status_code == HTTP_OK: success = resp.json()["success"] if not success: _LOGGER.error("Unable to post Rocket.Chat message") diff --git a/homeassistant/components/route53/__init__.py b/homeassistant/components/route53/__init__.py index a84475ab8a1..cda4ba9dc86 100644 --- a/homeassistant/components/route53/__init__.py +++ b/homeassistant/components/route53/__init__.py @@ -7,7 +7,7 @@ import boto3 from ipify import exceptions, get_ip import voluptuous as vol -from homeassistant.const import CONF_DOMAIN, CONF_TTL, CONF_ZONE +from homeassistant.const import CONF_DOMAIN, CONF_TTL, CONF_ZONE, HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_time_interval @@ -118,5 +118,5 @@ def _update_route53( ) _LOGGER.debug("Response is %s", response) - if response["ResponseMetadata"]["HTTPStatusCode"] != 200: + if response["ResponseMetadata"]["HTTPStatusCode"] != HTTP_OK: _LOGGER.warning(response) diff --git a/homeassistant/components/rss_feed_template/__init__.py b/homeassistant/components/rss_feed_template/__init__.py index 69bc9474267..b979e4d5261 100644 --- a/homeassistant/components/rss_feed_template/__init__.py +++ b/homeassistant/components/rss_feed_template/__init__.py @@ -5,6 +5,7 @@ from aiohttp import web import voluptuous as vol from homeassistant.components.http import HomeAssistantView +from homeassistant.const import HTTP_OK import homeassistant.helpers.config_validation as cv CONTENT_TYPE_XML = "text/xml" @@ -98,4 +99,6 @@ class RssView(HomeAssistantView): response += "\n" - return web.Response(body=response, content_type=CONTENT_TYPE_XML, status=200) + return web.Response( + body=response, content_type=CONTENT_TYPE_XML, status=HTTP_OK + ) diff --git a/homeassistant/components/sigfox/sensor.py b/homeassistant/components/sigfox/sensor.py index da07290f422..6df6e1d0c82 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 +from homeassistant.const import CONF_NAME, HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -66,7 +66,7 @@ class SigfoxAPI: """Check API credentials are valid.""" url = urljoin(API_URL, "devicetypes") response = requests.get(url, auth=self._auth, timeout=10) - if response.status_code != 200: + if response.status_code != HTTP_OK: if response.status_code == 401: _LOGGER.error("Invalid credentials for Sigfox API") else: diff --git a/homeassistant/components/sky_hub/device_tracker.py b/homeassistant/components/sky_hub/device_tracker.py index c7dc1092b73..2537196f21d 100644 --- a/homeassistant/components/sky_hub/device_tracker.py +++ b/homeassistant/components/sky_hub/device_tracker.py @@ -10,7 +10,7 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import CONF_HOST +from homeassistant.const import CONF_HOST, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -85,7 +85,7 @@ def _get_skyhub_data(url): except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out") return - if response.status_code == 200: + if response.status_code == HTTP_OK: return _parse_skyhub_response(response.text) _LOGGER.error("Invalid response from Sky Hub: %s", response) diff --git a/homeassistant/components/sonarr/sensor.py b/homeassistant/components/sonarr/sensor.py index c0781b37603..ac9b81be7a4 100644 --- a/homeassistant/components/sonarr/sensor.py +++ b/homeassistant/components/sonarr/sensor.py @@ -23,6 +23,7 @@ from homeassistant.const import ( DATA_TERABYTES, DATA_YOTTABYTES, DATA_ZETTABYTES, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -220,7 +221,7 @@ class SonarrSensor(Entity): self._state = None return - if res.status_code == 200: + if res.status_code == HTTP_OK: if self.type in ["upcoming", "queue", "series", "commands"]: if self.days == 1 and self.type == "upcoming": # Sonarr API returns an empty array if start and end dates diff --git a/homeassistant/components/squeezebox/media_player.py b/homeassistant/components/squeezebox/media_player.py index 0610d4d9cf2..57305a3b4c0 100644 --- a/homeassistant/components/squeezebox/media_player.py +++ b/homeassistant/components/squeezebox/media_player.py @@ -33,6 +33,7 @@ from homeassistant.const import ( CONF_PASSWORD, CONF_PORT, CONF_USERNAME, + HTTP_OK, STATE_IDLE, STATE_OFF, STATE_PAUSED, @@ -223,7 +224,7 @@ class LogitechMediaServer: with async_timeout.timeout(TIMEOUT): response = await websession.post(url, data=data, auth=auth) - if response.status != 200: + if response.status != HTTP_OK: _LOGGER.error( "Query failed, response code: %s Full message: %s", response.status, diff --git a/homeassistant/components/startca/sensor.py b/homeassistant/components/startca/sensor.py index b6d90b99302..19c80a82e9f 100644 --- a/homeassistant/components/startca/sensor.py +++ b/homeassistant/components/startca/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_MONITORED_VARIABLES, CONF_NAME, DATA_GIGABYTES, + HTTP_OK, UNIT_PERCENTAGE, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -146,7 +147,7 @@ class StartcaData: url = f"https://www.start.ca/support/usage/api?key={self.api_key}" with async_timeout.timeout(REQUEST_TIMEOUT): req = await self.websession.get(url) - if req.status != 200: + if req.status != HTTP_OK: _LOGGER.error("Request failed with status: %u", req.status) return False diff --git a/homeassistant/components/synology_chat/notify.py b/homeassistant/components/synology_chat/notify.py index 3e1aeb4ce13..c8f665cb408 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 +from homeassistant.const import CONF_RESOURCE, CONF_VERIFY_SSL, 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 (200, 201): + if response.status_code not in (HTTP_OK, 201): _LOGGER.exception( "Error sending message. Response %d: %s:", response.status_code, diff --git a/homeassistant/components/tado/device_tracker.py b/homeassistant/components/tado/device_tracker.py index ea797754da8..5d87bfe8e34 100644 --- a/homeassistant/components/tado/device_tracker.py +++ b/homeassistant/components/tado/device_tracker.py @@ -13,7 +13,7 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_OK from homeassistant.helpers.aiohttp_client import async_create_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle @@ -114,7 +114,7 @@ class TadoDeviceScanner(DeviceScanner): response = await self.websession.get(url) - if response.status != 200: + if response.status != HTTP_OK: _LOGGER.warning("Error %d on %s.", response.status, self.tadoapiurl) return False diff --git a/homeassistant/components/teksavvy/sensor.py b/homeassistant/components/teksavvy/sensor.py index 0d2d290fed9..96331cb5347 100644 --- a/homeassistant/components/teksavvy/sensor.py +++ b/homeassistant/components/teksavvy/sensor.py @@ -11,6 +11,7 @@ from homeassistant.const import ( CONF_MONITORED_VARIABLES, CONF_NAME, DATA_GIGABYTES, + HTTP_OK, UNIT_PERCENTAGE, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -144,7 +145,7 @@ class TekSavvyData: ) with async_timeout.timeout(REQUEST_TIMEOUT): req = await self.websession.get(url, headers=headers) - if req.status != 200: + if req.status != HTTP_OK: _LOGGER.error("Request failed with status: %u", req.status) return False diff --git a/homeassistant/components/tomato/device_tracker.py b/homeassistant/components/tomato/device_tracker.py index 35db0671772..873da5a7864 100644 --- a/homeassistant/components/tomato/device_tracker.py +++ b/homeassistant/components/tomato/device_tracker.py @@ -18,6 +18,7 @@ from homeassistant.const import ( CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, + HTTP_OK, ) import homeassistant.helpers.config_validation as cv @@ -102,7 +103,7 @@ class TomatoDeviceScanner(DeviceScanner): # Calling and parsing the Tomato api here. We only need the # wldev and dhcpd_lease values. - if response.status_code == 200: + if response.status_code == HTTP_OK: for param, value in self.parse_api_pattern.findall(response.text): diff --git a/homeassistant/components/traccar/__init__.py b/homeassistant/components/traccar/__init__.py index 7e94ab0a351..03482292135 100644 --- a/homeassistant/components/traccar/__init__.py +++ b/homeassistant/components/traccar/__init__.py @@ -28,7 +28,7 @@ _LOGGER = logging.getLogger(__name__) TRACKER_UPDATE = f"{DOMAIN}_tracker_update" -DEFAULT_ACCURACY = 200 +DEFAULT_ACCURACY = HTTP_OK DEFAULT_BATTERY = -1 diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index d9d513198ce..726490b2030 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -22,7 +22,7 @@ from homeassistant.components.media_player.const import ( MEDIA_TYPE_MUSIC, SERVICE_PLAY_MEDIA, ) -from homeassistant.const import ATTR_ENTITY_ID, CONF_PLATFORM +from homeassistant.const import ATTR_ENTITY_ID, CONF_PLATFORM, HTTP_OK from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform, discovery @@ -507,7 +507,7 @@ def _get_cache_files(cache_dir): record = _RE_VOICE_FILE.match(file_data) if record: key = KEY_PATTERN.format( - record.group(1), record.group(2), record.group(3), record.group(4), + record.group(1), record.group(2), record.group(3), record.group(4) ) cache[key.lower()] = file_data.lower() return cache @@ -543,7 +543,7 @@ class TextToSpeechUrlView(HomeAssistantView): url = await self.tts.async_get_url( p_type, message, cache=cache, language=language, options=options ) - resp = self.json({"url": url}, 200) + 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) diff --git a/homeassistant/components/twitter/notify.py b/homeassistant/components/twitter/notify.py index 768e1ee7316..62e8fc17dff 100644 --- a/homeassistant/components/twitter/notify.py +++ b/homeassistant/components/twitter/notify.py @@ -14,7 +14,7 @@ from homeassistant.components.notify import ( PLATFORM_SCHEMA, BaseNotificationService, ) -from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME +from homeassistant.const import CONF_ACCESS_TOKEN, CONF_USERNAME, HTTP_OK import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_track_point_in_time @@ -88,7 +88,7 @@ class TwitterNotificationService(BaseNotificationService): if self.user: user_resp = self.api.request("users/lookup", {"screen_name": self.user}) user_id = user_resp.json()[0]["id"] - if user_resp.status_code != 200: + if user_resp.status_code != HTTP_OK: self.log_error_resp(user_resp) else: _LOGGER.debug("Message posted: %s", user_resp.json()) @@ -108,7 +108,7 @@ class TwitterNotificationService(BaseNotificationService): "statuses/update", {"status": message, "media_ids": media_id} ) - if resp.status_code != 200: + if resp.status_code != HTTP_OK: self.log_error_resp(resp) else: _LOGGER.debug("Message posted: %s", resp.json()) @@ -171,7 +171,7 @@ class TwitterNotificationService(BaseNotificationService): while bytes_sent < total_bytes: chunk = file.read(4 * 1024 * 1024) resp = self.upload_media_append(chunk, media_id, segment_id) - if resp.status_code not in range(200, 299): + if resp.status_code not in range(HTTP_OK, 299): self.log_error_resp_append(resp) return None segment_id = segment_id + 1 @@ -200,7 +200,7 @@ class TwitterNotificationService(BaseNotificationService): {"command": "STATUS", "media_id": media_id}, method_override="GET", ) - if resp.status_code != 200: + if resp.status_code != HTTP_OK: _LOGGER.error("media processing error: %s", resp.json()) processing_info = resp.json()["processing_info"] diff --git a/homeassistant/components/ubus/device_tracker.py b/homeassistant/components/ubus/device_tracker.py index 1f5b5b4b1b6..4cefefc2f96 100644 --- a/homeassistant/components/ubus/device_tracker.py +++ b/homeassistant/components/ubus/device_tracker.py @@ -11,7 +11,7 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, HTTP_OK from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv @@ -214,7 +214,7 @@ def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params): except (requests.exceptions.ConnectionError, requests.exceptions.Timeout): return - if res.status_code == 200: + if res.status_code == HTTP_OK: response = res.json() if "error" in response: if ( diff --git a/homeassistant/components/uk_transport/sensor.py b/homeassistant/components/uk_transport/sensor.py index 77929436283..e7c01479a96 100644 --- a/homeassistant/components/uk_transport/sensor.py +++ b/homeassistant/components/uk_transport/sensor.py @@ -7,7 +7,7 @@ import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import CONF_MODE, TIME_MINUTES +from homeassistant.const import CONF_MODE, HTTP_OK, TIME_MINUTES import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle @@ -133,7 +133,7 @@ class UkTransportSensor(Entity): ) response = requests.get(self._url, params=request_params) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.warning("Invalid response from API") elif "error" in response.json(): if "exceeded" in response.json()["error"]: diff --git a/homeassistant/components/viaggiatreno/sensor.py b/homeassistant/components/viaggiatreno/sensor.py index 783581a0755..5de968f5eac 100644 --- a/homeassistant/components/viaggiatreno/sensor.py +++ b/homeassistant/components/viaggiatreno/sensor.py @@ -7,7 +7,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA -from homeassistant.const import ATTR_ATTRIBUTION, TIME_MINUTES +from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity @@ -72,7 +72,7 @@ async def async_http_request(hass, uri): session = hass.helpers.aiohttp_client.async_get_clientsession(hass) with async_timeout.timeout(REQUEST_TIMEOUT): req = await session.get(uri) - if req.status != 200: + if req.status != HTTP_OK: return {"error": req.status} json_response = await req.json() return json_response diff --git a/homeassistant/components/voicerss/tts.py b/homeassistant/components/voicerss/tts.py index 9f87dabf94f..52a3f9f1b1c 100644 --- a/homeassistant/components/voicerss/tts.py +++ b/homeassistant/components/voicerss/tts.py @@ -7,7 +7,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider -from homeassistant.const import CONF_API_KEY +from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -175,7 +175,7 @@ class VoiceRSSProvider(Provider): with async_timeout.timeout(10): request = await websession.post(VOICERSS_API_URL, data=form_data) - if request.status != 200: + if request.status != HTTP_OK: _LOGGER.error( "Error %d on load url %s.", request.status, request.url ) diff --git a/homeassistant/components/volumio/media_player.py b/homeassistant/components/volumio/media_player.py index 5778df8c367..6d46b6015e0 100644 --- a/homeassistant/components/volumio/media_player.py +++ b/homeassistant/components/volumio/media_player.py @@ -31,6 +31,7 @@ from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PORT, + HTTP_OK, STATE_IDLE, STATE_PAUSED, STATE_PLAYING, @@ -127,7 +128,7 @@ class Volumio(MediaPlayerDevice): try: websession = async_get_clientsession(self.hass) response = await websession.get(url, params=params) - if response.status == 200: + if response.status == HTTP_OK: data = await response.json() else: _LOGGER.error( diff --git a/homeassistant/components/webhook/__init__.py b/homeassistant/components/webhook/__init__.py index 217baf42f3a..84ebdaddad0 100644 --- a/homeassistant/components/webhook/__init__.py +++ b/homeassistant/components/webhook/__init__.py @@ -7,6 +7,7 @@ import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.http.view import HomeAssistantView +from homeassistant.const import HTTP_OK from homeassistant.core import callback from homeassistant.loader import bind_hass @@ -71,16 +72,16 @@ async def async_handle_webhook(hass, webhook_id, request): # Always respond successfully to not give away if a hook exists or not. if webhook is None: _LOGGER.warning("Received message for unregistered webhook %s", webhook_id) - return Response(status=200) + return Response(status=HTTP_OK) try: response = await webhook["handler"](hass, webhook_id, request) if response is None: - response = Response(status=200) + response = Response(status=HTTP_OK) return response except Exception: # pylint: disable=broad-except _LOGGER.exception("Error processing webhook %s", webhook_id) - return Response(status=200) + return Response(status=HTTP_OK) async def async_setup(hass, config): diff --git a/homeassistant/components/wsdot/sensor.py b/homeassistant/components/wsdot/sensor.py index 6ee55aa387f..786fd07f626 100644 --- a/homeassistant/components/wsdot/sensor.py +++ b/homeassistant/components/wsdot/sensor.py @@ -13,6 +13,7 @@ from homeassistant.const import ( CONF_API_KEY, CONF_ID, CONF_NAME, + HTTP_OK, TIME_MINUTES, ) import homeassistant.helpers.config_validation as cv @@ -112,7 +113,7 @@ class WashingtonStateTravelTimeSensor(WashingtonStateTransportSensor): } response = requests.get(RESOURCE, params, timeout=10) - if response.status_code != 200: + if response.status_code != HTTP_OK: _LOGGER.warning("Invalid response from WSDOT API") else: self._data = response.json() diff --git a/homeassistant/components/xiaomi/device_tracker.py b/homeassistant/components/xiaomi/device_tracker.py index df16b13b931..530140b524f 100644 --- a/homeassistant/components/xiaomi/device_tracker.py +++ b/homeassistant/components/xiaomi/device_tracker.py @@ -9,7 +9,7 @@ from homeassistant.components.device_tracker import ( PLATFORM_SCHEMA, DeviceScanner, ) -from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, HTTP_OK import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) @@ -112,7 +112,7 @@ def _retrieve_list(host, token, **kwargs): except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out at URL %s", url) return - if res.status_code != 200: + if res.status_code != HTTP_OK: _LOGGER.exception("Connection failed with http code %s", res.status_code) return try: @@ -150,7 +150,7 @@ def _get_token(host, username, password): except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out") return - if res.status_code == 200: + if res.status_code == HTTP_OK: try: result = res.json() except ValueError: diff --git a/homeassistant/components/yandextts/tts.py b/homeassistant/components/yandextts/tts.py index b06df4b7a42..32b77e08df4 100644 --- a/homeassistant/components/yandextts/tts.py +++ b/homeassistant/components/yandextts/tts.py @@ -7,7 +7,7 @@ import async_timeout import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider -from homeassistant.const import CONF_API_KEY +from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -133,7 +133,7 @@ class YandexSpeechKitProvider(Provider): request = await websession.get(YANDEX_API_URL, params=url_param) - if request.status != 200: + if request.status != HTTP_OK: _LOGGER.error( "Error %d on load URL %s", request.status, request.url ) diff --git a/homeassistant/components/yr/sensor.py b/homeassistant/components/yr/sensor.py index 2061c061dd0..e477f4a3c89 100644 --- a/homeassistant/components/yr/sensor.py +++ b/homeassistant/components/yr/sensor.py @@ -20,6 +20,7 @@ from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, + HTTP_OK, PRESSURE_HPA, SPEED_METERS_PER_SECOND, TEMP_CELSIUS, @@ -185,7 +186,7 @@ class YrData: websession = async_get_clientsession(self.hass) with async_timeout.timeout(10): resp = await websession.get(self._url, params=self._urlparams) - if resp.status != 200: + if resp.status != HTTP_OK: try_again(f"{resp.url} returned {resp.status}") return text = await resp.text() diff --git a/homeassistant/util/aiohttp.py b/homeassistant/util/aiohttp.py index 69911986f57..d43929dd777 100644 --- a/homeassistant/util/aiohttp.py +++ b/homeassistant/util/aiohttp.py @@ -5,6 +5,8 @@ from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict +from homeassistant.const import HTTP_OK + class MockRequest: """Mock an aiohttp request.""" @@ -13,7 +15,7 @@ class MockRequest: self, content: bytes, method: str = "GET", - status: int = 200, + status: int = HTTP_OK, headers: Optional[Dict[str, str]] = None, query_string: Optional[str] = None, url: str = "",