From 8ca127df2a0a9196fe05f6a835e6004390a77e64 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Thu, 7 Mar 2024 18:03:44 +0100 Subject: [PATCH] Use KEY_HASS [h-z] (#112610) --- homeassistant/components/hassio/auth.py | 6 +++--- homeassistant/components/hassio/http.py | 4 ++-- homeassistant/components/history/__init__.py | 4 ++-- homeassistant/components/homekit/__init__.py | 4 ++-- homeassistant/components/html5/notify.py | 8 ++++---- homeassistant/components/image/__init__.py | 4 ++-- homeassistant/components/image_upload/__init__.py | 6 +++--- homeassistant/components/intent/__init__.py | 2 +- homeassistant/components/ios/__init__.py | 4 ++-- homeassistant/components/konnected/__init__.py | 9 +++++---- homeassistant/components/logbook/rest_api.py | 4 ++-- .../components/logi_circle/config_flow.py | 4 ++-- homeassistant/components/meraki/device_tracker.py | 4 ++-- homeassistant/components/mobile_app/http_api.py | 4 ++-- homeassistant/components/mystrom/binary_sensor.py | 4 ++-- homeassistant/components/onboarding/views.py | 14 +++++++------- homeassistant/components/plex/config_flow.py | 4 ++-- homeassistant/components/plex/view.py | 4 ++-- homeassistant/components/point/config_flow.py | 4 ++-- .../components/shopping_list/__init__.py | 8 ++++---- homeassistant/components/spaceapi/__init__.py | 4 ++-- homeassistant/components/stream/core.py | 4 ++-- homeassistant/components/stt/__init__.py | 6 +++--- homeassistant/components/torque/sensor.py | 4 ++-- homeassistant/components/webhook/__init__.py | 4 ++-- homeassistant/components/websocket_api/http.py | 4 ++-- homeassistant/components/zwave_js/api.py | 5 ++--- homeassistant/helpers/config_entry_oauth2_flow.py | 2 +- tests/components/http/test_data_validator.py | 6 +++--- tests/components/http/test_view.py | 15 ++++++++------- tests/components/logi_circle/test_config_flow.py | 3 ++- 31 files changed, 82 insertions(+), 80 deletions(-) diff --git a/homeassistant/components/hassio/auth.py b/homeassistant/components/hassio/auth.py index 1e20b3da8e5..7ee9f04120a 100644 --- a/homeassistant/components/hassio/auth.py +++ b/homeassistant/components/hassio/auth.py @@ -10,7 +10,7 @@ import voluptuous as vol from homeassistant.auth.models import User from homeassistant.auth.providers import homeassistant as auth_ha -from homeassistant.components.http import KEY_HASS_USER, HomeAssistantView +from homeassistant.components.http import KEY_HASS, KEY_HASS_USER, HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv @@ -74,7 +74,7 @@ class HassIOAuth(HassIOBaseAuth): async def post(self, request: web.Request, data: dict[str, str]) -> web.Response: """Handle auth requests.""" self._check_access(request) - provider = auth_ha.async_get_provider(request.app["hass"]) + provider = auth_ha.async_get_provider(request.app[KEY_HASS]) try: await provider.async_validate_login( @@ -104,7 +104,7 @@ class HassIOPasswordReset(HassIOBaseAuth): async def post(self, request: web.Request, data: dict[str, str]) -> web.Response: """Handle password reset requests.""" self._check_access(request) - provider = auth_ha.async_get_provider(request.app["hass"]) + provider = auth_ha.async_get_provider(request.app[KEY_HASS]) try: await provider.async_change_password( diff --git a/homeassistant/components/hassio/http.py b/homeassistant/components/hassio/http.py index d86f1b7dc5c..afaa57dda9a 100644 --- a/homeassistant/components/hassio/http.py +++ b/homeassistant/components/hassio/http.py @@ -23,11 +23,11 @@ from aiohttp.web_exceptions import HTTPBadGateway from homeassistant.components.http import ( KEY_AUTHENTICATED, + KEY_HASS, KEY_HASS_USER, HomeAssistantView, ) from homeassistant.components.onboarding import async_is_onboarded -from homeassistant.core import HomeAssistant from .const import X_HASS_SOURCE @@ -116,7 +116,7 @@ class HassIOView(HomeAssistantView): if path != unquote(path): return web.Response(status=HTTPStatus.BAD_REQUEST) - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] is_admin = request[KEY_AUTHENTICATED] and request[KEY_HASS_USER].is_admin authorized = is_admin diff --git a/homeassistant/components/history/__init__.py b/homeassistant/components/history/__init__.py index 9eab92dce5c..de5f994f8c7 100644 --- a/homeassistant/components/history/__init__.py +++ b/homeassistant/components/history/__init__.py @@ -9,7 +9,7 @@ from aiohttp import web import voluptuous as vol from homeassistant.components import frontend -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.recorder import get_instance, history from homeassistant.components.recorder.util import session_scope from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE @@ -74,7 +74,7 @@ class HistoryPeriodView(HomeAssistantView): "filter_entity_id is missing", HTTPStatus.BAD_REQUEST ) - hass = request.app["hass"] + hass = request.app[KEY_HASS] for entity_id in entity_ids: if not hass.states.get(entity_id) and not valid_entity_id(entity_id): diff --git a/homeassistant/components/homekit/__init__.py b/homeassistant/components/homekit/__init__.py index afbfc784b19..76256ea1a7e 100644 --- a/homeassistant/components/homekit/__init__.py +++ b/homeassistant/components/homekit/__init__.py @@ -27,7 +27,7 @@ from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN from homeassistant.components.device_automation.trigger import ( async_validate_trigger_config, ) -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.humidifier import DOMAIN as HUMIDIFIER_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorDeviceClass from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry @@ -1163,7 +1163,7 @@ class HomeKitPairingQRView(HomeAssistantView): if not request.query_string: raise Unauthorized() entry_id, secret = request.query_string.split("-") - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] domain_data: dict[str, HomeKitEntryData] = hass.data[DOMAIN] if ( not (entry_data := domain_data.get(entry_id)) diff --git a/homeassistant/components/html5/notify.py b/homeassistant/components/html5/notify.py index d65a4c42488..a9ecabb37a8 100644 --- a/homeassistant/components/html5/notify.py +++ b/homeassistant/components/html5/notify.py @@ -19,7 +19,7 @@ import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant.components import websocket_api -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.notify import ( ATTR_DATA, ATTR_TARGET, @@ -231,7 +231,7 @@ class HTML5PushRegistrationView(HomeAssistantView): self.registrations[name] = data try: - hass = request.app["hass"] + hass = request.app[KEY_HASS] await hass.async_add_executor_job( save_json, self.json_path, self.registrations @@ -279,7 +279,7 @@ class HTML5PushRegistrationView(HomeAssistantView): reg = self.registrations.pop(found) try: - hass = request.app["hass"] + hass = request.app[KEY_HASS] await hass.async_add_executor_job( save_json, self.json_path, self.registrations @@ -388,7 +388,7 @@ class HTML5PushCallbackView(HomeAssistantView): ) event_name = f"{NOTIFY_CALLBACK_EVENT}.{event_payload[ATTR_TYPE]}" - request.app["hass"].bus.fire(event_name, event_payload) + request.app[KEY_HASS].bus.fire(event_name, event_payload) return self.json({"status": "ok", "event": event_payload[ATTR_TYPE]}) diff --git a/homeassistant/components/image/__init__.py b/homeassistant/components/image/__init__.py index 164b7048da8..9b05dcddffb 100644 --- a/homeassistant/components/image/__init__.py +++ b/homeassistant/components/image/__init__.py @@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Final, final from aiohttp import hdrs, web import httpx -from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView +from homeassistant.components.http import KEY_AUTHENTICATED, KEY_HASS, HomeAssistantView from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONTENT_TYPE_MULTIPART, EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback @@ -345,7 +345,7 @@ async def async_get_still_stream( """Write image to stream.""" event.set() - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] remove = async_track_state_change_event( hass, image_entity.entity_id, diff --git a/homeassistant/components/image_upload/__init__.py b/homeassistant/components/image_upload/__init__.py index 6faa690b4cb..d7c5052af30 100644 --- a/homeassistant/components/image_upload/__init__.py +++ b/homeassistant/components/image_upload/__init__.py @@ -13,8 +13,8 @@ from aiohttp.web_request import FileField from PIL import Image, ImageOps, UnidentifiedImageError import voluptuous as vol +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.http.static import CACHE_HEADERS -from homeassistant.components.http.view import HomeAssistantView from homeassistant.const import CONF_ID from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import collection, config_validation as cv @@ -162,7 +162,7 @@ class ImageUploadView(HomeAssistantView): request._client_max_size = MAX_SIZE # pylint: disable=protected-access data = await request.post() - item = await request.app["hass"].data[DOMAIN].async_create_item(data) + item = await request.app[KEY_HASS].data[DOMAIN].async_create_item(data) return self.json(item) @@ -200,7 +200,7 @@ class ImageServeView(HomeAssistantView): if image_info is None: raise web.HTTPNotFound() - hass = request.app["hass"] + hass = request.app[KEY_HASS] target_file = self.image_folder / image_id / f"{width}x{height}" if not target_file.is_file(): diff --git a/homeassistant/components/intent/__init__.py b/homeassistant/components/intent/__init__.py index f307208e537..7fd9fd4b712 100644 --- a/homeassistant/components/intent/__init__.py +++ b/homeassistant/components/intent/__init__.py @@ -348,7 +348,7 @@ class IntentHandleView(http.HomeAssistantView): ) async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response: """Handle intent with name/data.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[http.KEY_HASS] language = hass.config.language try: diff --git a/homeassistant/components/ios/__init__.py b/homeassistant/components/ios/__init__.py index 291f08425fa..5dcec01e138 100644 --- a/homeassistant/components/ios/__init__.py +++ b/homeassistant/components/ios/__init__.py @@ -7,7 +7,7 @@ from aiohttp import web import voluptuous as vol from homeassistant import config_entries -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.const import Platform from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError @@ -348,7 +348,7 @@ class iOSIdentifyDeviceView(HomeAssistantView): except ValueError: return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST) - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] data[ATTR_LAST_SEEN_AT] = datetime.datetime.now().isoformat() diff --git a/homeassistant/components/konnected/__init__.py b/homeassistant/components/konnected/__init__.py index fa8a35d7a64..f23f9110a74 100644 --- a/homeassistant/components/konnected/__init__.py +++ b/homeassistant/components/konnected/__init__.py @@ -11,7 +11,7 @@ import voluptuous as vol from homeassistant import config_entries from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, @@ -304,7 +304,7 @@ class KonnectedView(HomeAssistantView): async def update_sensor(self, request: Request, device_id) -> Response: """Process a put or post.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] data = hass.data[DOMAIN] auth = request.headers.get(AUTHORIZATION) @@ -376,7 +376,7 @@ class KonnectedView(HomeAssistantView): async def get(self, request: Request, device_id) -> Response: """Return the current binary state of a switch.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] data = hass.data[DOMAIN] if not (device := data[CONF_DEVICES].get(device_id)): @@ -424,7 +424,8 @@ class KonnectedView(HomeAssistantView): # Make sure entity is setup if zone_entity_id := zone.get(ATTR_ENTITY_ID): resp["state"] = self.binary_value( - hass.states.get(zone_entity_id).state, zone[CONF_ACTIVATION] + hass.states.get(zone_entity_id).state, # type: ignore[union-attr] + zone[CONF_ACTIVATION], ) return self.json(resp) diff --git a/homeassistant/components/logbook/rest_api.py b/homeassistant/components/logbook/rest_api.py index 57d0a6695c7..5ffd057670f 100644 --- a/homeassistant/components/logbook/rest_api.py +++ b/homeassistant/components/logbook/rest_api.py @@ -9,7 +9,7 @@ from typing import Any, cast from aiohttp import web import voluptuous as vol -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.recorder import get_instance from homeassistant.components.recorder.filters import Filters from homeassistant.core import HomeAssistant, callback @@ -86,7 +86,7 @@ class LogbookView(HomeAssistantView): return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST) end_day = end_day_dt - hass = request.app["hass"] + hass = request.app[KEY_HASS] context_id = request.query.get("context_id") diff --git a/homeassistant/components/logi_circle/config_flow.py b/homeassistant/components/logi_circle/config_flow.py index 6b7d6881c19..86ef530d0d3 100644 --- a/homeassistant/components/logi_circle/config_flow.py +++ b/homeassistant/components/logi_circle/config_flow.py @@ -7,7 +7,7 @@ from logi_circle import LogiCircle from logi_circle.exception import AuthorizationFailed import voluptuous as vol -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.config_entries import ConfigFlow from homeassistant.const import ( CONF_API_KEY, @@ -191,7 +191,7 @@ class LogiCircleAuthCallbackView(HomeAssistantView): async def get(self, request): """Receive authorization code.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] if "code" in request.query: hass.async_create_task( hass.config_entries.flow.async_init( diff --git a/homeassistant/components/meraki/device_tracker.py b/homeassistant/components/meraki/device_tracker.py index dae98734ae7..4149c5ac8ae 100644 --- a/homeassistant/components/meraki/device_tracker.py +++ b/homeassistant/components/meraki/device_tracker.py @@ -12,7 +12,7 @@ from homeassistant.components.device_tracker import ( AsyncSeeCallback, SourceType, ) -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType @@ -86,7 +86,7 @@ class MerakiView(HomeAssistantView): if not data["data"]["observations"]: _LOGGER.debug("No observations found") return - self._handle(request.app["hass"], data) + self._handle(request.app[KEY_HASS], data) @callback def _handle(self, hass, data): diff --git a/homeassistant/components/mobile_app/http_api.py b/homeassistant/components/mobile_app/http_api.py index 129a6a8b8d1..b48221c3c56 100644 --- a/homeassistant/components/mobile_app/http_api.py +++ b/homeassistant/components/mobile_app/http_api.py @@ -10,7 +10,7 @@ from nacl.secret import SecretBox import voluptuous as vol from homeassistant.components import cloud -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.const import ATTR_DEVICE_ID, CONF_WEBHOOK_ID from homeassistant.helpers import config_validation as cv @@ -65,7 +65,7 @@ class RegistrationsView(HomeAssistantView): ) async def post(self, request: Request, data: dict) -> Response: """Handle the POST request for registration.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] webhook_id = secrets.token_hex() diff --git a/homeassistant/components/mystrom/binary_sensor.py b/homeassistant/components/mystrom/binary_sensor.py index 91a7814df2d..33e78ca3afe 100644 --- a/homeassistant/components/mystrom/binary_sensor.py +++ b/homeassistant/components/mystrom/binary_sensor.py @@ -5,7 +5,7 @@ from http import HTTPStatus import logging from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType @@ -37,7 +37,7 @@ class MyStromView(HomeAssistantView): async def get(self, request): """Handle the GET request received from a myStrom button.""" - res = await self._handle(request.app["hass"], request.query) + res = await self._handle(request.app[KEY_HASS], request.query) return res async def _handle(self, hass, data): diff --git a/homeassistant/components/onboarding/views.py b/homeassistant/components/onboarding/views.py index 9bef34150a2..37ace1e1bab 100644 --- a/homeassistant/components/onboarding/views.py +++ b/homeassistant/components/onboarding/views.py @@ -14,7 +14,7 @@ from homeassistant.auth.const import GROUP_ID_ADMIN from homeassistant.auth.providers.homeassistant import HassAuthProvider from homeassistant.components import person from homeassistant.components.auth import indieauth -from homeassistant.components.http import KEY_HASS_REFRESH_TOKEN_ID +from homeassistant.components.http import KEY_HASS, KEY_HASS_REFRESH_TOKEN_ID from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.components.http.view import HomeAssistantView from homeassistant.core import HomeAssistant, callback @@ -85,7 +85,7 @@ class InstallationTypeOnboardingView(HomeAssistantView): if self._data["done"]: raise HTTPUnauthorized() - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] info = await async_get_system_info(hass) return self.json({"installation_type": info["installation_type"]}) @@ -136,7 +136,7 @@ class UserOnboardingView(_BaseOnboardingView): ) async def post(self, request: web.Request, data: dict[str, str]) -> web.Response: """Handle user creation, area creation.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] async with self._lock: if self._async_is_done(): @@ -190,7 +190,7 @@ class CoreConfigOnboardingView(_BaseOnboardingView): async def post(self, request: web.Request) -> web.Response: """Handle finishing core config step.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] async with self._lock: if self._async_is_done(): @@ -250,7 +250,7 @@ class IntegrationOnboardingView(_BaseOnboardingView): ) async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response: """Handle token creation.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] refresh_token_id = request[KEY_HASS_REFRESH_TOKEN_ID] async with self._lock: @@ -263,7 +263,7 @@ class IntegrationOnboardingView(_BaseOnboardingView): # Validate client ID and redirect uri if not await indieauth.verify_redirect_uri( - request.app["hass"], data["client_id"], data["redirect_uri"] + request.app[KEY_HASS], data["client_id"], data["redirect_uri"] ): return self.json_message( "invalid client id or redirect uri", HTTPStatus.BAD_REQUEST @@ -294,7 +294,7 @@ class AnalyticsOnboardingView(_BaseOnboardingView): async def post(self, request: web.Request) -> web.Response: """Handle finishing analytics step.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] async with self._lock: if self._async_is_done(): diff --git a/homeassistant/components/plex/config_flow.py b/homeassistant/components/plex/config_flow.py index 93947614955..1bc72b9e639 100644 --- a/homeassistant/components/plex/config_flow.py +++ b/homeassistant/components/plex/config_flow.py @@ -14,7 +14,7 @@ import requests.exceptions import voluptuous as vol from homeassistant.components import http -from homeassistant.components.http.view import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.media_player import DOMAIN as MP_DOMAIN from homeassistant.config_entries import ( SOURCE_INTEGRATION_DISCOVERY, @@ -443,7 +443,7 @@ class PlexAuthorizationCallbackView(HomeAssistantView): async def get(self, request): """Receive authorization confirmation.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] await hass.config_entries.flow.async_configure( flow_id=request.query["flow_id"], user_input=None ) diff --git a/homeassistant/components/plex/view.py b/homeassistant/components/plex/view.py index ba883883ddc..49c0af1c48e 100644 --- a/homeassistant/components/plex/view.py +++ b/homeassistant/components/plex/view.py @@ -8,7 +8,7 @@ from aiohttp import web from aiohttp.hdrs import CACHE_CONTROL from aiohttp.typedefs import LooseHeaders -from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView +from homeassistant.components.http import KEY_AUTHENTICATED, KEY_HASS, HomeAssistantView from homeassistant.components.media_player import async_fetch_image from .const import SERVERS @@ -33,7 +33,7 @@ class PlexImageView(HomeAssistantView): if not request[KEY_AUTHENTICATED]: return web.Response(status=HTTPStatus.UNAUTHORIZED) - hass = request.app["hass"] + hass = request.app[KEY_HASS] if (server := get_plex_data(hass)[SERVERS].get(server_id)) is None: return web.Response(status=HTTPStatus.NOT_FOUND) diff --git a/homeassistant/components/point/config_flow.py b/homeassistant/components/point/config_flow.py index b9254aa7d4d..b88862758af 100644 --- a/homeassistant/components/point/config_flow.py +++ b/homeassistant/components/point/config_flow.py @@ -6,7 +6,7 @@ import logging from pypoint import PointSession import voluptuous as vol -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.config_entries import ConfigFlow from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET from homeassistant.core import callback @@ -179,7 +179,7 @@ class MinutAuthCallbackView(HomeAssistantView): @staticmethod async def get(request): """Receive authorization code.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] if "code" in request.query: hass.async_create_task( hass.config_entries.flow.async_init( diff --git a/homeassistant/components/shopping_list/__init__.py b/homeassistant/components/shopping_list/__init__.py index e030f15d26e..a250adcf5f2 100644 --- a/homeassistant/components/shopping_list/__init__.py +++ b/homeassistant/components/shopping_list/__init__.py @@ -414,7 +414,7 @@ class ShoppingListView(http.HomeAssistantView): @callback def get(self, request: web.Request) -> web.Response: """Retrieve shopping list items.""" - return self.json(request.app["hass"].data[DOMAIN].items) + return self.json(request.app[http.KEY_HASS].data[DOMAIN].items) class UpdateShoppingListItemView(http.HomeAssistantView): @@ -426,7 +426,7 @@ class UpdateShoppingListItemView(http.HomeAssistantView): async def post(self, request: web.Request, item_id: str) -> web.Response: """Update a shopping list item.""" data = await request.json() - hass: HomeAssistant = request.app["hass"] + hass = request.app[http.KEY_HASS] try: item = await hass.data[DOMAIN].async_update(item_id, data) @@ -446,7 +446,7 @@ class CreateShoppingListItemView(http.HomeAssistantView): @RequestDataValidator(vol.Schema({vol.Required("name"): str})) async def post(self, request: web.Request, data: dict[str, str]) -> web.Response: """Create a new shopping list item.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[http.KEY_HASS] item = await hass.data[DOMAIN].async_add(data["name"]) return self.json(item) @@ -459,7 +459,7 @@ class ClearCompletedItemsView(http.HomeAssistantView): async def post(self, request: web.Request) -> web.Response: """Retrieve if API is running.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[http.KEY_HASS] await hass.data[DOMAIN].async_clear_completed() return self.json_message("Cleared completed items.") diff --git a/homeassistant/components/spaceapi/__init__.py b/homeassistant/components/spaceapi/__init__.py index 1a25986a243..bcbd2a258ac 100644 --- a/homeassistant/components/spaceapi/__init__.py +++ b/homeassistant/components/spaceapi/__init__.py @@ -3,7 +3,7 @@ from contextlib import suppress import voluptuous as vol -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_ICON, @@ -266,7 +266,7 @@ class APISpaceApiView(HomeAssistantView): @ha.callback def get(self, request): """Get SpaceAPI data.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] spaceapi = dict(hass.data[DATA_SPACEAPI]) is_sensors = spaceapi.get("sensors") diff --git a/homeassistant/components/stream/core.py b/homeassistant/components/stream/core.py index 1d2957b35a3..b7f27367d77 100644 --- a/homeassistant/components/stream/core.py +++ b/homeassistant/components/stream/core.py @@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any from aiohttp import web import numpy as np -from homeassistant.components.http.view import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers.event import async_call_later from homeassistant.util.decorator import Registry @@ -380,7 +380,7 @@ class StreamView(HomeAssistantView): self, request: web.Request, token: str, sequence: str = "", part_num: str = "" ) -> web.StreamResponse: """Start a GET request.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] stream = next( (s for s in hass.data[DOMAIN][ATTR_STREAMS] if s.access_token == token), diff --git a/homeassistant/components/stt/__init__.py b/homeassistant/components/stt/__init__.py index c856a4817c9..45bdc3a63c7 100644 --- a/homeassistant/components/stt/__init__.py +++ b/homeassistant/components/stt/__init__.py @@ -18,7 +18,7 @@ from aiohttp.web_exceptions import ( import voluptuous as vol from homeassistant.components import websocket_api -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant, callback @@ -250,7 +250,7 @@ class SpeechToTextView(HomeAssistantView): async def post(self, request: web.Request, provider: str) -> web.Response: """Convert Speech (audio) to text.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] provider_entity: SpeechToTextEntity | None = None if ( not (provider_entity := async_get_speech_to_text_entity(hass, provider)) @@ -290,7 +290,7 @@ class SpeechToTextView(HomeAssistantView): async def get(self, request: web.Request, provider: str) -> web.Response: """Return provider specific audio information.""" - hass: HomeAssistant = request.app["hass"] + hass = request.app[KEY_HASS] if ( not (provider_entity := async_get_speech_to_text_entity(hass, provider)) and provider not in self.providers diff --git a/homeassistant/components/torque/sensor.py b/homeassistant/components/torque/sensor.py index a2e1e35d2ae..0ac91589c35 100644 --- a/homeassistant/components/torque/sensor.py +++ b/homeassistant/components/torque/sensor.py @@ -5,7 +5,7 @@ import re import voluptuous as vol -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_EMAIL, CONF_NAME, DEGREE from homeassistant.core import HomeAssistant, callback @@ -74,7 +74,7 @@ class TorqueReceiveDataView(HomeAssistantView): @callback def get(self, request): """Handle Torque data request.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] data = request.query if self.email is not None and self.email != data[SENSOR_EMAIL_FIELD]: diff --git a/homeassistant/components/webhook/__init__.py b/homeassistant/components/webhook/__init__.py index 00b27fdb647..8d73e444279 100644 --- a/homeassistant/components/webhook/__init__.py +++ b/homeassistant/components/webhook/__init__.py @@ -14,7 +14,7 @@ from aiohttp.web import Request, Response import voluptuous as vol from homeassistant.components import websocket_api -from homeassistant.components.http.view import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.network import get_url, is_cloud_connection @@ -202,7 +202,7 @@ class WebhookView(HomeAssistantView): async def _handle(self, request: Request, webhook_id: str) -> Response: """Handle webhook call.""" _LOGGER.debug("Handling webhook %s payload for %s", request.method, webhook_id) - hass = request.app["hass"] + hass = request.app[KEY_HASS] return await async_handle_webhook(hass, webhook_id, request) get = _handle diff --git a/homeassistant/components/websocket_api/http.py b/homeassistant/components/websocket_api/http.py index 82c54a08136..06b9c0c4bfa 100644 --- a/homeassistant/components/websocket_api/http.py +++ b/homeassistant/components/websocket_api/http.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any, Final from aiohttp import WSMsgType, web -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_send @@ -49,7 +49,7 @@ class WebsocketAPIView(HomeAssistantView): async def get(self, request: web.Request) -> web.WebSocketResponse: """Handle an incoming websocket connection.""" - return await WebSocketHandler(request.app["hass"], request).async_handle() + return await WebSocketHandler(request.app[KEY_HASS], request).async_handle() class WebSocketAdapter(logging.LoggerAdapter): diff --git a/homeassistant/components/zwave_js/api.py b/homeassistant/components/zwave_js/api.py index 5aa27ada977..068ce348caf 100644 --- a/homeassistant/components/zwave_js/api.py +++ b/homeassistant/components/zwave_js/api.py @@ -55,8 +55,7 @@ from zwave_js_server.model.utils import ( from zwave_js_server.util.node import async_set_config_parameter from homeassistant.components import websocket_api -from homeassistant.components.http import require_admin -from homeassistant.components.http.view import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin from homeassistant.components.websocket_api import ( ERR_INVALID_FORMAT, ERR_NOT_FOUND, @@ -2196,7 +2195,7 @@ class FirmwareUploadView(HomeAssistantView): @require_admin async def post(self, request: web.Request, device_id: str) -> web.Response: """Handle upload.""" - hass = request.app["hass"] + hass = request.app[KEY_HASS] try: node = async_get_node_from_device_id(hass, device_id, self._dev_reg) diff --git a/homeassistant/helpers/config_entry_oauth2_flow.py b/homeassistant/helpers/config_entry_oauth2_flow.py index 337e6ca92b6..dcc0265ab61 100644 --- a/homeassistant/helpers/config_entry_oauth2_flow.py +++ b/homeassistant/helpers/config_entry_oauth2_flow.py @@ -455,7 +455,7 @@ class OAuth2AuthorizeCallbackView(http.HomeAssistantView): if "state" not in request.query: return web.Response(text="Missing state parameter") - hass = request.app["hass"] + hass = request.app[http.KEY_HASS] state = _decode_jwt(hass, request.query["state"]) diff --git a/tests/components/http/test_data_validator.py b/tests/components/http/test_data_validator.py index ecff4370999..c9f1ed46157 100644 --- a/tests/components/http/test_data_validator.py +++ b/tests/components/http/test_data_validator.py @@ -5,7 +5,7 @@ from unittest.mock import Mock from aiohttp import web import voluptuous as vol -from homeassistant.components.http import HomeAssistantView +from homeassistant.components.http import KEY_HASS, HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator from tests.typing import ClientSessionGenerator @@ -14,7 +14,7 @@ from tests.typing import ClientSessionGenerator async def get_client(aiohttp_client, validator): """Generate a client that hits a view decorated with validator.""" app = web.Application() - app["hass"] = Mock(is_stopping=False) + app[KEY_HASS] = Mock(is_stopping=False) app["allow_configured_cors"] = lambda _: None class TestView(HomeAssistantView): @@ -27,7 +27,7 @@ async def get_client(aiohttp_client, validator): """Test method.""" return b"" - TestView().register(app["hass"], app, app.router) + TestView().register(app[KEY_HASS], app, app.router) client = await aiohttp_client(app) return client diff --git a/tests/components/http/test_view.py b/tests/components/http/test_view.py index e52413d5225..6f8386ae36f 100644 --- a/tests/components/http/test_view.py +++ b/tests/components/http/test_view.py @@ -12,6 +12,7 @@ from aiohttp.web_exceptions import ( import pytest import voluptuous as vol +from homeassistant.components.http import KEY_HASS from homeassistant.components.http.view import ( HomeAssistantView, request_handler_factory, @@ -22,13 +23,13 @@ from homeassistant.exceptions import ServiceNotFound, Unauthorized @pytest.fixture def mock_request() -> Mock: """Mock a request.""" - return Mock(app={"hass": Mock(is_stopping=False)}, match_info={}) + return Mock(app={KEY_HASS: Mock(is_stopping=False)}, match_info={}) @pytest.fixture def mock_request_with_stopping() -> Mock: """Mock a request.""" - return Mock(app={"hass": Mock(is_stopping=True)}, match_info={}) + return Mock(app={KEY_HASS: Mock(is_stopping=True)}, match_info={}) async def test_invalid_json(caplog: pytest.LogCaptureFixture) -> None: @@ -52,7 +53,7 @@ async def test_handling_unauthorized(mock_request: Mock) -> None: """Test handling unauth exceptions.""" with pytest.raises(HTTPUnauthorized): await request_handler_factory( - mock_request.app["hass"], + mock_request.app[KEY_HASS], Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized), )(mock_request) @@ -62,7 +63,7 @@ async def test_handling_invalid_data(mock_request: Mock) -> None: """Test handling unauth exceptions.""" with pytest.raises(HTTPBadRequest): await request_handler_factory( - mock_request.app["hass"], + mock_request.app[KEY_HASS], Mock(requires_auth=False), AsyncMock(side_effect=vol.Invalid("yo")), )(mock_request) @@ -72,7 +73,7 @@ async def test_handling_service_not_found(mock_request: Mock) -> None: """Test handling unauth exceptions.""" with pytest.raises(HTTPInternalServerError): await request_handler_factory( - mock_request.app["hass"], + mock_request.app[KEY_HASS], Mock(requires_auth=False), AsyncMock(side_effect=ServiceNotFound("test", "test")), )(mock_request) @@ -81,7 +82,7 @@ async def test_handling_service_not_found(mock_request: Mock) -> None: async def test_not_running(mock_request_with_stopping: Mock) -> None: """Test we get a 503 when not running.""" response = await request_handler_factory( - mock_request_with_stopping.app["hass"], + mock_request_with_stopping.app[KEY_HASS], Mock(requires_auth=False), AsyncMock(side_effect=Unauthorized), )(mock_request_with_stopping) @@ -92,7 +93,7 @@ async def test_invalid_handler(mock_request: Mock) -> None: """Test an invalid handler.""" with pytest.raises(TypeError): await request_handler_factory( - mock_request.app["hass"], + mock_request.app[KEY_HASS], Mock(requires_auth=False), AsyncMock(return_value=["not valid"]), )(mock_request) diff --git a/tests/components/logi_circle/test_config_flow.py b/tests/components/logi_circle/test_config_flow.py index 830760040e0..2c1642aefba 100644 --- a/tests/components/logi_circle/test_config_flow.py +++ b/tests/components/logi_circle/test_config_flow.py @@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, Mock, patch import pytest from homeassistant import config_entries, data_entry_flow +from homeassistant.components.http import KEY_HASS from homeassistant.components.logi_circle import config_flow from homeassistant.components.logi_circle.config_flow import ( DOMAIN, @@ -23,7 +24,7 @@ class MockRequest: def __init__(self, hass, query): """Init request object.""" - self.app = {"hass": hass} + self.app = {KEY_HASS: hass} self.query = query