Use http status constants more, add HTTP_ACCEPTED and HTTP_BAD_GATEWAY (#39993)

* Use http status codes and add HTTP_BAD_GATEWAY constant

* Address review comments:
 - using constants in tado integration
 - using constant in media_player init.py

* Add and use HTTP_ACCEPTED constant
pull/39822/head
springstan 2020-09-15 19:01:07 +02:00 committed by GitHub
parent 59d610af17
commit db582bdc1b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 137 additions and 58 deletions

View File

@ -6,7 +6,7 @@ import logging
import aiohttp
import async_timeout
from homeassistant.const import MATCH_ALL, STATE_ON
from homeassistant.const import HTTP_ACCEPTED, MATCH_ALL, STATE_ON
import homeassistant.util.dt as dt_util
from .const import API_CHANGE, Cause
@ -109,7 +109,7 @@ async def async_send_changereport_message(
_LOGGER.debug("Sent: %s", json.dumps(message_serialized))
_LOGGER.debug("Received (%s): %s", response.status, response_text)
if response.status == 202:
if response.status == HTTP_ACCEPTED:
return
response_json = json.loads(response_text)
@ -240,7 +240,7 @@ async def async_send_doorbell_event_message(hass, config, alexa_entity):
_LOGGER.debug("Sent: %s", json.dumps(message_serialized))
_LOGGER.debug("Received (%s): %s", response.status, response_text)
if response.status == 202:
if response.status == HTTP_ACCEPTED:
return
response_json = json.loads(response_text)

View File

@ -80,7 +80,11 @@ from homeassistant.components.http.ban import (
)
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND
from homeassistant.const import (
HTTP_BAD_REQUEST,
HTTP_METHOD_NOT_ALLOWED,
HTTP_NOT_FOUND,
)
from . import indieauth
@ -153,7 +157,7 @@ class LoginFlowIndexView(HomeAssistantView):
async def get(self, request):
"""Do not allow index of flows in progress."""
return web.Response(status=405)
return web.Response(status=HTTP_METHOD_NOT_ALLOWED)
@RequestDataValidator(
vol.Schema(

View File

@ -6,7 +6,12 @@ from aiohttp.hdrs import AUTHORIZATION
import requests
import voluptuous as vol
from homeassistant.const import CONF_API_KEY, HTTP_OK
from homeassistant.const import (
CONF_API_KEY,
HTTP_METHOD_NOT_ALLOWED,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
@ -67,9 +72,9 @@ class BloomSky:
headers={AUTHORIZATION: self._api_key},
timeout=10,
)
if response.status_code == 401:
if response.status_code == HTTP_UNAUTHORIZED:
raise RuntimeError("Invalid API_KEY")
if response.status_code == 405:
if response.status_code == HTTP_METHOD_NOT_ALLOWED:
_LOGGER.error("You have no bloomsky devices configured")
return
if response.status_code != HTTP_OK:

View File

@ -7,7 +7,12 @@ from bond_api import Bond
import voluptuous as vol
from homeassistant import config_entries, exceptions
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST, CONF_NAME
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_HOST,
CONF_NAME,
HTTP_UNAUTHORIZED,
)
from .const import CONF_BOND_ID
from .const import DOMAIN # pylint:disable=unused-import
@ -31,7 +36,7 @@ async def _validate_input(data: Dict[str, Any]) -> str:
except ClientConnectionError as error:
raise InputValidationError("cannot_connect") from error
except ClientResponseError as error:
if error.status == 401:
if error.status == HTTP_UNAUTHORIZED:
raise InputValidationError("invalid_auth") from error
raise InputValidationError("unknown") from error
except Exception as error:

View File

@ -5,7 +5,7 @@ import requests
import voluptuous as vol
from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService
from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT, HTTP_OK
from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT, HTTP_ACCEPTED, HTTP_OK
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
@ -37,5 +37,5 @@ class ClickatellNotificationService(BaseNotificationService):
data = {"apiKey": self.api_key, "to": self.recipient, "content": message}
resp = requests.get(BASE_API_URL, params=data, timeout=5)
if (resp.status_code != HTTP_OK) or (resp.status_code != 202):
if (resp.status_code != HTTP_OK) or (resp.status_code != HTTP_ACCEPTED):
_LOGGER.error("Error %s : %s", resp.status_code, resp.text)

View File

@ -19,7 +19,13 @@ from homeassistant.components.google_assistant import helpers as google_helpers
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components.websocket_api import const as ws_const
from homeassistant.const import HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR, HTTP_OK
from homeassistant.const import (
HTTP_BAD_GATEWAY,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import callback
from .const import (
@ -73,7 +79,10 @@ _CLOUD_ERRORS = {
HTTP_INTERNAL_SERVER_ERROR,
"Remote UI not compatible with 127.0.0.1/::1 as trusted proxies.",
),
asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."),
asyncio.TimeoutError: (
HTTP_BAD_GATEWAY,
"Unable to reach the Home Assistant cloud.",
),
aiohttp.ClientError: (
HTTP_INTERNAL_SERVER_ERROR,
"Error making internal request",
@ -122,7 +131,7 @@ async def async_setup(hass):
HTTP_BAD_REQUEST,
"An account with the given email already exists.",
),
auth.Unauthenticated: (401, "Authentication failed."),
auth.Unauthenticated: (HTTP_UNAUTHORIZED, "Authentication failed."),
auth.PasswordChangeRequired: (
HTTP_BAD_REQUEST,
"Password change required.",
@ -177,7 +186,7 @@ def _process_cloud_exception(exc, where):
if err_info is None:
_LOGGER.exception("Unexpected error processing request for %s", where)
err_info = (502, f"Unexpected error: {exc}")
err_info = (HTTP_BAD_GATEWAY, f"Unexpected error: {exc}")
return err_info

View File

@ -6,7 +6,7 @@ from aiohttp.web import Response
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.zwave import DEVICE_CONFIG_SCHEMA_ENTRY, const
from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_OK
from homeassistant.const import HTTP_ACCEPTED, HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_OK
import homeassistant.core as ha
import homeassistant.helpers.config_validation as cv
@ -254,7 +254,9 @@ class ZWaveProtectionView(HomeAssistantView):
)
state = node.set_protection(value_id, selection)
if not state:
return self.json_message("Protection setting did not complete", 202)
return self.json_message(
"Protection setting did not complete", HTTP_ACCEPTED
)
return self.json_message("Protection setting succsessfully set", HTTP_OK)
return await hass.async_add_executor_job(_set_protection)

View File

@ -17,6 +17,7 @@ from homeassistant.const import (
CONF_USERNAME,
CONF_VERIFY_SSL,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
import homeassistant.helpers.config_validation as cv
@ -155,7 +156,7 @@ class DdWrtDeviceScanner(DeviceScanner):
return
if response.status_code == HTTP_OK:
return _parse_ddwrt_response(response.text)
if response.status_code == 401:
if response.status_code == HTTP_UNAUTHORIZED:
# Authentication error
_LOGGER.exception(
"Failed to authenticate, check your username and password"

View File

@ -19,6 +19,7 @@ from homeassistant.const import (
CONF_TOKEN,
CONF_USERNAME,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryNotReady
@ -127,7 +128,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
status = await hass.async_add_executor_job(device.ready)
info = await hass.async_add_executor_job(device.info)
except urllib.error.HTTPError as err:
if err.code == 401:
if err.code == HTTP_UNAUTHORIZED:
_LOGGER.error(
"Authorization rejected by DoorBird for %s@%s", username, device_ip
)
@ -357,7 +358,9 @@ class DoorBirdRequestView(HomeAssistantView):
device = get_doorstation_by_token(hass, token)
if device is None:
return web.Response(status=401, text="Invalid token provided.")
return web.Response(
status=HTTP_UNAUTHORIZED, text="Invalid token provided."
)
if device:
event_data = device.get_event_data()

View File

@ -7,7 +7,13 @@ from doorbirdpy import DoorBird
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_USERNAME,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import callback
from homeassistant.util.network import is_link_local
@ -39,7 +45,7 @@ async def validate_input(hass: core.HomeAssistant, data):
status = await hass.async_add_executor_job(device.ready)
info = await hass.async_add_executor_job(device.info)
except urllib.error.HTTPError as err:
if err.code == 401:
if err.code == HTTP_UNAUTHORIZED:
raise InvalidAuth from err
raise CannotConnect from err
except OSError as err:

View File

@ -5,7 +5,12 @@ import requests
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_BAD_REQUEST, HTTP_OK
from homeassistant.const import (
CONF_ACCESS_TOKEN,
HTTP_BAD_REQUEST,
HTTP_CREATED,
HTTP_OK,
)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
@ -55,7 +60,7 @@ def setup(hass, config):
url = f"https://api.foursquare.com/v2/checkins/add?oauth_token={config[CONF_ACCESS_TOKEN]}&v=20160802&m=swarm"
response = requests.post(url, data=call.data, timeout=10)
if response.status_code not in (HTTP_OK, 201):
if response.status_code not in (HTTP_OK, HTTP_CREATED):
_LOGGER.exception(
"Error checking in user. Response %d: %s:",
response.status_code,

View File

@ -10,7 +10,11 @@ import jwt
# Typing imports
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES, HTTP_INTERNAL_SERVER_ERROR
from homeassistant.const import (
CLOUD_NEVER_EXPOSED_ENTITIES,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_UNAUTHORIZED,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util import dt as dt_util
@ -200,7 +204,7 @@ class GoogleConfig(AbstractConfig):
try:
return await _call()
except ClientResponseError as error:
if error.status == 401:
if error.status == HTTP_UNAUTHORIZED:
_LOGGER.warning(
"Request for %s unauthorized, renewing token and retrying", url
)

View File

@ -12,6 +12,7 @@ from aiohttp.web_exceptions import HTTPBadGateway
import async_timeout
from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView
from homeassistant.const import HTTP_UNAUTHORIZED
from .const import X_HASS_IS_ADMIN, X_HASS_USER_ID, X_HASSIO
@ -53,7 +54,7 @@ class HassIOView(HomeAssistantView):
) -> Union[web.Response, web.StreamResponse]:
"""Route data to Hass.io."""
if _need_auth(path) and not request[KEY_AUTHENTICATED]:
return web.Response(status=401)
return web.Response(status=HTTP_UNAUTHORIZED)
return await self._command_proxy(path, request)

View File

@ -12,6 +12,7 @@ from homeassistant.components.notify import (
ATTR_TITLE_DEFAULT,
BaseNotificationService,
)
from homeassistant.const import HTTP_CREATED, HTTP_TOO_MANY_REQUESTS
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
@ -90,13 +91,13 @@ class iOSNotificationService(BaseNotificationService):
req = requests.post(PUSH_URL, json=data, timeout=10)
if req.status_code != 201:
if req.status_code != HTTP_CREATED:
fallback_error = req.json().get("errorMessage", "Unknown error")
fallback_message = (
f"Internal server error, please try again later: {fallback_error}"
)
message = req.json().get("message", fallback_message)
if req.status_code == 429:
if req.status_code == HTTP_TOO_MANY_REQUESTS:
_LOGGER.warning(message)
log_rate_limits(self.hass, target, req.json(), 30)
else:

View File

@ -9,7 +9,13 @@ import async_timeout
import voluptuous as vol
from homeassistant.components.scene import Scene
from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN, HTTP_OK
from homeassistant.const import (
CONF_PLATFORM,
CONF_TIMEOUT,
CONF_TOKEN,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
@ -50,7 +56,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
devices = [LifxCloudScene(hass, headers, timeout, scene) for scene in data]
async_add_entities(devices)
return True
if status == 401:
if status == HTTP_UNAUTHORIZED:
_LOGGER.error("Unauthorized (bad token?) on %s", url)
return False

View File

@ -27,6 +27,7 @@ from homeassistant.const import (
HTTP_INTERNAL_SERVER_ERROR,
HTTP_NOT_FOUND,
HTTP_OK,
HTTP_UNAUTHORIZED,
SERVICE_MEDIA_NEXT_TRACK,
SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY,
@ -880,7 +881,7 @@ class MediaPlayerImageView(HomeAssistantView):
"""Start a get request."""
player = self.component.get_entity(entity_id)
if player is None:
status = HTTP_NOT_FOUND if request[KEY_AUTHENTICATED] else 401
status = HTTP_NOT_FOUND if request[KEY_AUTHENTICATED] else HTTP_UNAUTHORIZED
return web.Response(status=status)
authenticated = (
@ -889,7 +890,7 @@ class MediaPlayerImageView(HomeAssistantView):
)
if not authenticated:
return web.Response(status=401)
return web.Response(status=HTTP_UNAUTHORIZED)
data, content_type = await player.async_get_media_image()

View File

@ -9,7 +9,13 @@ import pymelcloud
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME, HTTP_FORBIDDEN
from homeassistant.const import (
CONF_PASSWORD,
CONF_TOKEN,
CONF_USERNAME,
HTTP_FORBIDDEN,
HTTP_UNAUTHORIZED,
)
from .const import DOMAIN # pylint: disable=unused-import
@ -57,7 +63,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self.hass.helpers.aiohttp_client.async_get_clientsession(),
)
except ClientResponseError as err:
if err.status == 401 or err.status == HTTP_FORBIDDEN:
if err.status == HTTP_UNAUTHORIZED or err.status == HTTP_FORBIDDEN:
return self.async_abort(reason="invalid_auth")
return self.async_abort(reason="cannot_connect")
except (asyncio.TimeoutError, ClientError):

View File

@ -12,7 +12,12 @@ from homeassistant.components.notify import (
ATTR_TITLE_DEFAULT,
BaseNotificationService,
)
from homeassistant.const import HTTP_OK
from homeassistant.const import (
HTTP_ACCEPTED,
HTTP_CREATED,
HTTP_OK,
HTTP_TOO_MANY_REQUESTS,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.util.dt as dt_util
@ -135,7 +140,7 @@ class MobileAppNotificationService(BaseNotificationService):
response = await self._session.post(push_url, json=data)
result = await response.json()
if response.status in [HTTP_OK, 201, 202]:
if response.status in [HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED]:
log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result)
continue
@ -152,7 +157,7 @@ class MobileAppNotificationService(BaseNotificationService):
" This message is generated externally to Home Assistant."
)
if response.status == 429:
if response.status == HTTP_TOO_MANY_REQUESTS:
_LOGGER.warning(message)
log_rate_limits(
self.hass, entry_data[ATTR_DEVICE_NAME], result, logging.WARNING

View File

@ -4,6 +4,7 @@ from functools import partial
from nest.nest import AUTHORIZE_URL, AuthorizationError, NestAuth
from homeassistant.const import HTTP_UNAUTHORIZED
from homeassistant.core import callback
from . import config_flow
@ -42,7 +43,7 @@ async def resolve_auth_code(hass, client_id, client_secret, code):
await hass.async_add_job(auth.login)
return await result
except AuthorizationError as err:
if err.response.status_code == 401:
if err.response.status_code == HTTP_UNAUTHORIZED:
raise config_flow.CodeInvalid()
raise config_flow.NestAuthError(
f"Unknown error: {err} ({err.response.status_code})"

View File

@ -17,6 +17,7 @@ from homeassistant.const import (
EVENT_HOMEASSISTANT_STOP,
HTTP_BASIC_AUTHENTICATION,
HTTP_DIGEST_AUTHENTICATION,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
@ -138,7 +139,7 @@ async def _get_snapshot_auth(hass, device, entry):
try:
response = await hass.async_add_executor_job(_get)
if response.status_code == 401:
if response.status_code == HTTP_UNAUTHORIZED:
return HTTP_BASIC_AUTHENTICATION
return HTTP_DIGEST_AUTHENTICATION

View File

@ -15,6 +15,7 @@ from homeassistant.const import (
CONF_RECIPIENT,
CONF_SENDER,
CONTENT_TYPE_TEXT_PLAIN,
HTTP_ACCEPTED,
)
import homeassistant.helpers.config_validation as cv
@ -65,5 +66,5 @@ class SendgridNotificationService(BaseNotificationService):
}
response = self._sg.client.mail.send.post(request_body=data)
if response.status_code != 202:
if response.status_code != HTTP_ACCEPTED:
_LOGGER.error("Unable to send notification")

View File

@ -8,7 +8,12 @@ import async_timeout
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_USERNAME,
HTTP_UNAUTHORIZED,
)
from homeassistant.helpers import aiohttp_client
from .const import DOMAIN # pylint:disable=unused-import
@ -91,7 +96,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try:
device_info = await validate_input(self.hass, self.host, user_input)
except aiohttp.ClientResponseError as error:
if error.status == 401:
if error.status == HTTP_UNAUTHORIZED:
errors["base"] = "invalid_auth"
else:
errors["base"] = "cannot_connect"

View File

@ -8,7 +8,7 @@ import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, HTTP_OK
from homeassistant.const import CONF_NAME, HTTP_OK, HTTP_UNAUTHORIZED
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
@ -67,7 +67,7 @@ class SigfoxAPI:
url = urljoin(API_URL, "devicetypes")
response = requests.get(url, auth=self._auth, timeout=10)
if response.status_code != HTTP_OK:
if response.status_code == 401:
if response.status_code == HTTP_UNAUTHORIZED:
_LOGGER.error("Invalid credentials for Sigfox API")
else:
_LOGGER.error(

View File

@ -14,6 +14,7 @@ from homeassistant.const import (
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
HTTP_FORBIDDEN,
HTTP_UNAUTHORIZED,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -158,7 +159,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
hass.data[DOMAIN][DATA_BROKERS][entry.entry_id] = broker
except ClientResponseError as ex:
if ex.status in (401, HTTP_FORBIDDEN):
if ex.status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN):
_LOGGER.exception(
"Unable to setup configuration entry '%s' - please reconfigure the integration",
entry.title,

View File

@ -10,7 +10,7 @@ from homeassistant.components.notify import (
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import CONF_RESOURCE, CONF_VERIFY_SSL, HTTP_OK
from homeassistant.const import CONF_RESOURCE, CONF_VERIFY_SSL, HTTP_CREATED, HTTP_OK
import homeassistant.helpers.config_validation as cv
ATTR_FILE_URL = "file_url"
@ -57,7 +57,7 @@ class SynologyChatNotificationService(BaseNotificationService):
self._resource, data=to_send, timeout=10, verify=self._verify_ssl
)
if response.status_code not in (HTTP_OK, 201):
if response.status_code not in (HTTP_OK, HTTP_CREATED):
_LOGGER.exception(
"Error sending message. Response %d: %s:",
response.status_code,

View File

@ -11,6 +11,7 @@ from homeassistant.const import (
CONF_SCAN_INTERVAL,
CONF_TOKEN,
CONF_USERNAME,
HTTP_UNAUTHORIZED,
)
from homeassistant.core import callback
from homeassistant.helpers import aiohttp_client, config_validation as cv
@ -140,7 +141,7 @@ async def validate_input(hass: core.HomeAssistant, data):
test_login=True
)
except TeslaException as ex:
if ex.code == 401:
if ex.code == HTTP_UNAUTHORIZED:
_LOGGER.error("Invalid credentials: %s", ex)
raise InvalidAuth() from ex
_LOGGER.error("Unable to communicate with Tesla API: %s", ex)

View File

@ -8,7 +8,7 @@ import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONTENT_TYPE_JSON, HTTP_NOT_FOUND
from homeassistant.const import CONTENT_TYPE_JSON, HTTP_NOT_FOUND, HTTP_UNAUTHORIZED
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
@ -135,7 +135,7 @@ class TtnDataStorage:
_LOGGER.error("The device is not available: %s", self._device_id)
return None
if status == 401:
if status == HTTP_UNAUTHORIZED:
_LOGGER.error("Not authorized for Application ID: %s", self._app_id)
return None

View File

@ -19,6 +19,7 @@ from homeassistant.const import (
CONF_USERNAME,
CONF_VERIFY_SSL,
HTTP_OK,
HTTP_UNAUTHORIZED,
)
import homeassistant.helpers.config_validation as cv
@ -111,7 +112,7 @@ class TomatoDeviceScanner(DeviceScanner):
self.last_results[param] = json.loads(value.replace("'", '"'))
return True
if response.status_code == 401:
if response.status_code == HTTP_UNAUTHORIZED:
# Authentication error
_LOGGER.exception(
"Failed to authenticate, please check your username and password"

View File

@ -12,6 +12,7 @@ from homeassistant.const import (
CONF_SCAN_INTERVAL,
CONF_USERNAME,
EVENT_HOMEASSISTANT_STOP,
HTTP_SERVICE_UNAVAILABLE,
)
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
@ -189,7 +190,7 @@ class VerisureHub:
self.overview = self.session.get_overview()
except verisure.ResponseError as ex:
_LOGGER.error("Could not read overview, %s", ex)
if ex.status_code == 503: # Service unavailable
if ex.status_code == HTTP_SERVICE_UNAVAILABLE: # Service unavailable
_LOGGER.info("Trying to log in again")
self.login()
else:

View File

@ -29,6 +29,7 @@ from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_WEBHOOK_ID,
HTTP_UNAUTHORIZED,
MASS_KILOGRAMS,
PERCENTAGE,
SPEED_METERS_PER_SECOND,
@ -54,7 +55,7 @@ from .const import Measurement
_LOGGER = logging.getLogger(const.LOG_NAMESPACE)
NOT_AUTHENTICATED_ERROR = re.compile(
"^401,.*",
f"^{HTTP_UNAUTHORIZED},.*",
re.IGNORECASE,
)
DATA_UPDATED_SIGNAL = "withings_entity_state_updated"

View File

@ -564,6 +564,7 @@ URL_API_TEMPLATE = "/api/template"
HTTP_OK = 200
HTTP_CREATED = 201
HTTP_ACCEPTED = 202
HTTP_MOVED_PERMANENTLY = 301
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
@ -573,6 +574,7 @@ HTTP_METHOD_NOT_ALLOWED = 405
HTTP_UNPROCESSABLE_ENTITY = 422
HTTP_TOO_MANY_REQUESTS = 429
HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_BAD_GATEWAY = 502
HTTP_SERVICE_UNAVAILABLE = 503
HTTP_BASIC_AUTHENTICATION = "basic"

View File

@ -8,7 +8,7 @@ import voluptuous as vol
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.const import HTTP_NOT_FOUND
from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND
import homeassistant.helpers.config_validation as cv
@ -76,7 +76,7 @@ class FlowManagerIndexView(_BaseFlowManagerView):
except data_entry_flow.UnknownHandler:
return self.json_message("Invalid handler specified", HTTP_NOT_FOUND)
except data_entry_flow.UnknownStep:
return self.json_message("Handler does not support user", 400)
return self.json_message("Handler does not support user", HTTP_BAD_REQUEST)
result = self._prepare_result_json(result)
@ -107,7 +107,7 @@ class FlowManagerResourceView(_BaseFlowManagerView):
except data_entry_flow.UnknownFlow:
return self.json_message("Invalid flow specified", HTTP_NOT_FOUND)
except vol.Invalid:
return self.json_message("User input malformed", 400)
return self.json_message("User input malformed", HTTP_BAD_REQUEST)
result = self._prepare_result_json(result)