From cc97502a0c379b6ba4846251aaf7c15806cd6efa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Fri, 1 Oct 2021 19:27:44 +0300 Subject: [PATCH] Use HTTPStatus instead of HTTP_* consts in aiohttp web response statuses (#56541) --- homeassistant/components/auth/__init__.py | 7 +++---- homeassistant/components/auth/login_flow.py | 3 +-- homeassistant/components/calendar/__init__.py | 7 ++++--- homeassistant/components/config/zwave.py | 3 +-- homeassistant/components/doorbird/__init__.py | 3 ++- homeassistant/components/geofency/__init__.py | 7 +++++-- homeassistant/components/gpslogger/__init__.py | 13 ++++++------- homeassistant/components/hassio/addon_panel.py | 5 +++-- homeassistant/components/hassio/auth.py | 6 +++--- homeassistant/components/hassio/http.py | 4 ++-- homeassistant/components/http/view.py | 4 ++-- homeassistant/components/locative/__init__.py | 8 +++++--- homeassistant/components/mailbox/__init__.py | 6 +++--- homeassistant/components/media_player/__init__.py | 6 +++--- homeassistant/components/motioneye/__init__.py | 15 +++++---------- homeassistant/components/traccar/__init__.py | 8 ++++++-- homeassistant/components/tts/__init__.py | 3 +-- homeassistant/components/webhook/__init__.py | 8 ++++---- 18 files changed, 59 insertions(+), 57 deletions(-) diff --git a/homeassistant/components/auth/__init__.py b/homeassistant/components/auth/__init__.py index 49c18b4737a..4076cace2a2 100644 --- a/homeassistant/components/auth/__init__.py +++ b/homeassistant/components/auth/__init__.py @@ -134,7 +134,6 @@ 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 @@ -274,15 +273,15 @@ class TokenView(HomeAssistantView): token = data.get("token") if token is None: - return web.Response(status=HTTP_OK) + return web.Response(status=HTTPStatus.OK) refresh_token = await hass.auth.async_get_refresh_token_by_token(token) if refresh_token is None: - return web.Response(status=HTTP_OK) + return web.Response(status=HTTPStatus.OK) await hass.auth.async_remove_refresh_token(refresh_token) - return web.Response(status=HTTP_OK) + return web.Response(status=HTTPStatus.OK) async def _async_handle_auth_code(self, hass, data, remote_addr): """Handle authorization code request.""" diff --git a/homeassistant/components/auth/login_flow.py b/homeassistant/components/auth/login_flow.py index f15eeee2f16..7975e220acb 100644 --- a/homeassistant/components/auth/login_flow.py +++ b/homeassistant/components/auth/login_flow.py @@ -81,7 +81,6 @@ 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_METHOD_NOT_ALLOWED from . import indieauth @@ -155,7 +154,7 @@ class LoginFlowIndexView(HomeAssistantView): async def get(self, request): """Do not allow index of flows in progress.""" # pylint: disable=no-self-use - return web.Response(status=HTTP_METHOD_NOT_ALLOWED) + return web.Response(status=HTTPStatus.METHOD_NOT_ALLOWED) @RequestDataValidator( vol.Schema( diff --git a/homeassistant/components/calendar/__init__.py b/homeassistant/components/calendar/__init__.py index 8809e05d25b..10580339329 100644 --- a/homeassistant/components/calendar/__init__.py +++ b/homeassistant/components/calendar/__init__.py @@ -2,6 +2,7 @@ from __future__ import annotations from datetime import timedelta +from http import HTTPStatus import logging import re from typing import cast, final @@ -10,7 +11,7 @@ from aiohttp import web from homeassistant.components import http from homeassistant.config_entries import ConfigEntry -from homeassistant.const import HTTP_BAD_REQUEST, STATE_OFF, STATE_ON +from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, @@ -200,12 +201,12 @@ class CalendarEventView(http.HomeAssistantView): start = request.query.get("start") end = request.query.get("end") if None in (start, end, entity): - return web.Response(status=HTTP_BAD_REQUEST) + return web.Response(status=HTTPStatus.BAD_REQUEST) try: start_date = dt.parse_datetime(start) end_date = dt.parse_datetime(end) except (ValueError, AttributeError): - return web.Response(status=HTTP_BAD_REQUEST) + return web.Response(status=HTTPStatus.BAD_REQUEST) event_list = await entity.async_get_events( request.app["hass"], start_date, end_date ) diff --git a/homeassistant/components/config/zwave.py b/homeassistant/components/config/zwave.py index f8a3ac0cd9f..6817b230fb8 100644 --- a/homeassistant/components/config/zwave.py +++ b/homeassistant/components/config/zwave.py @@ -7,7 +7,6 @@ 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 import homeassistant.core as ha import homeassistant.helpers.config_validation as cv @@ -52,7 +51,7 @@ class ZWaveLogView(HomeAssistantView): try: lines = int(request.query.get("lines", 0)) except ValueError: - return Response(text="Invalid datetime", status=HTTP_BAD_REQUEST) + return Response(text="Invalid datetime", status=HTTPStatus.BAD_REQUEST) hass = request.app["hass"] response = await hass.async_add_executor_job(self._get_log, hass, lines) diff --git a/homeassistant/components/doorbird/__init__.py b/homeassistant/components/doorbird/__init__.py index f1addbf477b..255b9e54636 100644 --- a/homeassistant/components/doorbird/__init__.py +++ b/homeassistant/components/doorbird/__init__.py @@ -1,4 +1,5 @@ """Support for DoorBird devices.""" +from http import HTTPStatus import logging from aiohttp import web @@ -332,7 +333,7 @@ class DoorBirdRequestView(HomeAssistantView): if device is None: return web.Response( - status=HTTP_UNAUTHORIZED, text="Invalid token provided." + status=HTTPStatus.UNAUTHORIZED, text="Invalid token provided." ) if device: diff --git a/homeassistant/components/geofency/__init__.py b/homeassistant/components/geofency/__init__.py index 6d604ec6e30..1e8e3eb1f04 100644 --- a/homeassistant/components/geofency/__init__.py +++ b/homeassistant/components/geofency/__init__.py @@ -1,4 +1,6 @@ """Support for Geofency.""" +from http import HTTPStatus + from aiohttp import web import voluptuous as vol @@ -8,7 +10,6 @@ from homeassistant.const import ( ATTR_LONGITUDE, ATTR_NAME, CONF_WEBHOOK_ID, - HTTP_UNPROCESSABLE_ENTITY, STATE_NOT_HOME, ) from homeassistant.helpers import config_entry_flow @@ -88,7 +89,9 @@ async def handle_webhook(hass, webhook_id, request): try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: - return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) + return web.Response( + text=error.error_message, status=HTTPStatus.UNPROCESSABLE_ENTITY + ) if _is_mobile_beacon(data, hass.data[DOMAIN]["beacons"]): return _set_location(hass, data, None) diff --git a/homeassistant/components/gpslogger/__init__.py b/homeassistant/components/gpslogger/__init__.py index 0c475872093..715119448b5 100644 --- a/homeassistant/components/gpslogger/__init__.py +++ b/homeassistant/components/gpslogger/__init__.py @@ -1,4 +1,6 @@ """Support for GPSLogger.""" +from http import HTTPStatus + from aiohttp import web import voluptuous as vol @@ -6,12 +8,7 @@ from homeassistant.components.device_tracker import ( ATTR_BATTERY, DOMAIN as DEVICE_TRACKER, ) -from homeassistant.const import ( - ATTR_LATITUDE, - ATTR_LONGITUDE, - CONF_WEBHOOK_ID, - HTTP_UNPROCESSABLE_ENTITY, -) +from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, CONF_WEBHOOK_ID from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send @@ -68,7 +65,9 @@ async def handle_webhook(hass, webhook_id, request): try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: - return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) + return web.Response( + text=error.error_message, status=HTTPStatus.UNPROCESSABLE_ENTITY + ) attrs = { ATTR_SPEED: data.get(ATTR_SPEED), diff --git a/homeassistant/components/hassio/addon_panel.py b/homeassistant/components/hassio/addon_panel.py index d540479d779..d6240896c84 100644 --- a/homeassistant/components/hassio/addon_panel.py +++ b/homeassistant/components/hassio/addon_panel.py @@ -1,11 +1,12 @@ """Implement the Ingress Panel feature for Hass.io Add-ons.""" import asyncio +from http import HTTPStatus import logging from aiohttp import web from homeassistant.components.http import HomeAssistantView -from homeassistant.const import ATTR_ICON, HTTP_BAD_REQUEST +from homeassistant.const import ATTR_ICON from homeassistant.core import HomeAssistant from .const import ATTR_ADMIN, ATTR_ENABLE, ATTR_PANELS, ATTR_TITLE @@ -53,7 +54,7 @@ class HassIOAddonPanel(HomeAssistantView): # Panel exists for add-on slug if addon not in panels or not panels[addon][ATTR_ENABLE]: _LOGGER.error("Panel is not enable for %s", addon) - return web.Response(status=HTTP_BAD_REQUEST) + return web.Response(status=HTTPStatus.BAD_REQUEST) data = panels[addon] # Register panel diff --git a/homeassistant/components/hassio/auth.py b/homeassistant/components/hassio/auth.py index 78925ed73fc..2d76a758096 100644 --- a/homeassistant/components/hassio/auth.py +++ b/homeassistant/components/hassio/auth.py @@ -1,4 +1,5 @@ """Implement the auth feature from Hass.io for Add-ons.""" +from http import HTTPStatus from ipaddress import ip_address import logging import os @@ -12,7 +13,6 @@ from homeassistant.auth.providers import homeassistant as auth_ha from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.const import KEY_HASS_USER from homeassistant.components.http.data_validator import RequestDataValidator -from homeassistant.const import HTTP_OK from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv @@ -83,7 +83,7 @@ class HassIOAuth(HassIOBaseAuth): except auth_ha.InvalidAuth: raise HTTPNotFound() from None - return web.Response(status=HTTP_OK) + return web.Response(status=HTTPStatus.OK) class HassIOPasswordReset(HassIOBaseAuth): @@ -113,4 +113,4 @@ class HassIOPasswordReset(HassIOBaseAuth): except auth_ha.InvalidUser as err: raise HTTPNotFound() from err - return web.Response(status=HTTP_OK) + return web.Response(status=HTTPStatus.OK) diff --git a/homeassistant/components/hassio/http.py b/homeassistant/components/hassio/http.py index fe01cbe3197..d25a65afee1 100644 --- a/homeassistant/components/hassio/http.py +++ b/homeassistant/components/hassio/http.py @@ -2,6 +2,7 @@ from __future__ import annotations import asyncio +from http import HTTPStatus import logging import os import re @@ -20,7 +21,6 @@ from aiohttp.web_exceptions import HTTPBadGateway from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.components.onboarding import async_is_onboarded -from homeassistant.const import HTTP_UNAUTHORIZED from .const import X_HASS_IS_ADMIN, X_HASS_USER_ID, X_HASSIO @@ -73,7 +73,7 @@ class HassIOView(HomeAssistantView): """Route data to Hass.io.""" hass = request.app["hass"] if _need_auth(hass, path) and not request[KEY_AUTHENTICATED]: - return web.Response(status=HTTP_UNAUTHORIZED) + return web.Response(status=HTTPStatus.UNAUTHORIZED) return await self._command_proxy(path, request) diff --git a/homeassistant/components/http/view.py b/homeassistant/components/http/view.py index 39225c918e5..adebf2bb46a 100644 --- a/homeassistant/components/http/view.py +++ b/homeassistant/components/http/view.py @@ -19,7 +19,7 @@ from aiohttp.web_urldispatcher import AbstractRoute import voluptuous as vol from homeassistant import exceptions -from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK, HTTP_SERVICE_UNAVAILABLE +from homeassistant.const import CONTENT_TYPE_JSON, HTTP_OK from homeassistant.core import Context, is_callback from homeassistant.helpers.json import JSONEncoder @@ -115,7 +115,7 @@ def request_handler_factory( async def handle(request: web.Request) -> web.StreamResponse: """Handle incoming request.""" if request.app[KEY_HASS].is_stopping: - return web.Response(status=HTTP_SERVICE_UNAVAILABLE) + return web.Response(status=HTTPStatus.SERVICE_UNAVAILABLE) authenticated = request.get(KEY_AUTHENTICATED, False) diff --git a/homeassistant/components/locative/__init__.py b/homeassistant/components/locative/__init__.py index 52cfc7900ba..548b0a2d1fe 100644 --- a/homeassistant/components/locative/__init__.py +++ b/homeassistant/components/locative/__init__.py @@ -1,6 +1,7 @@ """Support for Locative.""" from __future__ import annotations +from http import HTTPStatus import logging from aiohttp import web @@ -12,7 +13,6 @@ from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, CONF_WEBHOOK_ID, - HTTP_UNPROCESSABLE_ENTITY, STATE_NOT_HOME, ) from homeassistant.helpers import config_entry_flow @@ -68,7 +68,9 @@ async def handle_webhook(hass, webhook_id, request): try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: - return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) + return web.Response( + text=error.error_message, status=HTTPStatus.UNPROCESSABLE_ENTITY + ) device = data[ATTR_DEVICE_ID] location_name = data.get(ATTR_ID, data[ATTR_TRIGGER]).lower() @@ -105,7 +107,7 @@ async def handle_webhook(hass, webhook_id, request): _LOGGER.error("Received unidentified message from Locative: %s", direction) return web.Response( text=f"Received unidentified message: {direction}", - status=HTTP_UNPROCESSABLE_ENTITY, + status=HTTPStatus.UNPROCESSABLE_ENTITY, ) diff --git a/homeassistant/components/mailbox/__init__.py b/homeassistant/components/mailbox/__init__.py index 307bd54195f..0c473367fe9 100644 --- a/homeassistant/components/mailbox/__init__.py +++ b/homeassistant/components/mailbox/__init__.py @@ -2,6 +2,7 @@ import asyncio from contextlib import suppress from datetime import timedelta +from http import HTTPStatus import logging from aiohttp import web @@ -9,7 +10,6 @@ from aiohttp.web_exceptions import HTTPNotFound import async_timeout from homeassistant.components.http import HomeAssistantView -from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform, discovery @@ -255,8 +255,8 @@ class MailboxMediaView(MailboxView): stream = await mailbox.async_get_media(msgid) except StreamError as err: _LOGGER.error("Error getting media: %s", err) - return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) + return web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR) if stream: return web.Response(body=stream, content_type=mailbox.media_type) - return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) + return web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR) diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index 9ac350a5714..dbe7c0ef04d 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -9,6 +9,7 @@ from dataclasses import dataclass import datetime as dt import functools as ft import hashlib +from http import HTTPStatus import logging import secrets from typing import final @@ -30,7 +31,6 @@ from homeassistant.components.websocket_api.const import ( ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( - HTTP_INTERNAL_SERVER_ERROR, HTTP_NOT_FOUND, HTTP_OK, HTTP_UNAUTHORIZED, @@ -1045,7 +1045,7 @@ class MediaPlayerImageView(HomeAssistantView): ) if not authenticated: - return web.Response(status=HTTP_UNAUTHORIZED) + return web.Response(status=HTTPStatus.UNAUTHORIZED) if media_content_type and media_content_id: media_image_id = request.query.get("media_image_id") @@ -1056,7 +1056,7 @@ class MediaPlayerImageView(HomeAssistantView): data, content_type = await player.async_get_media_image() if data is None: - return web.Response(status=HTTP_INTERNAL_SERVER_ERROR) + return web.Response(status=HTTPStatus.INTERNAL_SERVER_ERROR) headers: LooseHeaders = {CACHE_CONTROL: "max-age=3600"} return web.Response(body=data, content_type=content_type, headers=headers) diff --git a/homeassistant/components/motioneye/__init__.py b/homeassistant/components/motioneye/__init__.py index 07385f24216..51f1e316a87 100644 --- a/homeassistant/components/motioneye/__init__.py +++ b/homeassistant/components/motioneye/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio from collections.abc import Callable +from http import HTTPStatus import json import logging from types import MappingProxyType @@ -38,13 +39,7 @@ from homeassistant.components.webhook import ( async_unregister as webhook_unregister, ) from homeassistant.config_entries import ConfigEntry -from homeassistant.const import ( - ATTR_DEVICE_ID, - ATTR_NAME, - CONF_URL, - CONF_WEBHOOK_ID, - HTTP_BAD_REQUEST, -) +from homeassistant.const import ATTR_DEVICE_ID, ATTR_NAME, CONF_URL, CONF_WEBHOOK_ID from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import device_registry as dr @@ -412,14 +407,14 @@ async def handle_webhook( except (json.decoder.JSONDecodeError, UnicodeDecodeError): return Response( text="Could not decode request", - status=HTTP_BAD_REQUEST, + status=HTTPStatus.BAD_REQUEST, ) for key in (ATTR_DEVICE_ID, ATTR_EVENT_TYPE): if key not in data: return Response( text=f"Missing webhook parameter: {key}", - status=HTTP_BAD_REQUEST, + status=HTTPStatus.BAD_REQUEST, ) event_type = data[ATTR_EVENT_TYPE] @@ -430,7 +425,7 @@ async def handle_webhook( if not device: return Response( text=f"Device not found: {device_id}", - status=HTTP_BAD_REQUEST, + status=HTTPStatus.BAD_REQUEST, ) hass.bus.async_fire( diff --git a/homeassistant/components/traccar/__init__.py b/homeassistant/components/traccar/__init__.py index 916b0f71169..e2605cdfd54 100644 --- a/homeassistant/components/traccar/__init__.py +++ b/homeassistant/components/traccar/__init__.py @@ -1,9 +1,11 @@ """Support for Traccar.""" +from http import HTTPStatus + from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER -from homeassistant.const import ATTR_ID, CONF_WEBHOOK_ID, HTTP_UNPROCESSABLE_ENTITY +from homeassistant.const import ATTR_ID, CONF_WEBHOOK_ID from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send @@ -61,7 +63,9 @@ async def handle_webhook(hass, webhook_id, request): try: data = WEBHOOK_SCHEMA(dict(request.query)) except vol.MultipleInvalid as error: - return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) + return web.Response( + text=error.error_message, status=HTTPStatus.UNPROCESSABLE_ENTITY + ) attrs = { ATTR_ALTITUDE: data.get(ATTR_ALTITUDE), diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index 59dfaf484b4..52b7c4aa034 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -30,7 +30,6 @@ from homeassistant.const import ( CONF_DESCRIPTION, CONF_NAME, CONF_PLATFORM, - HTTP_NOT_FOUND, PLATFORM_FORMAT, ) from homeassistant.core import HomeAssistant, callback @@ -641,7 +640,7 @@ class TextToSpeechView(HomeAssistantView): content, data = await self.tts.async_read_tts(filename) except HomeAssistantError as err: _LOGGER.error("Error on load tts: %s", err) - return web.Response(status=HTTP_NOT_FOUND) + return web.Response(status=HTTPStatus.NOT_FOUND) return web.Response(body=data, content_type=content) diff --git a/homeassistant/components/webhook/__init__.py b/homeassistant/components/webhook/__init__.py index 656f12950ea..52778600147 100644 --- a/homeassistant/components/webhook/__init__.py +++ b/homeassistant/components/webhook/__init__.py @@ -2,6 +2,7 @@ from __future__ import annotations from collections.abc import Awaitable, Callable +from http import HTTPStatus import logging import secrets @@ -10,7 +11,6 @@ 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 HomeAssistant, callback from homeassistant.helpers.network import get_url from homeassistant.loader import bind_hass @@ -99,16 +99,16 @@ async def async_handle_webhook(hass, webhook_id, request): # Limit to 64 chars to avoid flooding the log content = await request.content.read(64) _LOGGER.debug("%s", content) - return Response(status=HTTP_OK) + return Response(status=HTTPStatus.OK) try: response = await webhook["handler"](hass, webhook_id, request) if response is None: - response = Response(status=HTTP_OK) + response = Response(status=HTTPStatus.OK) return response except Exception: # pylint: disable=broad-except _LOGGER.exception("Error processing webhook %s", webhook_id) - return Response(status=HTTP_OK) + return Response(status=HTTPStatus.OK) async def async_setup(hass, config):