Use KEY_HASS [h-z] (#112610)

This commit is contained in:
Marc Mueller 2024-03-07 18:03:44 +01:00 committed by GitHub
parent 714777e853
commit 8ca127df2a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 82 additions and 80 deletions

View file

@ -10,7 +10,7 @@ import voluptuous as vol
from homeassistant.auth.models import User from homeassistant.auth.models import User
from homeassistant.auth.providers import homeassistant as auth_ha 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.components.http.data_validator import RequestDataValidator
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv 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: async def post(self, request: web.Request, data: dict[str, str]) -> web.Response:
"""Handle auth requests.""" """Handle auth requests."""
self._check_access(request) self._check_access(request)
provider = auth_ha.async_get_provider(request.app["hass"]) provider = auth_ha.async_get_provider(request.app[KEY_HASS])
try: try:
await provider.async_validate_login( 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: async def post(self, request: web.Request, data: dict[str, str]) -> web.Response:
"""Handle password reset requests.""" """Handle password reset requests."""
self._check_access(request) self._check_access(request)
provider = auth_ha.async_get_provider(request.app["hass"]) provider = auth_ha.async_get_provider(request.app[KEY_HASS])
try: try:
await provider.async_change_password( await provider.async_change_password(

View file

@ -23,11 +23,11 @@ from aiohttp.web_exceptions import HTTPBadGateway
from homeassistant.components.http import ( from homeassistant.components.http import (
KEY_AUTHENTICATED, KEY_AUTHENTICATED,
KEY_HASS,
KEY_HASS_USER, KEY_HASS_USER,
HomeAssistantView, HomeAssistantView,
) )
from homeassistant.components.onboarding import async_is_onboarded from homeassistant.components.onboarding import async_is_onboarded
from homeassistant.core import HomeAssistant
from .const import X_HASS_SOURCE from .const import X_HASS_SOURCE
@ -116,7 +116,7 @@ class HassIOView(HomeAssistantView):
if path != unquote(path): if path != unquote(path):
return web.Response(status=HTTPStatus.BAD_REQUEST) 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 is_admin = request[KEY_AUTHENTICATED] and request[KEY_HASS_USER].is_admin
authorized = is_admin authorized = is_admin

View file

@ -9,7 +9,7 @@ from aiohttp import web
import voluptuous as vol import voluptuous as vol
from homeassistant.components import frontend 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 import get_instance, history
from homeassistant.components.recorder.util import session_scope from homeassistant.components.recorder.util import session_scope
from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE
@ -74,7 +74,7 @@ class HistoryPeriodView(HomeAssistantView):
"filter_entity_id is missing", HTTPStatus.BAD_REQUEST "filter_entity_id is missing", HTTPStatus.BAD_REQUEST
) )
hass = request.app["hass"] hass = request.app[KEY_HASS]
for entity_id in entity_ids: for entity_id in entity_ids:
if not hass.states.get(entity_id) and not valid_entity_id(entity_id): if not hass.states.get(entity_id) and not valid_entity_id(entity_id):

View file

@ -27,7 +27,7 @@ from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN
from homeassistant.components.device_automation.trigger import ( from homeassistant.components.device_automation.trigger import (
async_validate_trigger_config, 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.humidifier import DOMAIN as HUMIDIFIER_DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorDeviceClass from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN, SensorDeviceClass
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
@ -1163,7 +1163,7 @@ class HomeKitPairingQRView(HomeAssistantView):
if not request.query_string: if not request.query_string:
raise Unauthorized() raise Unauthorized()
entry_id, secret = request.query_string.split("-") 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] domain_data: dict[str, HomeKitEntryData] = hass.data[DOMAIN]
if ( if (
not (entry_data := domain_data.get(entry_id)) not (entry_data := domain_data.get(entry_id))

View file

@ -19,7 +19,7 @@ import voluptuous as vol
from voluptuous.humanize import humanize_error from voluptuous.humanize import humanize_error
from homeassistant.components import websocket_api 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 ( from homeassistant.components.notify import (
ATTR_DATA, ATTR_DATA,
ATTR_TARGET, ATTR_TARGET,
@ -231,7 +231,7 @@ class HTML5PushRegistrationView(HomeAssistantView):
self.registrations[name] = data self.registrations[name] = data
try: try:
hass = request.app["hass"] hass = request.app[KEY_HASS]
await hass.async_add_executor_job( await hass.async_add_executor_job(
save_json, self.json_path, self.registrations save_json, self.json_path, self.registrations
@ -279,7 +279,7 @@ class HTML5PushRegistrationView(HomeAssistantView):
reg = self.registrations.pop(found) reg = self.registrations.pop(found)
try: try:
hass = request.app["hass"] hass = request.app[KEY_HASS]
await hass.async_add_executor_job( await hass.async_add_executor_job(
save_json, self.json_path, self.registrations save_json, self.json_path, self.registrations
@ -388,7 +388,7 @@ class HTML5PushCallbackView(HomeAssistantView):
) )
event_name = f"{NOTIFY_CALLBACK_EVENT}.{event_payload[ATTR_TYPE]}" 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]}) return self.json({"status": "ok", "event": event_payload[ATTR_TYPE]})

View file

@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Final, final
from aiohttp import hdrs, web from aiohttp import hdrs, web
import httpx 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.config_entries import ConfigEntry
from homeassistant.const import CONTENT_TYPE_MULTIPART, EVENT_HOMEASSISTANT_STOP from homeassistant.const import CONTENT_TYPE_MULTIPART, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
@ -345,7 +345,7 @@ async def async_get_still_stream(
"""Write image to stream.""" """Write image to stream."""
event.set() event.set()
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
remove = async_track_state_change_event( remove = async_track_state_change_event(
hass, hass,
image_entity.entity_id, image_entity.entity_id,

View file

@ -13,8 +13,8 @@ from aiohttp.web_request import FileField
from PIL import Image, ImageOps, UnidentifiedImageError from PIL import Image, ImageOps, UnidentifiedImageError
import voluptuous as vol import voluptuous as vol
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.components.http.static import CACHE_HEADERS from homeassistant.components.http.static import CACHE_HEADERS
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.const import CONF_ID from homeassistant.const import CONF_ID
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import collection, config_validation as cv 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 request._client_max_size = MAX_SIZE # pylint: disable=protected-access
data = await request.post() 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) return self.json(item)
@ -200,7 +200,7 @@ class ImageServeView(HomeAssistantView):
if image_info is None: if image_info is None:
raise web.HTTPNotFound() raise web.HTTPNotFound()
hass = request.app["hass"] hass = request.app[KEY_HASS]
target_file = self.image_folder / image_id / f"{width}x{height}" target_file = self.image_folder / image_id / f"{width}x{height}"
if not target_file.is_file(): if not target_file.is_file():

View file

@ -348,7 +348,7 @@ class IntentHandleView(http.HomeAssistantView):
) )
async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response: async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response:
"""Handle intent with name/data.""" """Handle intent with name/data."""
hass: HomeAssistant = request.app["hass"] hass = request.app[http.KEY_HASS]
language = hass.config.language language = hass.config.language
try: try:

View file

@ -7,7 +7,7 @@ from aiohttp import web
import voluptuous as vol 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 KEY_HASS, HomeAssistantView
from homeassistant.const import Platform from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
@ -348,7 +348,7 @@ class iOSIdentifyDeviceView(HomeAssistantView):
except ValueError: except ValueError:
return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST) 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() data[ATTR_LAST_SEEN_AT] = datetime.datetime.now().isoformat()

View file

@ -11,7 +11,7 @@ import voluptuous as vol
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA 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.config_entries import ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_ENTITY_ID,
@ -304,7 +304,7 @@ class KonnectedView(HomeAssistantView):
async def update_sensor(self, request: Request, device_id) -> Response: async def update_sensor(self, request: Request, device_id) -> Response:
"""Process a put or post.""" """Process a put or post."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
data = hass.data[DOMAIN] data = hass.data[DOMAIN]
auth = request.headers.get(AUTHORIZATION) auth = request.headers.get(AUTHORIZATION)
@ -376,7 +376,7 @@ class KonnectedView(HomeAssistantView):
async def get(self, request: Request, device_id) -> Response: async def get(self, request: Request, device_id) -> Response:
"""Return the current binary state of a switch.""" """Return the current binary state of a switch."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
data = hass.data[DOMAIN] data = hass.data[DOMAIN]
if not (device := data[CONF_DEVICES].get(device_id)): if not (device := data[CONF_DEVICES].get(device_id)):
@ -424,7 +424,8 @@ class KonnectedView(HomeAssistantView):
# Make sure entity is setup # Make sure entity is setup
if zone_entity_id := zone.get(ATTR_ENTITY_ID): if zone_entity_id := zone.get(ATTR_ENTITY_ID):
resp["state"] = self.binary_value( 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) return self.json(resp)

View file

@ -9,7 +9,7 @@ from typing import Any, cast
from aiohttp import web from aiohttp import web
import voluptuous as vol 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 import get_instance
from homeassistant.components.recorder.filters import Filters from homeassistant.components.recorder.filters import Filters
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
@ -86,7 +86,7 @@ class LogbookView(HomeAssistantView):
return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST) return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST)
end_day = end_day_dt end_day = end_day_dt
hass = request.app["hass"] hass = request.app[KEY_HASS]
context_id = request.query.get("context_id") context_id = request.query.get("context_id")

View file

@ -7,7 +7,7 @@ from logi_circle import LogiCircle
from logi_circle.exception import AuthorizationFailed from logi_circle.exception import AuthorizationFailed
import voluptuous as vol 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.config_entries import ConfigFlow
from homeassistant.const import ( from homeassistant.const import (
CONF_API_KEY, CONF_API_KEY,
@ -191,7 +191,7 @@ class LogiCircleAuthCallbackView(HomeAssistantView):
async def get(self, request): async def get(self, request):
"""Receive authorization code.""" """Receive authorization code."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
if "code" in request.query: if "code" in request.query:
hass.async_create_task( hass.async_create_task(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(

View file

@ -12,7 +12,7 @@ from homeassistant.components.device_tracker import (
AsyncSeeCallback, AsyncSeeCallback,
SourceType, SourceType,
) )
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
@ -86,7 +86,7 @@ class MerakiView(HomeAssistantView):
if not data["data"]["observations"]: if not data["data"]["observations"]:
_LOGGER.debug("No observations found") _LOGGER.debug("No observations found")
return return
self._handle(request.app["hass"], data) self._handle(request.app[KEY_HASS], data)
@callback @callback
def _handle(self, hass, data): def _handle(self, hass, data):

View file

@ -10,7 +10,7 @@ from nacl.secret import SecretBox
import voluptuous as vol import voluptuous as vol
from homeassistant.components import cloud 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.components.http.data_validator import RequestDataValidator
from homeassistant.const import ATTR_DEVICE_ID, CONF_WEBHOOK_ID from homeassistant.const import ATTR_DEVICE_ID, CONF_WEBHOOK_ID
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
@ -65,7 +65,7 @@ class RegistrationsView(HomeAssistantView):
) )
async def post(self, request: Request, data: dict) -> Response: async def post(self, request: Request, data: dict) -> Response:
"""Handle the POST request for registration.""" """Handle the POST request for registration."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
webhook_id = secrets.token_hex() webhook_id = secrets.token_hex()

View file

@ -5,7 +5,7 @@ from http import HTTPStatus
import logging import logging
from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity 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.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
@ -37,7 +37,7 @@ class MyStromView(HomeAssistantView):
async def get(self, request): async def get(self, request):
"""Handle the GET request received from a myStrom button.""" """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 return res
async def _handle(self, hass, data): async def _handle(self, hass, data):

View file

@ -14,7 +14,7 @@ from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.auth.providers.homeassistant import HassAuthProvider from homeassistant.auth.providers.homeassistant import HassAuthProvider
from homeassistant.components import person from homeassistant.components import person
from homeassistant.components.auth import indieauth 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.data_validator import RequestDataValidator
from homeassistant.components.http.view import HomeAssistantView from homeassistant.components.http.view import HomeAssistantView
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
@ -85,7 +85,7 @@ class InstallationTypeOnboardingView(HomeAssistantView):
if self._data["done"]: if self._data["done"]:
raise HTTPUnauthorized() raise HTTPUnauthorized()
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
info = await async_get_system_info(hass) info = await async_get_system_info(hass)
return self.json({"installation_type": info["installation_type"]}) 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: async def post(self, request: web.Request, data: dict[str, str]) -> web.Response:
"""Handle user creation, area creation.""" """Handle user creation, area creation."""
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
async with self._lock: async with self._lock:
if self._async_is_done(): if self._async_is_done():
@ -190,7 +190,7 @@ class CoreConfigOnboardingView(_BaseOnboardingView):
async def post(self, request: web.Request) -> web.Response: async def post(self, request: web.Request) -> web.Response:
"""Handle finishing core config step.""" """Handle finishing core config step."""
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
async with self._lock: async with self._lock:
if self._async_is_done(): 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: async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response:
"""Handle token creation.""" """Handle token creation."""
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
refresh_token_id = request[KEY_HASS_REFRESH_TOKEN_ID] refresh_token_id = request[KEY_HASS_REFRESH_TOKEN_ID]
async with self._lock: async with self._lock:
@ -263,7 +263,7 @@ class IntegrationOnboardingView(_BaseOnboardingView):
# Validate client ID and redirect uri # Validate client ID and redirect uri
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[KEY_HASS], data["client_id"], data["redirect_uri"]
): ):
return self.json_message( return self.json_message(
"invalid client id or redirect uri", HTTPStatus.BAD_REQUEST "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: async def post(self, request: web.Request) -> web.Response:
"""Handle finishing analytics step.""" """Handle finishing analytics step."""
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
async with self._lock: async with self._lock:
if self._async_is_done(): if self._async_is_done():

View file

@ -14,7 +14,7 @@ import requests.exceptions
import voluptuous as vol import voluptuous as vol
from homeassistant.components import http 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.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.config_entries import ( from homeassistant.config_entries import (
SOURCE_INTEGRATION_DISCOVERY, SOURCE_INTEGRATION_DISCOVERY,
@ -443,7 +443,7 @@ class PlexAuthorizationCallbackView(HomeAssistantView):
async def get(self, request): async def get(self, request):
"""Receive authorization confirmation.""" """Receive authorization confirmation."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
await hass.config_entries.flow.async_configure( await hass.config_entries.flow.async_configure(
flow_id=request.query["flow_id"], user_input=None flow_id=request.query["flow_id"], user_input=None
) )

View file

@ -8,7 +8,7 @@ from aiohttp import web
from aiohttp.hdrs import CACHE_CONTROL from aiohttp.hdrs import CACHE_CONTROL
from aiohttp.typedefs import LooseHeaders 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 homeassistant.components.media_player import async_fetch_image
from .const import SERVERS from .const import SERVERS
@ -33,7 +33,7 @@ class PlexImageView(HomeAssistantView):
if not request[KEY_AUTHENTICATED]: if not request[KEY_AUTHENTICATED]:
return web.Response(status=HTTPStatus.UNAUTHORIZED) 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: if (server := get_plex_data(hass)[SERVERS].get(server_id)) is None:
return web.Response(status=HTTPStatus.NOT_FOUND) return web.Response(status=HTTPStatus.NOT_FOUND)

View file

@ -6,7 +6,7 @@ import logging
from pypoint import PointSession from pypoint import PointSession
import voluptuous as vol 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.config_entries import ConfigFlow
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import callback from homeassistant.core import callback
@ -179,7 +179,7 @@ class MinutAuthCallbackView(HomeAssistantView):
@staticmethod @staticmethod
async def get(request): async def get(request):
"""Receive authorization code.""" """Receive authorization code."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
if "code" in request.query: if "code" in request.query:
hass.async_create_task( hass.async_create_task(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(

View file

@ -414,7 +414,7 @@ class ShoppingListView(http.HomeAssistantView):
@callback @callback
def get(self, request: web.Request) -> web.Response: def get(self, request: web.Request) -> web.Response:
"""Retrieve shopping list items.""" """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): class UpdateShoppingListItemView(http.HomeAssistantView):
@ -426,7 +426,7 @@ class UpdateShoppingListItemView(http.HomeAssistantView):
async def post(self, request: web.Request, item_id: str) -> web.Response: async def post(self, request: web.Request, item_id: str) -> web.Response:
"""Update a shopping list item.""" """Update a shopping list item."""
data = await request.json() data = await request.json()
hass: HomeAssistant = request.app["hass"] hass = request.app[http.KEY_HASS]
try: try:
item = await hass.data[DOMAIN].async_update(item_id, data) 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})) @RequestDataValidator(vol.Schema({vol.Required("name"): str}))
async def post(self, request: web.Request, data: dict[str, str]) -> web.Response: async def post(self, request: web.Request, data: dict[str, str]) -> web.Response:
"""Create a new shopping list item.""" """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"]) item = await hass.data[DOMAIN].async_add(data["name"])
return self.json(item) return self.json(item)
@ -459,7 +459,7 @@ class ClearCompletedItemsView(http.HomeAssistantView):
async def post(self, request: web.Request) -> web.Response: async def post(self, request: web.Request) -> web.Response:
"""Retrieve if API is running.""" """Retrieve if API is running."""
hass: HomeAssistant = request.app["hass"] hass = request.app[http.KEY_HASS]
await hass.data[DOMAIN].async_clear_completed() await hass.data[DOMAIN].async_clear_completed()
return self.json_message("Cleared completed items.") return self.json_message("Cleared completed items.")

View file

@ -3,7 +3,7 @@ from contextlib import suppress
import voluptuous as vol import voluptuous as vol
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.const import ( from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_ENTITY_ID,
ATTR_ICON, ATTR_ICON,
@ -266,7 +266,7 @@ class APISpaceApiView(HomeAssistantView):
@ha.callback @ha.callback
def get(self, request): def get(self, request):
"""Get SpaceAPI data.""" """Get SpaceAPI data."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
spaceapi = dict(hass.data[DATA_SPACEAPI]) spaceapi = dict(hass.data[DATA_SPACEAPI])
is_sensors = spaceapi.get("sensors") is_sensors = spaceapi.get("sensors")

View file

@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any
from aiohttp import web from aiohttp import web
import numpy as np 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.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.helpers.event import async_call_later from homeassistant.helpers.event import async_call_later
from homeassistant.util.decorator import Registry from homeassistant.util.decorator import Registry
@ -380,7 +380,7 @@ class StreamView(HomeAssistantView):
self, request: web.Request, token: str, sequence: str = "", part_num: str = "" self, request: web.Request, token: str, sequence: str = "", part_num: str = ""
) -> web.StreamResponse: ) -> web.StreamResponse:
"""Start a GET request.""" """Start a GET request."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
stream = next( stream = next(
(s for s in hass.data[DOMAIN][ATTR_STREAMS] if s.access_token == token), (s for s in hass.data[DOMAIN][ATTR_STREAMS] if s.access_token == token),

View file

@ -18,7 +18,7 @@ from aiohttp.web_exceptions import (
import voluptuous as vol import voluptuous as vol
from homeassistant.components import websocket_api 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.config_entries import ConfigEntry
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
@ -250,7 +250,7 @@ class SpeechToTextView(HomeAssistantView):
async def post(self, request: web.Request, provider: str) -> web.Response: async def post(self, request: web.Request, provider: str) -> web.Response:
"""Convert Speech (audio) to text.""" """Convert Speech (audio) to text."""
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
provider_entity: SpeechToTextEntity | None = None provider_entity: SpeechToTextEntity | None = None
if ( if (
not (provider_entity := async_get_speech_to_text_entity(hass, provider)) 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: async def get(self, request: web.Request, provider: str) -> web.Response:
"""Return provider specific audio information.""" """Return provider specific audio information."""
hass: HomeAssistant = request.app["hass"] hass = request.app[KEY_HASS]
if ( if (
not (provider_entity := async_get_speech_to_text_entity(hass, provider)) not (provider_entity := async_get_speech_to_text_entity(hass, provider))
and provider not in self.providers and provider not in self.providers

View file

@ -5,7 +5,7 @@ import re
import voluptuous as vol 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.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_EMAIL, CONF_NAME, DEGREE from homeassistant.const import CONF_EMAIL, CONF_NAME, DEGREE
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
@ -74,7 +74,7 @@ class TorqueReceiveDataView(HomeAssistantView):
@callback @callback
def get(self, request): def get(self, request):
"""Handle Torque data request.""" """Handle Torque data request."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
data = request.query data = request.query
if self.email is not None and self.email != data[SENSOR_EMAIL_FIELD]: if self.email is not None and self.email != data[SENSOR_EMAIL_FIELD]:

View file

@ -14,7 +14,7 @@ from aiohttp.web import Request, Response
import voluptuous as vol import voluptuous as vol
from homeassistant.components import websocket_api 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.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.network import get_url, is_cloud_connection 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: async def _handle(self, request: Request, webhook_id: str) -> Response:
"""Handle webhook call.""" """Handle webhook call."""
_LOGGER.debug("Handling webhook %s payload for %s", request.method, webhook_id) _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) return await async_handle_webhook(hass, webhook_id, request)
get = _handle get = _handle

View file

@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any, Final
from aiohttp import WSMsgType, web 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.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
@ -49,7 +49,7 @@ class WebsocketAPIView(HomeAssistantView):
async def get(self, request: web.Request) -> web.WebSocketResponse: async def get(self, request: web.Request) -> web.WebSocketResponse:
"""Handle an incoming websocket connection.""" """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): class WebSocketAdapter(logging.LoggerAdapter):

View file

@ -55,8 +55,7 @@ from zwave_js_server.model.utils import (
from zwave_js_server.util.node import async_set_config_parameter from zwave_js_server.util.node import async_set_config_parameter
from homeassistant.components import websocket_api from homeassistant.components import websocket_api
from homeassistant.components.http import require_admin from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.websocket_api import ( from homeassistant.components.websocket_api import (
ERR_INVALID_FORMAT, ERR_INVALID_FORMAT,
ERR_NOT_FOUND, ERR_NOT_FOUND,
@ -2196,7 +2195,7 @@ class FirmwareUploadView(HomeAssistantView):
@require_admin @require_admin
async def post(self, request: web.Request, device_id: str) -> web.Response: async def post(self, request: web.Request, device_id: str) -> web.Response:
"""Handle upload.""" """Handle upload."""
hass = request.app["hass"] hass = request.app[KEY_HASS]
try: try:
node = async_get_node_from_device_id(hass, device_id, self._dev_reg) node = async_get_node_from_device_id(hass, device_id, self._dev_reg)

View file

@ -455,7 +455,7 @@ class OAuth2AuthorizeCallbackView(http.HomeAssistantView):
if "state" not in request.query: if "state" not in request.query:
return web.Response(text="Missing state parameter") return web.Response(text="Missing state parameter")
hass = request.app["hass"] hass = request.app[http.KEY_HASS]
state = _decode_jwt(hass, request.query["state"]) state = _decode_jwt(hass, request.query["state"])

View file

@ -5,7 +5,7 @@ from unittest.mock import Mock
from aiohttp import web from aiohttp import web
import voluptuous as vol 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 homeassistant.components.http.data_validator import RequestDataValidator
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator
@ -14,7 +14,7 @@ from tests.typing import ClientSessionGenerator
async def get_client(aiohttp_client, validator): async def get_client(aiohttp_client, validator):
"""Generate a client that hits a view decorated with validator.""" """Generate a client that hits a view decorated with validator."""
app = web.Application() app = web.Application()
app["hass"] = Mock(is_stopping=False) app[KEY_HASS] = Mock(is_stopping=False)
app["allow_configured_cors"] = lambda _: None app["allow_configured_cors"] = lambda _: None
class TestView(HomeAssistantView): class TestView(HomeAssistantView):
@ -27,7 +27,7 @@ async def get_client(aiohttp_client, validator):
"""Test method.""" """Test method."""
return b"" return b""
TestView().register(app["hass"], app, app.router) TestView().register(app[KEY_HASS], app, app.router)
client = await aiohttp_client(app) client = await aiohttp_client(app)
return client return client

View file

@ -12,6 +12,7 @@ from aiohttp.web_exceptions import (
import pytest import pytest
import voluptuous as vol import voluptuous as vol
from homeassistant.components.http import KEY_HASS
from homeassistant.components.http.view import ( from homeassistant.components.http.view import (
HomeAssistantView, HomeAssistantView,
request_handler_factory, request_handler_factory,
@ -22,13 +23,13 @@ from homeassistant.exceptions import ServiceNotFound, Unauthorized
@pytest.fixture @pytest.fixture
def mock_request() -> Mock: def mock_request() -> Mock:
"""Mock a request.""" """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 @pytest.fixture
def mock_request_with_stopping() -> Mock: def mock_request_with_stopping() -> Mock:
"""Mock a request.""" """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: 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.""" """Test handling unauth exceptions."""
with pytest.raises(HTTPUnauthorized): with pytest.raises(HTTPUnauthorized):
await request_handler_factory( await request_handler_factory(
mock_request.app["hass"], mock_request.app[KEY_HASS],
Mock(requires_auth=False), Mock(requires_auth=False),
AsyncMock(side_effect=Unauthorized), AsyncMock(side_effect=Unauthorized),
)(mock_request) )(mock_request)
@ -62,7 +63,7 @@ async def test_handling_invalid_data(mock_request: Mock) -> None:
"""Test handling unauth exceptions.""" """Test handling unauth exceptions."""
with pytest.raises(HTTPBadRequest): with pytest.raises(HTTPBadRequest):
await request_handler_factory( await request_handler_factory(
mock_request.app["hass"], mock_request.app[KEY_HASS],
Mock(requires_auth=False), Mock(requires_auth=False),
AsyncMock(side_effect=vol.Invalid("yo")), AsyncMock(side_effect=vol.Invalid("yo")),
)(mock_request) )(mock_request)
@ -72,7 +73,7 @@ async def test_handling_service_not_found(mock_request: Mock) -> None:
"""Test handling unauth exceptions.""" """Test handling unauth exceptions."""
with pytest.raises(HTTPInternalServerError): with pytest.raises(HTTPInternalServerError):
await request_handler_factory( await request_handler_factory(
mock_request.app["hass"], mock_request.app[KEY_HASS],
Mock(requires_auth=False), Mock(requires_auth=False),
AsyncMock(side_effect=ServiceNotFound("test", "test")), AsyncMock(side_effect=ServiceNotFound("test", "test")),
)(mock_request) )(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: async def test_not_running(mock_request_with_stopping: Mock) -> None:
"""Test we get a 503 when not running.""" """Test we get a 503 when not running."""
response = await request_handler_factory( response = await request_handler_factory(
mock_request_with_stopping.app["hass"], mock_request_with_stopping.app[KEY_HASS],
Mock(requires_auth=False), Mock(requires_auth=False),
AsyncMock(side_effect=Unauthorized), AsyncMock(side_effect=Unauthorized),
)(mock_request_with_stopping) )(mock_request_with_stopping)
@ -92,7 +93,7 @@ async def test_invalid_handler(mock_request: Mock) -> None:
"""Test an invalid handler.""" """Test an invalid handler."""
with pytest.raises(TypeError): with pytest.raises(TypeError):
await request_handler_factory( await request_handler_factory(
mock_request.app["hass"], mock_request.app[KEY_HASS],
Mock(requires_auth=False), Mock(requires_auth=False),
AsyncMock(return_value=["not valid"]), AsyncMock(return_value=["not valid"]),
)(mock_request) )(mock_request)

View file

@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, Mock, patch
import pytest import pytest
from homeassistant import config_entries, data_entry_flow 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 import config_flow
from homeassistant.components.logi_circle.config_flow import ( from homeassistant.components.logi_circle.config_flow import (
DOMAIN, DOMAIN,
@ -23,7 +24,7 @@ class MockRequest:
def __init__(self, hass, query): def __init__(self, hass, query):
"""Init request object.""" """Init request object."""
self.app = {"hass": hass} self.app = {KEY_HASS: hass}
self.query = query self.query = query