Use KEY_HASS [a-g] (#112609)

This commit is contained in:
Marc Mueller 2024-03-07 18:09:20 +01:00 committed by GitHub
parent 8ca127df2a
commit f3594c543d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 67 additions and 68 deletions

View file

@ -64,7 +64,7 @@ class AlexaIntentsView(http.HomeAssistantView):
async def post(self, request: http.HomeAssistantRequest) -> Response | bytes:
"""Handle Alexa."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[http.KEY_HASS]
message: dict[str, Any] = await request.json()
_LOGGER.debug("Received Alexa request: %s", message)

View file

@ -7,8 +7,11 @@ from yarl import URL
from homeassistant import core
from homeassistant.auth.models import User
from homeassistant.components.http import HomeAssistantRequest
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.http import (
KEY_HASS,
HomeAssistantRequest,
HomeAssistantView,
)
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import entity_registry as er
@ -146,7 +149,7 @@ class SmartHomeView(HomeAssistantView):
Lambda, which will need to forward the requests to here and pass back
the response.
"""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
user: User = request["hass_user"]
message: dict[str, Any] = await request.json()

View file

@ -5,7 +5,7 @@ from typing import Any
from aiohttp import web
import ambiclimate
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant, callback
@ -150,7 +150,7 @@ class AmbiclimateAuthCallbackView(HomeAssistantView):
"""Receive authorization token."""
if (code := request.query.get("code")) is None:
return "No code"
hass = request.app["hass"]
hass = request.app[KEY_HASS]
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": "code"}, data=code

View file

@ -117,7 +117,7 @@ class APICoreStateView(HomeAssistantView):
Home Assistant core is running. Its primary use case is for supervisor
to check if Home Assistant is running.
"""
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
return self.json({"state": hass.state.value})
@ -130,7 +130,7 @@ class APIEventStream(HomeAssistantView):
@require_admin
async def get(self, request: web.Request) -> web.StreamResponse:
"""Provide a streaming interface for the event bus."""
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
stop_obj = object()
to_write: asyncio.Queue[object | str] = asyncio.Queue()
@ -197,8 +197,7 @@ class APIConfigView(HomeAssistantView):
@ha.callback
def get(self, request: web.Request) -> web.Response:
"""Get current configuration."""
hass: HomeAssistant = request.app[KEY_HASS]
return self.json(hass.config.as_dict())
return self.json(request.app[KEY_HASS].config.as_dict())
class APIStatesView(HomeAssistantView):
@ -211,7 +210,7 @@ class APIStatesView(HomeAssistantView):
def get(self, request: web.Request) -> web.Response:
"""Get current states."""
user: User = request[KEY_HASS_USER]
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
if user.is_admin:
states = (state.as_dict_json for state in hass.states.async_all())
else:
@ -240,7 +239,7 @@ class APIEntityStateView(HomeAssistantView):
def get(self, request: web.Request, entity_id: str) -> web.Response:
"""Retrieve state of entity."""
user: User = request[KEY_HASS_USER]
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
if not user.permissions.check_entity(entity_id, POLICY_READ):
raise Unauthorized(entity_id=entity_id)
@ -256,7 +255,7 @@ class APIEntityStateView(HomeAssistantView):
user: User = request[KEY_HASS_USER]
if not user.is_admin:
raise Unauthorized(entity_id=entity_id)
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
try:
data = await request.json()
except ValueError:
@ -296,8 +295,7 @@ class APIEntityStateView(HomeAssistantView):
"""Remove entity."""
if not request[KEY_HASS_USER].is_admin:
raise Unauthorized(entity_id=entity_id)
hass: HomeAssistant = request.app[KEY_HASS]
if hass.states.async_remove(entity_id):
if request.app[KEY_HASS].states.async_remove(entity_id):
return self.json_message("Entity removed.")
return self.json_message("Entity not found.", HTTPStatus.NOT_FOUND)
@ -311,8 +309,7 @@ class APIEventListenersView(HomeAssistantView):
@ha.callback
def get(self, request: web.Request) -> web.Response:
"""Get event listeners."""
hass: HomeAssistant = request.app[KEY_HASS]
return self.json(async_events_json(hass))
return self.json(async_events_json(request.app[KEY_HASS]))
class APIEventView(HomeAssistantView):
@ -346,8 +343,7 @@ class APIEventView(HomeAssistantView):
if state:
event_data[key] = state
hass: HomeAssistant = request.app[KEY_HASS]
hass.bus.async_fire(
request.app[KEY_HASS].bus.async_fire(
event_type, event_data, ha.EventOrigin.remote, self.context(request)
)
@ -362,8 +358,7 @@ class APIServicesView(HomeAssistantView):
async def get(self, request: web.Request) -> web.Response:
"""Get registered services."""
hass: HomeAssistant = request.app[KEY_HASS]
services = await async_services_json(hass)
services = await async_services_json(request.app[KEY_HASS])
return self.json(services)
@ -380,7 +375,7 @@ class APIDomainServicesView(HomeAssistantView):
Returns a list of changed states.
"""
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
body = await request.text()
try:
data = json_loads(body) if body else None
@ -433,8 +428,7 @@ class APIComponentsView(HomeAssistantView):
@ha.callback
def get(self, request: web.Request) -> web.Response:
"""Get current loaded components."""
hass: HomeAssistant = request.app[KEY_HASS]
return self.json(list(hass.config.components))
return self.json(request.app[KEY_HASS].config.components)
@lru_cache
@ -471,7 +465,7 @@ class APIErrorLog(HomeAssistantView):
@require_admin
async def get(self, request: web.Request) -> web.FileResponse:
"""Retrieve API error log."""
hass: HomeAssistant = request.app[KEY_HASS]
hass = request.app[KEY_HASS]
response = web.FileResponse(hass.data[DATA_LOGGING])
response.enable_compression()
return response

View file

@ -6,7 +6,7 @@ from http import HTTPStatus
from aiohttp.hdrs import CONTENT_DISPOSITION
from aiohttp.web import FileResponse, Request, Response
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.core import HomeAssistant, callback
from homeassistant.util import slugify
@ -35,7 +35,7 @@ class DownloadBackupView(HomeAssistantView):
if not request["hass_user"].is_admin:
return Response(status=HTTPStatus.UNAUTHORIZED)
manager: BackupManager = request.app["hass"].data[DOMAIN]
manager: BackupManager = request.app[KEY_HASS].data[DOMAIN]
backup = await manager.get_backup(slug)
if backup is None or not backup.path.exists():

View file

@ -652,7 +652,7 @@ class CalendarEventView(http.HomeAssistantView):
try:
calendar_event_list = await entity.async_get_events(
request.app["hass"],
request.app[http.KEY_HASS],
dt_util.as_local(start_date),
dt_util.as_local(end_date),
)
@ -682,11 +682,12 @@ class CalendarListView(http.HomeAssistantView):
async def get(self, request: web.Request) -> web.Response:
"""Retrieve calendar list."""
hass = request.app["hass"]
hass = request.app[http.KEY_HASS]
calendar_list: list[dict[str, str]] = []
for entity in self.component.entities:
state = hass.states.get(entity.entity_id)
assert state
calendar_list.append({"name": state.name, "entity_id": entity.entity_id})
return self.json(sorted(calendar_list, key=lambda x: cast(str, x["name"])))

View file

@ -25,7 +25,7 @@ from homeassistant.components.alexa import (
)
from homeassistant.components.google_assistant import helpers as google_helpers
from homeassistant.components.homeassistant import exposed_entities
from homeassistant.components.http import HomeAssistantView, require_admin
from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
from homeassistant.core import HomeAssistant, callback
@ -197,7 +197,7 @@ class GoogleActionsSyncView(HomeAssistantView):
@_handle_cloud_errors
async def post(self, request: web.Request) -> web.Response:
"""Trigger a Google Actions sync."""
hass = request.app["hass"]
hass = request.app[KEY_HASS]
cloud: Cloud[CloudClient] = hass.data[DOMAIN]
gconf = await cloud.client.get_google_config()
status = await gconf.async_sync_entities(gconf.agent_user_id)
@ -217,7 +217,7 @@ class CloudLoginView(HomeAssistantView):
)
async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response:
"""Handle login request."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
cloud: Cloud[CloudClient] = hass.data[DOMAIN]
await cloud.login(data["email"], data["password"])
@ -235,7 +235,7 @@ class CloudLogoutView(HomeAssistantView):
@_handle_cloud_errors
async def post(self, request: web.Request) -> web.Response:
"""Handle logout request."""
hass = request.app["hass"]
hass = request.app[KEY_HASS]
cloud: Cloud[CloudClient] = hass.data[DOMAIN]
async with asyncio.timeout(REQUEST_TIMEOUT):
@ -262,7 +262,7 @@ class CloudRegisterView(HomeAssistantView):
)
async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response:
"""Handle registration request."""
hass = request.app["hass"]
hass = request.app[KEY_HASS]
cloud: Cloud[CloudClient] = hass.data[DOMAIN]
client_metadata = None
@ -299,7 +299,7 @@ class CloudResendConfirmView(HomeAssistantView):
@RequestDataValidator(vol.Schema({vol.Required("email"): str}))
async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response:
"""Handle resending confirm email code request."""
hass = request.app["hass"]
hass = request.app[KEY_HASS]
cloud: Cloud[CloudClient] = hass.data[DOMAIN]
async with asyncio.timeout(REQUEST_TIMEOUT):
@ -319,7 +319,7 @@ class CloudForgotPasswordView(HomeAssistantView):
@RequestDataValidator(vol.Schema({vol.Required("email"): str}))
async def post(self, request: web.Request, data: dict[str, Any]) -> web.Response:
"""Handle forgot password request."""
hass = request.app["hass"]
hass = request.app[KEY_HASS]
cloud: Cloud[CloudClient] = hass.data[DOMAIN]
async with asyncio.timeout(REQUEST_TIMEOUT):

View file

@ -12,7 +12,7 @@ import voluptuous as vol
from homeassistant import config_entries, data_entry_flow
from homeassistant.auth.permissions.const import CAT_CONFIG_ENTRIES, POLICY_EDIT
from homeassistant.components import websocket_api
from homeassistant.components.http import HomeAssistantView, require_admin
from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin
from homeassistant.components.http.data_validator import RequestDataValidator
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import DependencyError, Unauthorized
@ -64,7 +64,7 @@ class ConfigManagerEntryIndexView(HomeAssistantView):
async def get(self, request: web.Request) -> web.Response:
"""List available config entries."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
domain = None
if "domain" in request.query:
domain = request.query["domain"]
@ -88,7 +88,7 @@ class ConfigManagerEntryResourceView(HomeAssistantView):
if not request["hass_user"].is_admin:
raise Unauthorized(config_entry_id=entry_id, permission="remove")
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
try:
result = await hass.config_entries.async_remove(entry_id)
@ -109,7 +109,7 @@ class ConfigManagerEntryResourceReloadView(HomeAssistantView):
if not request["hass_user"].is_admin:
raise Unauthorized(config_entry_id=entry_id, permission="remove")
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
entry = hass.config_entries.async_get_entry(entry_id)
if not entry:
return self.json_message("Invalid entry specified", HTTPStatus.NOT_FOUND)
@ -235,7 +235,7 @@ class ConfigManagerAvailableFlowView(HomeAssistantView):
async def get(self, request: web.Request) -> web.Response:
"""List available flow handlers."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
kwargs: dict[str, Any] = {}
if "type" in request.query:
kwargs["type_filter"] = request.query["type"]

View file

@ -7,7 +7,7 @@ from aiohttp import web
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.http import HomeAssistantView, require_admin
from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin
from homeassistant.components.sensor import async_update_suggested_units
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import check_config, config_validation as cv
@ -34,7 +34,7 @@ class CheckConfigView(HomeAssistantView):
async def post(self, request: web.Request) -> web.Response:
"""Validate configuration and return results."""
res = await check_config.async_check_ha_config_file(request.app["hass"])
res = await check_config.async_check_ha_config_file(request.app[KEY_HASS])
state = "invalid" if res.errors else "valid"

View file

@ -10,7 +10,7 @@ from typing import Any, Generic, TypeVar, cast
from aiohttp import web
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView, require_admin
from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin
from homeassistant.const import CONF_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
@ -80,7 +80,7 @@ class BaseEditConfigView(HomeAssistantView, Generic[_DataT]):
@require_admin
async def get(self, request: web.Request, config_key: str) -> web.Response:
"""Fetch device specific config."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
async with self.mutation_lock:
current = await self.read_config(hass)
value = self._get_value(hass, current, config_key)
@ -103,7 +103,7 @@ class BaseEditConfigView(HomeAssistantView, Generic[_DataT]):
except vol.Invalid as err:
return self.json_message(f"Key malformed: {err}", HTTPStatus.BAD_REQUEST)
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
try:
# We just validate, we don't store that data because
@ -135,7 +135,7 @@ class BaseEditConfigView(HomeAssistantView, Generic[_DataT]):
@require_admin
async def delete(self, request: web.Request, config_key: str) -> web.Response:
"""Remove an entry."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
async with self.mutation_lock:
current = await self.read_config(hass)
value = self._get_value(hass, current, config_key)

View file

@ -484,7 +484,7 @@ class ConversationProcessView(http.HomeAssistantView):
)
async def post(self, request: web.Request, data: dict[str, str]) -> web.Response:
"""Send a request for processing."""
hass = request.app["hass"]
hass = request.app[http.KEY_HASS]
result = await async_converse(
hass,

View file

@ -232,7 +232,7 @@ class DownloadDiagnosticsView(http.HomeAssistantView):
device_diagnostics = sub_type is not None
hass: HomeAssistant = request.app["hass"]
hass = request.app[http.KEY_HASS]
if (config_entry := hass.config_entries.async_get_entry(d_id)) is None:
return web.Response(status=HTTPStatus.NOT_FOUND)

View file

@ -5,8 +5,7 @@ from http import HTTPStatus
from aiohttp import web
from homeassistant.components.http import HomeAssistantView
from homeassistant.core import HomeAssistant
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from .const import API_URL, DOMAIN
from .device import async_reset_device_favorites
@ -23,7 +22,7 @@ class DoorBirdRequestView(HomeAssistantView):
async def get(self, request: web.Request, event: str) -> web.Response:
"""Respond to requests from the device."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
token: str | None = request.query.get("token")
if (
token is None

View file

@ -6,6 +6,7 @@ import logging
from aiohttp import web
import voluptuous as vol
from homeassistant.components.http import KEY_HASS
from homeassistant.components.network import async_get_source_ip
from homeassistant.const import (
CONF_ENTITIES,
@ -130,7 +131,7 @@ async def async_setup(hass: HomeAssistant, yaml_config: ConfigType) -> bool:
await config.async_setup()
app = web.Application()
app["hass"] = hass
app[KEY_HASS] = hass
# We misunderstood the startup signal. You're not allowed to change
# anything during startup. Temp workaround.

View file

@ -34,7 +34,7 @@ from homeassistant.components.cover import (
CoverEntityFeature,
)
from homeassistant.components.fan import ATTR_PERCENTAGE, FanEntityFeature
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.components.humidifier import ATTR_HUMIDITY, SERVICE_SET_HUMIDITY
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
@ -319,7 +319,7 @@ class HueOneLightStateView(HomeAssistantView):
if not _remote_is_allowed(request.remote):
return self.json_message("Only local IPs allowed", HTTPStatus.UNAUTHORIZED)
hass: core.HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
hass_entity_id = self.config.number_to_entity_id(entity_id)
if hass_entity_id is None:
@ -362,7 +362,7 @@ class HueOneLightChangeView(HomeAssistantView):
return self.json_message("Only local IPs allowed", HTTPStatus.UNAUTHORIZED)
config = self.config
hass: core.HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
entity_id = config.number_to_entity_id(entity_number)
if entity_id is None:
@ -885,7 +885,7 @@ def create_config_model(config: Config, request: web.Request) -> dict[str, Any]:
def create_list_of_entities(config: Config, request: web.Request) -> dict[str, Any]:
"""Create a list of all entities."""
hass: core.HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
return {
config.entity_id_to_number(entity_id): state_to_json(config, state)
for entity_id in config.get_exposed_entity_ids()

View file

@ -13,7 +13,7 @@ import tempfile
from aiohttp import BodyPartReader, 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 homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant, callback
@ -145,7 +145,7 @@ class FileUploadView(HomeAssistantView):
except ValueError as err:
raise web.HTTPBadRequest from err
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
file_id = ulid_hex()
if DOMAIN not in hass.data:
@ -199,7 +199,7 @@ class FileUploadView(HomeAssistantView):
@RequestDataValidator({vol.Required("file_id"): str})
async def delete(self, request: web.Request, data: dict[str, str]) -> web.Response:
"""Delete a file."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
if DOMAIN not in hass.data:
raise web.HTTPNotFound()

View file

@ -5,7 +5,7 @@ import logging
import requests
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.core import HomeAssistant, ServiceCall
import homeassistant.helpers.config_validation as cv
@ -105,4 +105,4 @@ class FoursquarePushReceiver(HomeAssistantView):
)
return self.json_message("Incorrect secret", HTTPStatus.BAD_REQUEST)
request.app["hass"].bus.async_fire(EVENT_PUSH, data)
request.app[KEY_HASS].bus.async_fire(EVENT_PUSH, data)

View file

@ -14,7 +14,7 @@ import voluptuous as vol
from yarl import URL
from homeassistant.components import onboarding, websocket_api
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.components.websocket_api.connection import ActiveConnection
from homeassistant.config import async_hass_config_yaml
from homeassistant.const import (
@ -595,7 +595,7 @@ class IndexView(web_urldispatcher.AbstractResource):
async def get(self, request: web.Request) -> web.Response:
"""Serve the index page for panel pages."""
hass: HomeAssistant = request.app["hass"]
hass = request.app[KEY_HASS]
if not onboarding.async_is_onboarded(hass):
return web.Response(status=302, headers={"location": "/onboarding.html"})

View file

@ -12,7 +12,7 @@ from aiohttp.web import Request, Response
import jwt
from homeassistant.components import webhook
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http import KEY_HASS, HomeAssistantView
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
@ -380,7 +380,7 @@ class GoogleAssistantView(HomeAssistantView):
"""Handle Google Assistant requests."""
message: dict = await request.json()
result = await async_handle_message(
request.app["hass"],
request.app[KEY_HASS],
self.config,
request["hass_user"].id,
request["hass_user"].id,

View file

@ -6,6 +6,7 @@ import pytest
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.ambiclimate import config_flow
from homeassistant.components.http import KEY_HASS
from homeassistant.config import async_process_ha_core_config
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant
@ -127,11 +128,11 @@ async def test_view(hass: HomeAssistant) -> None:
request = aiohttp.MockRequest(
b"", query_string="code=test_code", mock_source="test"
)
request.app = {"hass": hass}
request.app = {KEY_HASS: hass}
view = config_flow.AmbiclimateAuthCallbackView()
assert await view.get(request) == "OK!"
request = aiohttp.MockRequest(b"", query_string="", mock_source="test")
request.app = {"hass": hass}
request.app = {KEY_HASS: hass}
view = config_flow.AmbiclimateAuthCallbackView()
assert await view.get(request) == "No code"