Add template Base64 decode encoding parameter (#116603)

Co-authored-by: Robert Resch <robert@resch.dev>
This commit is contained in:
paulusbrand 2024-06-07 17:01:35 +02:00 committed by GitHub
parent 0556d9d4ed
commit 624017a0f9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 4 deletions

View File

@ -2397,14 +2397,18 @@ def struct_unpack(value: bytes, format_string: str, offset: int = 0) -> Any | No
return None
def base64_encode(value):
def base64_encode(value: str) -> str:
"""Perform base64 encode."""
return base64.b64encode(value.encode("utf-8")).decode("utf-8")
def base64_decode(value):
"""Perform base64 denode."""
return base64.b64decode(value).decode("utf-8")
def base64_decode(value: str, encoding: str | None = "utf-8") -> str | bytes:
"""Perform base64 decode."""
decoded = base64.b64decode(value)
if encoding:
return decoded.decode(encoding)
return decoded
def ordinal(value):

View File

@ -1643,6 +1643,18 @@ def test_base64_decode(hass: HomeAssistant) -> None:
).async_render()
== "homeassistant"
)
assert (
template.Template(
'{{ "aG9tZWFzc2lzdGFudA==" | base64_decode(None) }}', hass
).async_render()
== b"homeassistant"
)
assert (
template.Template(
'{{ "aG9tZWFzc2lzdGFudA==" | base64_decode("ascii") }}', hass
).async_render()
== "homeassistant"
)
def test_slugify(hass: HomeAssistant) -> None: