Use KEY_HASS [h-z] (#112610)

pull/112886/head
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.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(

View File

@ -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

View File

@ -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):

View File

@ -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))

View File

@ -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]})

View File

@ -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,

View File

@ -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():

View File

@ -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:

View File

@ -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()

View File

@ -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)

View File

@ -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")

View File

@ -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(

View File

@ -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):

View File

@ -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()

View File

@ -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):

View File

@ -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():

View File

@ -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
)

View File

@ -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)

View File

@ -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(

View File

@ -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.")

View File

@ -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")

View File

@ -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),

View File

@ -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

View File

@ -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]:

View File

@ -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

View File

@ -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):

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 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)

View File

@ -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"])

View File

@ -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

View File

@ -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)

View File

@ -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