Use HTTP_BAD_REQUEST constant (#33797)

This commit is contained in:
springstan 2020-04-09 21:43:42 +02:00 committed by GitHub
parent d510384c0d
commit 4c38e6cfa5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 111 additions and 61 deletions

View file

@ -5,7 +5,7 @@ from requests.exceptions import ConnectTimeout, HTTPError
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_BAD_REQUEST
from homeassistant.core import callback from homeassistant.core import callback
from .const import DEFAULT_CACHEDB, DOMAIN, LOGGER # pylint: disable=unused-import from .const import DEFAULT_CACHEDB, DOMAIN, LOGGER # pylint: disable=unused-import
@ -46,7 +46,7 @@ class AbodeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
except (AbodeException, ConnectTimeout, HTTPError) as ex: except (AbodeException, ConnectTimeout, HTTPError) as ex:
LOGGER.error("Unable to connect to Abode: %s", str(ex)) LOGGER.error("Unable to connect to Abode: %s", str(ex))
if ex.errcode == 400: if ex.errcode == HTTP_BAD_REQUEST:
return self._show_form({"base": "invalid_credentials"}) return self._show_form({"base": "invalid_credentials"})
return self._show_form({"base": "connection_error"}) return self._show_form({"base": "connection_error"})

View file

@ -132,7 +132,7 @@ from homeassistant.components.http.auth import async_sign_path
from homeassistant.components.http.ban import log_invalid_auth from homeassistant.components.http.ban import log_invalid_auth
from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components.http.view import HomeAssistantView from homeassistant.components.http.view import HomeAssistantView
from homeassistant.const import HTTP_FORBIDDEN, HTTP_OK from homeassistant.const import HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_OK
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.loader import bind_hass from homeassistant.loader import bind_hass
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -261,7 +261,9 @@ class TokenView(HomeAssistantView):
hass, data, str(request[KEY_REAL_IP]) hass, data, str(request[KEY_REAL_IP])
) )
return self.json({"error": "unsupported_grant_type"}, status_code=400) return self.json(
{"error": "unsupported_grant_type"}, status_code=HTTP_BAD_REQUEST
)
async def _async_handle_revoke_token(self, hass, data): async def _async_handle_revoke_token(self, hass, data):
"""Handle revoke token request.""" """Handle revoke token request."""
@ -288,7 +290,7 @@ class TokenView(HomeAssistantView):
if client_id is None or not indieauth.verify_client_id(client_id): if client_id is None or not indieauth.verify_client_id(client_id):
return self.json( return self.json(
{"error": "invalid_request", "error_description": "Invalid client id"}, {"error": "invalid_request", "error_description": "Invalid client id"},
status_code=400, status_code=HTTP_BAD_REQUEST,
) )
code = data.get("code") code = data.get("code")
@ -296,7 +298,7 @@ class TokenView(HomeAssistantView):
if code is None: if code is None:
return self.json( return self.json(
{"error": "invalid_request", "error_description": "Invalid code"}, {"error": "invalid_request", "error_description": "Invalid code"},
status_code=400, status_code=HTTP_BAD_REQUEST,
) )
user = self._retrieve_user(client_id, RESULT_TYPE_USER, code) user = self._retrieve_user(client_id, RESULT_TYPE_USER, code)
@ -304,7 +306,7 @@ class TokenView(HomeAssistantView):
if user is None or not isinstance(user, User): if user is None or not isinstance(user, User):
return self.json( return self.json(
{"error": "invalid_request", "error_description": "Invalid code"}, {"error": "invalid_request", "error_description": "Invalid code"},
status_code=400, status_code=HTTP_BAD_REQUEST,
) )
# refresh user # refresh user
@ -336,21 +338,21 @@ class TokenView(HomeAssistantView):
if client_id is not None and not indieauth.verify_client_id(client_id): if client_id is not None and not indieauth.verify_client_id(client_id):
return self.json( return self.json(
{"error": "invalid_request", "error_description": "Invalid client id"}, {"error": "invalid_request", "error_description": "Invalid client id"},
status_code=400, status_code=HTTP_BAD_REQUEST,
) )
token = data.get("refresh_token") token = data.get("refresh_token")
if token is None: if token is None:
return self.json({"error": "invalid_request"}, status_code=400) return self.json({"error": "invalid_request"}, status_code=HTTP_BAD_REQUEST)
refresh_token = await hass.auth.async_get_refresh_token_by_token(token) refresh_token = await hass.auth.async_get_refresh_token_by_token(token)
if refresh_token is None: if refresh_token is None:
return self.json({"error": "invalid_grant"}, status_code=400) return self.json({"error": "invalid_grant"}, status_code=HTTP_BAD_REQUEST)
if refresh_token.client_id != client_id: if refresh_token.client_id != client_id:
return self.json({"error": "invalid_request"}, status_code=400) return self.json({"error": "invalid_request"}, status_code=HTTP_BAD_REQUEST)
access_token = hass.auth.async_create_access_token(refresh_token, remote_addr) access_token = hass.auth.async_create_access_token(refresh_token, remote_addr)
@ -386,7 +388,7 @@ class LinkUserView(HomeAssistantView):
) )
if credentials is None: if credentials is None:
return self.json_message("Invalid code", status_code=400) return self.json_message("Invalid code", status_code=HTTP_BAD_REQUEST)
await hass.auth.async_link_user(user, credentials) await hass.auth.async_link_user(user, credentials)
return self.json_message("User linked") return self.json_message("User linked")

View file

@ -79,7 +79,7 @@ from homeassistant.components.http.ban import (
) )
from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components.http.view import HomeAssistantView from homeassistant.components.http.view import HomeAssistantView
from homeassistant.const import HTTP_NOT_FOUND from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND
from . import indieauth from . import indieauth
@ -104,7 +104,7 @@ class AuthProvidersView(HomeAssistantView):
if not hass.components.onboarding.async_is_user_onboarded(): if not hass.components.onboarding.async_is_user_onboarded():
return self.json_message( return self.json_message(
message="Onboarding not finished", message="Onboarding not finished",
status_code=400, status_code=HTTP_BAD_REQUEST,
message_code="onboarding_required", message_code="onboarding_required",
) )
@ -170,7 +170,9 @@ class LoginFlowIndexView(HomeAssistantView):
if not await indieauth.verify_redirect_uri( if not await indieauth.verify_redirect_uri(
request.app["hass"], data["client_id"], data["redirect_uri"] request.app["hass"], data["client_id"], data["redirect_uri"]
): ):
return self.json_message("invalid client id or redirect uri", 400) return self.json_message(
"invalid client id or redirect uri", HTTP_BAD_REQUEST
)
if isinstance(data["handler"], list): if isinstance(data["handler"], list):
handler = tuple(data["handler"]) handler = tuple(data["handler"])
@ -188,7 +190,7 @@ class LoginFlowIndexView(HomeAssistantView):
except data_entry_flow.UnknownHandler: except data_entry_flow.UnknownHandler:
return self.json_message("Invalid handler specified", HTTP_NOT_FOUND) return self.json_message("Invalid handler specified", HTTP_NOT_FOUND)
except data_entry_flow.UnknownStep: except data_entry_flow.UnknownStep:
return self.json_message("Handler does not support init", 400) return self.json_message("Handler does not support init", HTTP_BAD_REQUEST)
if result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY: if result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
await process_success_login(request) await process_success_login(request)
@ -222,7 +224,7 @@ class LoginFlowResourceView(HomeAssistantView):
client_id = data.pop("client_id") client_id = data.pop("client_id")
if not indieauth.verify_client_id(client_id): if not indieauth.verify_client_id(client_id):
return self.json_message("Invalid client id", 400) return self.json_message("Invalid client id", HTTP_BAD_REQUEST)
try: try:
# do not allow change ip during login flow # do not allow change ip during login flow
@ -230,13 +232,13 @@ class LoginFlowResourceView(HomeAssistantView):
if flow["flow_id"] == flow_id and flow["context"][ if flow["flow_id"] == flow_id and flow["context"][
"ip_address" "ip_address"
] != request.get(KEY_REAL_IP): ] != request.get(KEY_REAL_IP):
return self.json_message("IP address changed", 400) return self.json_message("IP address changed", HTTP_BAD_REQUEST)
result = await self._flow_mgr.async_configure(flow_id, data) result = await self._flow_mgr.async_configure(flow_id, data)
except data_entry_flow.UnknownFlow: except data_entry_flow.UnknownFlow:
return self.json_message("Invalid flow specified", HTTP_NOT_FOUND) return self.json_message("Invalid flow specified", HTTP_NOT_FOUND)
except vol.Invalid: except vol.Invalid:
return self.json_message("User input malformed", 400) return self.json_message("User input malformed", HTTP_BAD_REQUEST)
if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY: if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
# @log_invalid_auth does not work here since it returns HTTP 200 # @log_invalid_auth does not work here since it returns HTTP 200

View file

@ -6,7 +6,7 @@ import re
from aiohttp import web from aiohttp import web
from homeassistant.components import http from homeassistant.components import http
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import HTTP_BAD_REQUEST, STATE_OFF, STATE_ON
from homeassistant.helpers.config_validation import ( # noqa: F401 from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE, PLATFORM_SCHEMA_BASE,
@ -182,12 +182,12 @@ class CalendarEventView(http.HomeAssistantView):
start = request.query.get("start") start = request.query.get("start")
end = request.query.get("end") end = request.query.get("end")
if None in (start, end, entity): if None in (start, end, entity):
return web.Response(status=400) return web.Response(status=HTTP_BAD_REQUEST)
try: try:
start_date = dt.parse_datetime(start) start_date = dt.parse_datetime(start)
end_date = dt.parse_datetime(end) end_date = dt.parse_datetime(end)
except (ValueError, AttributeError): except (ValueError, AttributeError):
return web.Response(status=400) return web.Response(status=HTTP_BAD_REQUEST)
event_list = await entity.async_get_events( event_list = await entity.async_get_events(
request.app["hass"], start_date, end_date request.app["hass"], start_date, end_date
) )

View file

@ -13,7 +13,7 @@ from homeassistant.components.alexa import (
errors as alexa_errors, errors as alexa_errors,
state_report as alexa_state_report, state_report as alexa_state_report,
) )
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES, HTTP_BAD_REQUEST
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers import entity_registry from homeassistant.helpers import entity_registry
from homeassistant.helpers.event import async_call_later from homeassistant.helpers.event import async_call_later
@ -114,7 +114,7 @@ class AlexaConfig(alexa_config.AbstractConfig):
resp = await cloud_api.async_alexa_access_token(self._cloud) resp = await cloud_api.async_alexa_access_token(self._cloud)
body = await resp.json() body = await resp.json()
if resp.status == 400: if resp.status == HTTP_BAD_REQUEST:
if body["reason"] in ("RefreshTokenNotFound", "UnknownRegion"): if body["reason"] in ("RefreshTokenNotFound", "UnknownRegion"):
if self.should_report_state: if self.should_report_state:
await self._prefs.async_update(alexa_report_state=False) await self._prefs.async_update(alexa_report_state=False)

View file

@ -19,7 +19,7 @@ from homeassistant.components.google_assistant import helpers as google_helpers
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.components.websocket_api import const as ws_const from homeassistant.components.websocket_api import const as ws_const
from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR, HTTP_OK from homeassistant.const import HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR, HTTP_OK
from homeassistant.core import callback from homeassistant.core import callback
from .const import ( from .const import (
@ -109,11 +109,17 @@ async def async_setup(hass):
_CLOUD_ERRORS.update( _CLOUD_ERRORS.update(
{ {
auth.UserNotFound: (400, "User does not exist."), auth.UserNotFound: (HTTP_BAD_REQUEST, "User does not exist."),
auth.UserNotConfirmed: (400, "Email not confirmed."), auth.UserNotConfirmed: (HTTP_BAD_REQUEST, "Email not confirmed."),
auth.UserExists: (400, "An account with the given email already exists."), auth.UserExists: (
HTTP_BAD_REQUEST,
"An account with the given email already exists.",
),
auth.Unauthenticated: (401, "Authentication failed."), auth.Unauthenticated: (401, "Authentication failed."),
auth.PasswordChangeRequired: (400, "Password change required."), auth.PasswordChangeRequired: (
HTTP_BAD_REQUEST,
"Password change required.",
),
asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."), asyncio.TimeoutError: (502, "Unable to reach the Home Assistant cloud."),
aiohttp.ClientError: ( aiohttp.ClientError: (
HTTP_INTERNAL_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR,

View file

@ -6,7 +6,12 @@ import os
import voluptuous as vol import voluptuous as vol
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_ID, EVENT_COMPONENT_LOADED, HTTP_NOT_FOUND from homeassistant.const import (
CONF_ID,
EVENT_COMPONENT_LOADED,
HTTP_BAD_REQUEST,
HTTP_NOT_FOUND,
)
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import ATTR_COMPONENT from homeassistant.setup import ATTR_COMPONENT
@ -129,12 +134,12 @@ class BaseEditConfigView(HomeAssistantView):
try: try:
data = await request.json() data = await request.json()
except ValueError: except ValueError:
return self.json_message("Invalid JSON specified", 400) return self.json_message("Invalid JSON specified", HTTP_BAD_REQUEST)
try: try:
self.key_schema(config_key) self.key_schema(config_key)
except vol.Invalid as err: except vol.Invalid as err:
return self.json_message(f"Key malformed: {err}", 400) return self.json_message(f"Key malformed: {err}", HTTP_BAD_REQUEST)
hass = request.app["hass"] hass = request.app["hass"]
@ -146,7 +151,7 @@ class BaseEditConfigView(HomeAssistantView):
else: else:
self.data_schema(data) self.data_schema(data)
except (vol.Invalid, HomeAssistantError) as err: except (vol.Invalid, HomeAssistantError) as err:
return self.json_message(f"Message malformed: {err}", 400) return self.json_message(f"Message malformed: {err}", HTTP_BAD_REQUEST)
path = hass.config.path(self.path) path = hass.config.path(self.path)

View file

@ -6,7 +6,7 @@ from aiohttp.web import Response
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.components.zwave import DEVICE_CONFIG_SCHEMA_ENTRY, const from homeassistant.components.zwave import DEVICE_CONFIG_SCHEMA_ENTRY, const
from homeassistant.const import HTTP_NOT_FOUND, HTTP_OK from homeassistant.const import HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_OK
import homeassistant.core as ha import homeassistant.core as ha
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -51,7 +51,7 @@ class ZWaveLogView(HomeAssistantView):
try: try:
lines = int(request.query.get("lines", 0)) lines = int(request.query.get("lines", 0))
except ValueError: except ValueError:
return Response(text="Invalid datetime", status=400) return Response(text="Invalid datetime", status=HTTP_BAD_REQUEST)
hass = request.app["hass"] hass = request.app["hass"]
response = await hass.async_add_job(self._get_log, hass, lines) response = await hass.async_add_job(self._get_log, hass, lines)

View file

@ -8,6 +8,7 @@ from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationSer
from homeassistant.const import ( from homeassistant.const import (
CONF_ACCESS_TOKEN, CONF_ACCESS_TOKEN,
CONF_USERNAME, CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_FORBIDDEN, HTTP_FORBIDDEN,
HTTP_INTERNAL_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR,
) )
@ -36,7 +37,7 @@ class FreeSMSNotificationService(BaseNotificationService):
"""Send a message to the Free Mobile user cell.""" """Send a message to the Free Mobile user cell."""
resp = self.free_client.send_sms(message) resp = self.free_client.send_sms(message)
if resp.status_code == 400: if resp.status_code == HTTP_BAD_REQUEST:
_LOGGER.error("At least one parameter is missing") _LOGGER.error("At least one parameter is missing")
elif resp.status_code == 402: elif resp.status_code == 402:
_LOGGER.error("Too much SMS send in a few time") _LOGGER.error("Too much SMS send in a few time")

View file

@ -5,6 +5,7 @@ import logging
from aiohttp import web from aiohttp import web
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.const import HTTP_BAD_REQUEST
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.typing import HomeAssistantType
from .const import ATTR_ADMIN, ATTR_ENABLE, ATTR_ICON, ATTR_PANELS, ATTR_TITLE from .const import ATTR_ADMIN, ATTR_ENABLE, ATTR_ICON, ATTR_PANELS, ATTR_TITLE
@ -52,7 +53,7 @@ class HassIOAddonPanel(HomeAssistantView):
# Panel exists for add-on slug # Panel exists for add-on slug
if addon not in panels or not panels[addon][ATTR_ENABLE]: if addon not in panels or not panels[addon][ATTR_ENABLE]:
_LOGGER.error("Panel is not enable for %s", addon) _LOGGER.error("Panel is not enable for %s", addon)
return web.Response(status=400) return web.Response(status=HTTP_BAD_REQUEST)
data = panels[addon] data = panels[addon]
# Register panel # Register panel

View file

@ -12,7 +12,7 @@ from homeassistant.components.http import (
CONF_SSL_CERTIFICATE, CONF_SSL_CERTIFICATE,
DEFAULT_SERVER_HOST, DEFAULT_SERVER_HOST,
) )
from homeassistant.const import HTTP_OK, SERVER_PORT from homeassistant.const import HTTP_BAD_REQUEST, HTTP_OK, SERVER_PORT
from .const import X_HASSIO from .const import X_HASSIO
@ -167,7 +167,7 @@ class HassIO:
headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")}, headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")},
) )
if request.status not in (HTTP_OK, 400): if request.status not in (HTTP_OK, HTTP_BAD_REQUEST):
_LOGGER.error("%s return code %d.", command, request.status) _LOGGER.error("%s return code %d.", command, request.status)
raise HassioAPIError() raise HassioAPIError()

View file

@ -10,6 +10,7 @@ from aiohttp.web_exceptions import HTTPForbidden, HTTPUnauthorized
import voluptuous as vol import voluptuous as vol
from homeassistant.config import load_yaml_config_file from homeassistant.config import load_yaml_config_file
from homeassistant.const import HTTP_BAD_REQUEST
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -81,7 +82,7 @@ def log_invalid_auth(func):
async def handle_req(view, request, *args, **kwargs): async def handle_req(view, request, *args, **kwargs):
"""Try to log failed login attempts if response status >= 400.""" """Try to log failed login attempts if response status >= 400."""
resp = await func(view, request, *args, **kwargs) resp = await func(view, request, *args, **kwargs)
if resp.status >= 400: if resp.status >= HTTP_BAD_REQUEST:
await process_wrong_login(request) await process_wrong_login(request)
return resp return resp

View file

@ -4,6 +4,8 @@ import logging
import voluptuous as vol import voluptuous as vol
from homeassistant.const import HTTP_BAD_REQUEST
# mypy: allow-untyped-defs # mypy: allow-untyped-defs
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -38,14 +40,16 @@ class RequestDataValidator:
except ValueError: except ValueError:
if not self._allow_empty or (await request.content.read()) != b"": if not self._allow_empty or (await request.content.read()) != b"":
_LOGGER.error("Invalid JSON received.") _LOGGER.error("Invalid JSON received.")
return view.json_message("Invalid JSON.", 400) return view.json_message("Invalid JSON.", HTTP_BAD_REQUEST)
data = {} data = {}
try: try:
kwargs["data"] = self._schema(data) kwargs["data"] = self._schema(data)
except vol.Invalid as err: except vol.Invalid as err:
_LOGGER.error("Data does not match schema: %s", err) _LOGGER.error("Data does not match schema: %s", err)
return view.json_message(f"Message format incorrect: {err}", 400) return view.json_message(
f"Message format incorrect: {err}", HTTP_BAD_REQUEST
)
result = await method(view, request, *args, **kwargs) result = await method(view, request, *args, **kwargs)
return result return result

View file

@ -9,7 +9,7 @@ import voluptuous as vol
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.const import CONF_SENSORS from homeassistant.const import CONF_SENSORS, HTTP_BAD_REQUEST
from homeassistant.core import callback from homeassistant.core import callback
from .const import ( from .const import (
@ -207,5 +207,5 @@ class LogiCircleAuthCallbackView(HomeAssistantView):
) )
return self.json_message("Authorisation code saved") return self.json_message("Authorisation code saved")
return self.json_message( return self.json_message(
"Authorisation code missing from query string", status_code=400 "Authorisation code missing from query string", status_code=HTTP_BAD_REQUEST
) )

View file

@ -7,7 +7,7 @@ from aiohttp.web import Response, json_response
from nacl.encoding import Base64Encoder from nacl.encoding import Base64Encoder
from nacl.secret import SecretBox from nacl.secret import SecretBox
from homeassistant.const import HTTP_OK from homeassistant.const import HTTP_BAD_REQUEST, HTTP_OK
from homeassistant.core import Context from homeassistant.core import Context
from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.json import JSONEncoder
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.typing import HomeAssistantType
@ -99,7 +99,7 @@ def empty_okay_response(headers: Dict = None, status: int = HTTP_OK) -> Response
def error_response( def error_response(
code: str, message: str, status: int = 400, headers: dict = None code: str, message: str, status: int = HTTP_BAD_REQUEST, headers: dict = None
) -> Response: ) -> Response:
"""Return an error Response.""" """Return an error Response."""
return json_response( return json_response(

View file

@ -9,7 +9,12 @@ from requests.exceptions import ConnectTimeout, HTTPError
import voluptuous as vol import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from homeassistant.const import (
CONF_PASSWORD,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
)
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -74,7 +79,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
raise ConfigEntryNotReady raise ConfigEntryNotReady
except HTTPError as http_ex: except HTTPError as http_ex:
if ( if (
http_ex.response.status_code >= 400 http_ex.response.status_code >= HTTP_BAD_REQUEST
and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR
): ):
_LOGGER.error( _LOGGER.error(

View file

@ -6,7 +6,12 @@ from requests.exceptions import ConnectTimeout, HTTPError
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries, core, exceptions from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from homeassistant.const import (
CONF_PASSWORD,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
)
from .const import DOMAIN # pylint:disable=unused-import from .const import DOMAIN # pylint:disable=unused-import
@ -35,7 +40,7 @@ async def validate_input(hass: core.HomeAssistant, data):
except HTTPError as http_ex: except HTTPError as http_ex:
_LOGGER.error("HTTP error from Nexia service: %s", http_ex) _LOGGER.error("HTTP error from Nexia service: %s", http_ex)
if ( if (
http_ex.response.status_code >= 400 http_ex.response.status_code >= HTTP_BAD_REQUEST
and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR and http_ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR
): ):
raise InvalidAuth raise InvalidAuth

View file

@ -11,6 +11,7 @@ from homeassistant.const import (
CONF_DEVICES, CONF_DEVICES,
CONF_PASSWORD, CONF_PASSWORD,
CONF_USERNAME, CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@ -84,7 +85,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
raise ConfigEntryNotReady raise ConfigEntryNotReady
except requests.exceptions.HTTPError as ex: except requests.exceptions.HTTPError as ex:
if ( if (
ex.response.status_code > 400 ex.response.status_code > HTTP_BAD_REQUEST
and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR
): ):
_LOGGER.error("Failed to login to nuheat: %s", ex) _LOGGER.error("Failed to login to nuheat: %s", ex)

View file

@ -6,7 +6,12 @@ import requests.exceptions
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries, core, exceptions from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERVER_ERROR from homeassistant.const import (
CONF_PASSWORD,
CONF_USERNAME,
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
)
from .const import CONF_SERIAL_NUMBER from .const import CONF_SERIAL_NUMBER
from .const import DOMAIN # pylint:disable=unused-import from .const import DOMAIN # pylint:disable=unused-import
@ -35,7 +40,7 @@ async def validate_input(hass: core.HomeAssistant, data):
raise CannotConnect raise CannotConnect
except requests.exceptions.HTTPError as ex: except requests.exceptions.HTTPError as ex:
if ( if (
ex.response.status_code > 400 ex.response.status_code > HTTP_BAD_REQUEST
and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR
): ):
raise InvalidAuth raise InvalidAuth

View file

@ -21,6 +21,7 @@ from homeassistant.const import (
CONF_RESOURCE, CONF_RESOURCE,
CONF_USERNAME, CONF_USERNAME,
CONF_VERIFY_SSL, CONF_VERIFY_SSL,
HTTP_BAD_REQUEST,
HTTP_BASIC_AUTHENTICATION, HTTP_BASIC_AUTHENTICATION,
HTTP_DIGEST_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION,
HTTP_INTERNAL_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR,
@ -197,7 +198,7 @@ class RestNotificationService(BaseNotificationService):
"Server error. Response %d: %s:", response.status_code, response.reason "Server error. Response %d: %s:", response.status_code, response.reason
) )
elif ( elif (
response.status_code >= 400 response.status_code >= HTTP_BAD_REQUEST
and response.status_code < HTTP_INTERNAL_SERVER_ERROR and response.status_code < HTTP_INTERNAL_SERVER_ERROR
): ):
_LOGGER.exception( _LOGGER.exception(

View file

@ -16,6 +16,7 @@ from homeassistant.const import (
CONF_TIMEOUT, CONF_TIMEOUT,
CONF_USERNAME, CONF_USERNAME,
CONF_VERIFY_SSL, CONF_VERIFY_SSL,
HTTP_BAD_REQUEST,
HTTP_OK, HTTP_OK,
) )
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -95,7 +96,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
) )
req = await switch.get_device_state(hass) req = await switch.get_device_state(hass)
if req.status >= 400: if req.status >= HTTP_BAD_REQUEST:
_LOGGER.error("Got non-ok response from resource: %s", req.status) _LOGGER.error("Got non-ok response from resource: %s", req.status)
else: else:
async_add_entities([switch]) async_add_entities([switch])

View file

@ -15,6 +15,7 @@ from homeassistant.const import (
CONF_URL, CONF_URL,
CONF_USERNAME, CONF_USERNAME,
CONF_VERIFY_SSL, CONF_VERIFY_SSL,
HTTP_BAD_REQUEST,
) )
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
@ -119,7 +120,7 @@ async def async_setup(hass, config):
timeout=timeout, timeout=timeout,
) as response: ) as response:
if response.status < 400: if response.status < HTTP_BAD_REQUEST:
_LOGGER.debug( _LOGGER.debug(
"Success. Url: %s. Status code: %d.", "Success. Url: %s. Status code: %d.",
response.url, response.url,

View file

@ -22,7 +22,13 @@ from homeassistant.components.media_player.const import (
MEDIA_TYPE_MUSIC, MEDIA_TYPE_MUSIC,
SERVICE_PLAY_MEDIA, SERVICE_PLAY_MEDIA,
) )
from homeassistant.const import ATTR_ENTITY_ID, CONF_PLATFORM, HTTP_NOT_FOUND, HTTP_OK from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_PLATFORM,
HTTP_BAD_REQUEST,
HTTP_NOT_FOUND,
HTTP_OK,
)
from homeassistant.core import callback from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_per_platform, discovery from homeassistant.helpers import config_per_platform, discovery
@ -529,9 +535,11 @@ class TextToSpeechUrlView(HomeAssistantView):
try: try:
data = await request.json() data = await request.json()
except ValueError: except ValueError:
return self.json_message("Invalid JSON specified", 400) return self.json_message("Invalid JSON specified", HTTP_BAD_REQUEST)
if not data.get(ATTR_PLATFORM) and data.get(ATTR_MESSAGE): if not data.get(ATTR_PLATFORM) and data.get(ATTR_MESSAGE):
return self.json_message("Must specify platform and message", 400) return self.json_message(
"Must specify platform and message", HTTP_BAD_REQUEST
)
p_type = data[ATTR_PLATFORM] p_type = data[ATTR_PLATFORM]
message = data[ATTR_MESSAGE] message = data[ATTR_MESSAGE]
@ -546,7 +554,7 @@ class TextToSpeechUrlView(HomeAssistantView):
resp = self.json({"url": url}, HTTP_OK) resp = self.json({"url": url}, HTTP_OK)
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error("Error on init tts: %s", err) _LOGGER.error("Error on init tts: %s", err)
resp = self.json({"error": err}, 400) resp = self.json({"error": err}, HTTP_BAD_REQUEST)
return resp return resp

View file

@ -29,6 +29,7 @@ from homeassistant.const import (
CONF_RESOURCE, CONF_RESOURCE,
CONF_ROOM, CONF_ROOM,
CONF_SENDER, CONF_SENDER,
HTTP_BAD_REQUEST,
) )
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.template as template_helper import homeassistant.helpers.template as template_helper
@ -262,7 +263,7 @@ async def async_send_message(
result = await hass.async_add_executor_job(get_url, url) result = await hass.async_add_executor_job(get_url, url)
if result.status_code >= 400: if result.status_code >= HTTP_BAD_REQUEST:
_LOGGER.error("Could not load file from %s", url) _LOGGER.error("Could not load file from %s", url)
return None return None