ImageEntity split load_image_from_url (#96146)

* Initial commit

* fix async_load_image_from_url
This commit is contained in:
RenierM26 2023-07-13 17:03:26 +02:00 committed by GitHub
parent b8bc958070
commit c54ceb2da2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -167,18 +167,14 @@ class ImageEntity(Entity):
"""Return bytes of image.""" """Return bytes of image."""
raise NotImplementedError() raise NotImplementedError()
async def _async_load_image_from_url(self, url: str) -> Image | None: async def _fetch_url(self, url: str) -> httpx.Response | None:
"""Load an image by url.""" """Fetch a URL."""
try: try:
response = await self._client.get( response = await self._client.get(
url, timeout=GET_IMAGE_TIMEOUT, follow_redirects=True url, timeout=GET_IMAGE_TIMEOUT, follow_redirects=True
) )
response.raise_for_status() response.raise_for_status()
content_type = response.headers.get("content-type") return response
return Image(
content=response.content,
content_type=valid_image_content_type(content_type),
)
except httpx.TimeoutException: except httpx.TimeoutException:
_LOGGER.error("%s: Timeout getting image from %s", self.entity_id, url) _LOGGER.error("%s: Timeout getting image from %s", self.entity_id, url)
return None return None
@ -190,14 +186,25 @@ class ImageEntity(Entity):
err, err,
) )
return None return None
except ImageContentTypeError:
_LOGGER.error( async def _async_load_image_from_url(self, url: str) -> Image | None:
"%s: Image from %s has invalid content type: %s", """Load an image by url."""
self.entity_id, if response := await self._fetch_url(url):
url, content_type = response.headers.get("content-type")
content_type, try:
) return Image(
return None content=response.content,
content_type=valid_image_content_type(content_type),
)
except ImageContentTypeError:
_LOGGER.error(
"%s: Image from %s has invalid content type: %s",
self.entity_id,
url,
content_type,
)
return None
return None
async def async_image(self) -> bytes | None: async def async_image(self) -> bytes | None:
"""Return bytes of image.""" """Return bytes of image."""