-
-
Notifications
You must be signed in to change notification settings - Fork 32.7k
/
Copy pathtemplate.py
3232 lines (2587 loc) · 106 KB
/
template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Template helper methods for rendering strings with Home Assistant data."""
from __future__ import annotations
from ast import literal_eval
import asyncio
import base64
import collections.abc
from collections.abc import Callable, Generator, Iterable
from contextlib import AbstractContextManager
from contextvars import ContextVar
from copy import deepcopy
from datetime import date, datetime, time, timedelta
from functools import cache, lru_cache, partial, wraps
import json
import logging
import math
from operator import contains
import pathlib
import random
import re
import statistics
from struct import error as StructError, pack, unpack_from
import sys
from types import CodeType, TracebackType
from typing import (
TYPE_CHECKING,
Any,
Concatenate,
Literal,
NoReturn,
Self,
cast,
overload,
)
from urllib.parse import urlencode as urllib_urlencode
import weakref
from awesomeversion import AwesomeVersion
import jinja2
from jinja2 import pass_context, pass_environment, pass_eval_context
from jinja2.runtime import AsyncLoopContext, LoopContext
from jinja2.sandbox import ImmutableSandboxedEnvironment
from jinja2.utils import Namespace
from lru import LRU
import orjson
from propcache import under_cached_property
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_PERSONS,
ATTR_UNIT_OF_MEASUREMENT,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
UnitOfLength,
)
from homeassistant.core import (
Context,
HomeAssistant,
ServiceResponse,
State,
callback,
split_entity_id,
valid_domain,
valid_entity_id,
)
from homeassistant.exceptions import TemplateError
from homeassistant.loader import bind_hass
from homeassistant.util import (
convert,
dt as dt_util,
location as loc_util,
slugify as slugify_util,
)
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util.hass_dict import HassKey
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads
from homeassistant.util.read_only_dict import ReadOnlyDict
from homeassistant.util.thread import ThreadWithException
from . import (
area_registry,
device_registry,
entity_registry,
floor_registry as fr,
issue_registry,
label_registry,
location as loc_helper,
)
from .deprecation import deprecated_function
from .singleton import singleton
from .translation import async_translate_state
from .typing import TemplateVarsType
if TYPE_CHECKING:
from _typeshed import OptExcInfo
# mypy: allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getLogger(__name__)
_SENTINEL = object()
DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S"
_ENVIRONMENT: HassKey[TemplateEnvironment] = HassKey("template.environment")
_ENVIRONMENT_LIMITED: HassKey[TemplateEnvironment] = HassKey(
"template.environment_limited"
)
_ENVIRONMENT_STRICT: HassKey[TemplateEnvironment] = HassKey(
"template.environment_strict"
)
_HASS_LOADER = "template.hass_loader"
# Match "simple" ints and floats. -1.0, 1, +5, 5.0
_IS_NUMERIC = re.compile(r"^[+-]?(?!0\d)\d*(?:\.\d*)?$")
_RESERVED_NAMES = {
"contextfunction",
"evalcontextfunction",
"environmentfunction",
"jinja_pass_arg",
}
_COLLECTABLE_STATE_ATTRIBUTES = {
"state",
"attributes",
"last_changed",
"last_updated",
"context",
"domain",
"object_id",
"name",
}
ALL_STATES_RATE_LIMIT = 60 # seconds
DOMAIN_STATES_RATE_LIMIT = 1 # seconds
_render_info: ContextVar[RenderInfo | None] = ContextVar("_render_info", default=None)
template_cv: ContextVar[tuple[str, str] | None] = ContextVar(
"template_cv", default=None
)
#
# CACHED_TEMPLATE_STATES is a rough estimate of the number of entities
# on a typical system. It is used as the initial size of the LRU cache
# for TemplateState objects.
#
# If the cache is too small we will end up creating and destroying
# TemplateState objects too often which will cause a lot of GC activity
# and slow down the system. For systems with a lot of entities and
# templates, this can reach 100000s of object creations and destructions
# per minute.
#
# Since entity counts may grow over time, we will increase
# the size if the number of entities grows via _async_adjust_lru_sizes
# at the start of the system and every 10 minutes if needed.
#
CACHED_TEMPLATE_STATES = 512
EVAL_CACHE_SIZE = 512
MAX_CUSTOM_TEMPLATE_SIZE = 5 * 1024 * 1024
MAX_TEMPLATE_OUTPUT = 256 * 1024 # 256KiB
CACHED_TEMPLATE_LRU: LRU[State, TemplateState] = LRU(CACHED_TEMPLATE_STATES)
CACHED_TEMPLATE_NO_COLLECT_LRU: LRU[State, TemplateState] = LRU(CACHED_TEMPLATE_STATES)
ENTITY_COUNT_GROWTH_FACTOR = 1.2
ORJSON_PASSTHROUGH_OPTIONS = (
orjson.OPT_PASSTHROUGH_DATACLASS | orjson.OPT_PASSTHROUGH_DATETIME
)
def _template_state_no_collect(hass: HomeAssistant, state: State) -> TemplateState:
"""Return a TemplateState for a state without collecting."""
if template_state := CACHED_TEMPLATE_NO_COLLECT_LRU.get(state):
return template_state
template_state = _create_template_state_no_collect(hass, state)
CACHED_TEMPLATE_NO_COLLECT_LRU[state] = template_state
return template_state
def _template_state(hass: HomeAssistant, state: State) -> TemplateState:
"""Return a TemplateState for a state that collects."""
if template_state := CACHED_TEMPLATE_LRU.get(state):
return template_state
template_state = TemplateState(hass, state)
CACHED_TEMPLATE_LRU[state] = template_state
return template_state
def async_setup(hass: HomeAssistant) -> bool:
"""Set up tracking the template LRUs."""
@callback
def _async_adjust_lru_sizes(_: Any) -> None:
"""Adjust the lru cache sizes."""
new_size = int(
round(hass.states.async_entity_ids_count() * ENTITY_COUNT_GROWTH_FACTOR)
)
for lru in (CACHED_TEMPLATE_LRU, CACHED_TEMPLATE_NO_COLLECT_LRU):
# There is no typing for LRU
current_size = lru.get_size()
if new_size > current_size:
lru.set_size(new_size)
from .event import ( # pylint: disable=import-outside-toplevel
async_track_time_interval,
)
cancel = async_track_time_interval(
hass, _async_adjust_lru_sizes, timedelta(minutes=10)
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_adjust_lru_sizes)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, callback(lambda _: cancel()))
return True
@bind_hass
@deprecated_function(
"automatic setting of Template.hass introduced by HA Core PR #89242",
breaks_in_ha_version="2025.10",
)
def attach(hass: HomeAssistant, obj: Any) -> None:
"""Recursively attach hass to all template instances in list and dict."""
return _attach(hass, obj)
def _attach(hass: HomeAssistant, obj: Any) -> None:
"""Recursively attach hass to all template instances in list and dict."""
if isinstance(obj, list):
for child in obj:
_attach(hass, child)
elif isinstance(obj, collections.abc.Mapping):
for child_key, child_value in obj.items():
_attach(hass, child_key)
_attach(hass, child_value)
elif isinstance(obj, Template):
obj.hass = hass
def render_complex(
value: Any,
variables: TemplateVarsType = None,
limited: bool = False,
parse_result: bool = True,
) -> Any:
"""Recursive template creator helper function."""
if isinstance(value, list):
return [
render_complex(item, variables, limited, parse_result) for item in value
]
if isinstance(value, collections.abc.Mapping):
return {
render_complex(key, variables, limited, parse_result): render_complex(
item, variables, limited, parse_result
)
for key, item in value.items()
}
if isinstance(value, Template):
return value.async_render(variables, limited=limited, parse_result=parse_result)
return value
def is_complex(value: Any) -> bool:
"""Test if data structure is a complex template."""
if isinstance(value, Template):
return True
if isinstance(value, list):
return any(is_complex(val) for val in value)
if isinstance(value, collections.abc.Mapping):
return any(is_complex(val) for val in value) or any(
is_complex(val) for val in value.values()
)
return False
def is_template_string(maybe_template: str) -> bool:
"""Check if the input is a Jinja2 template."""
return "{" in maybe_template and (
"{%" in maybe_template or "{{" in maybe_template or "{#" in maybe_template
)
class ResultWrapper:
"""Result wrapper class to store render result."""
render_result: str | None
def gen_result_wrapper(kls: type[dict | list | set]) -> type:
"""Generate a result wrapper."""
class Wrapper(kls, ResultWrapper): # type: ignore[valid-type,misc]
"""Wrapper of a kls that can store render_result."""
def __init__(self, *args: Any, render_result: str | None = None) -> None:
super().__init__(*args)
self.render_result = render_result
def __str__(self) -> str:
if self.render_result is None:
# Can't get set repr to work
if kls is set:
return str(set(self))
return kls.__str__(self)
return self.render_result
return Wrapper
class TupleWrapper(tuple, ResultWrapper):
"""Wrap a tuple."""
__slots__ = ()
# This is all magic to be allowed to subclass a tuple.
def __new__(cls, value: tuple, *, render_result: str | None = None) -> Self:
"""Create a new tuple class."""
return super().__new__(cls, tuple(value))
def __init__(self, value: tuple, *, render_result: str | None = None) -> None:
"""Initialize a new tuple class."""
self.render_result = render_result
def __str__(self) -> str:
"""Return string representation."""
if self.render_result is None:
return super().__str__()
return self.render_result
_types: tuple[type[dict | list | set], ...] = (dict, list, set)
RESULT_WRAPPERS: dict[type, type] = {kls: gen_result_wrapper(kls) for kls in _types}
RESULT_WRAPPERS[tuple] = TupleWrapper
def _true(arg: str) -> bool:
return True
def _false(arg: str) -> bool:
return False
@lru_cache(maxsize=EVAL_CACHE_SIZE)
def _cached_parse_result(render_result: str) -> Any:
"""Parse a result and cache the result."""
result = literal_eval(render_result)
if type(result) in RESULT_WRAPPERS:
result = RESULT_WRAPPERS[type(result)](result, render_result=render_result)
# If the literal_eval result is a string, use the original
# render, by not returning right here. The evaluation of strings
# resulting in strings impacts quotes, to avoid unexpected
# output; use the original render instead of the evaluated one.
# Complex and scientific values are also unexpected. Filter them out.
if (
# Filter out string and complex numbers
not isinstance(result, (str, complex))
and (
# Pass if not numeric and not a boolean
not isinstance(result, (int, float))
# Or it's a boolean (inherit from int)
or isinstance(result, bool)
# Or if it's a digit
or _IS_NUMERIC.match(render_result) is not None
)
):
return result
return render_result
class RenderInfo:
"""Holds information about a template render."""
__slots__ = (
"_result",
"all_states",
"all_states_lifecycle",
"domains",
"domains_lifecycle",
"entities",
"exception",
"filter",
"filter_lifecycle",
"has_time",
"is_static",
"rate_limit",
"template",
)
def __init__(self, template: Template) -> None:
"""Initialise."""
self.template = template
# Will be set sensibly once frozen.
self.filter_lifecycle: Callable[[str], bool] = _true
self.filter: Callable[[str], bool] = _true
self._result: str | None = None
self.is_static = False
self.exception: TemplateError | None = None
self.all_states = False
self.all_states_lifecycle = False
self.domains: collections.abc.Set[str] = set()
self.domains_lifecycle: collections.abc.Set[str] = set()
self.entities: collections.abc.Set[str] = set()
self.rate_limit: float | None = None
self.has_time = False
def __repr__(self) -> str:
"""Representation of RenderInfo."""
return (
f"<RenderInfo {self.template}"
f" all_states={self.all_states}"
f" all_states_lifecycle={self.all_states_lifecycle}"
f" domains={self.domains}"
f" domains_lifecycle={self.domains_lifecycle}"
f" entities={self.entities}"
f" rate_limit={self.rate_limit}"
f" has_time={self.has_time}"
f" exception={self.exception}"
f" is_static={self.is_static}"
">"
)
def _filter_domains_and_entities(self, entity_id: str) -> bool:
"""Template should re-render if the entity state changes.
Only when we match specific domains or entities.
"""
return (
split_entity_id(entity_id)[0] in self.domains or entity_id in self.entities
)
def _filter_entities(self, entity_id: str) -> bool:
"""Template should re-render if the entity state changes.
Only when we match specific entities.
"""
return entity_id in self.entities
def _filter_lifecycle_domains(self, entity_id: str) -> bool:
"""Template should re-render if the entity is added or removed.
Only with domains watched.
"""
return split_entity_id(entity_id)[0] in self.domains_lifecycle
def result(self) -> str:
"""Results of the template computation."""
if self.exception is not None:
raise self.exception
return cast(str, self._result)
def _freeze_static(self) -> None:
self.is_static = True
self._freeze_sets()
self.all_states = False
def _freeze_sets(self) -> None:
self.entities = frozenset(self.entities)
self.domains = frozenset(self.domains)
self.domains_lifecycle = frozenset(self.domains_lifecycle)
def _freeze(self) -> None:
self._freeze_sets()
if self.rate_limit is None:
if self.all_states or self.exception:
self.rate_limit = ALL_STATES_RATE_LIMIT
elif self.domains or self.domains_lifecycle:
self.rate_limit = DOMAIN_STATES_RATE_LIMIT
if self.exception:
return
if not self.all_states_lifecycle:
if self.domains_lifecycle:
self.filter_lifecycle = self._filter_lifecycle_domains
else:
self.filter_lifecycle = _false
if self.all_states:
return
if self.domains:
self.filter = self._filter_domains_and_entities
elif self.entities:
self.filter = self._filter_entities
else:
self.filter = _false
class Template:
"""Class to hold a template and manage caching and rendering."""
__slots__ = (
"__weakref__",
"_compiled",
"_compiled_code",
"_exc_info",
"_hash_cache",
"_limited",
"_log_fn",
"_renders",
"_strict",
"hass",
"is_static",
"template",
)
def __init__(self, template: str, hass: HomeAssistant | None = None) -> None:
"""Instantiate a template.
Note: A valid hass instance should always be passed in. The hass parameter
will be non optional in Home Assistant Core 2025.10.
"""
# pylint: disable-next=import-outside-toplevel
from .frame import ReportBehavior, report_usage
if not isinstance(template, str):
raise TypeError("Expected template to be a string")
if not hass:
report_usage(
"creates a template object without passing hass",
core_behavior=ReportBehavior.LOG,
breaks_in_ha_version="2025.10",
)
self.template: str = template.strip()
self._compiled_code: CodeType | None = None
self._compiled: jinja2.Template | None = None
self.hass = hass
self.is_static = not is_template_string(template)
self._exc_info: OptExcInfo | None = None
self._limited: bool | None = None
self._strict: bool | None = None
self._log_fn: Callable[[int, str], None] | None = None
self._hash_cache: int = hash(self.template)
self._renders: int = 0
@property
def _env(self) -> TemplateEnvironment:
if self.hass is None:
return _NO_HASS_ENV
# Bypass cache if a custom log function is specified
if self._log_fn is not None:
return TemplateEnvironment(
self.hass, self._limited, self._strict, self._log_fn
)
if self._limited:
wanted_env = _ENVIRONMENT_LIMITED
elif self._strict:
wanted_env = _ENVIRONMENT_STRICT
else:
wanted_env = _ENVIRONMENT
if (ret := self.hass.data.get(wanted_env)) is None:
ret = self.hass.data[wanted_env] = TemplateEnvironment(
self.hass, self._limited, self._strict, self._log_fn
)
return ret
def ensure_valid(self) -> None:
"""Return if template is valid."""
if self.is_static or self._compiled_code is not None:
return
if compiled := self._env.template_cache.get(self.template):
self._compiled_code = compiled
return
with _template_context_manager as cm:
cm.set_template(self.template, "compiling")
try:
self._compiled_code = self._env.compile(self.template)
except jinja2.TemplateError as err:
raise TemplateError(err) from err
def render(
self,
variables: TemplateVarsType = None,
parse_result: bool = True,
limited: bool = False,
**kwargs: Any,
) -> Any:
"""Render given template.
If limited is True, the template is not allowed to access any function
or filter depending on hass or the state machine.
"""
if self.is_static:
if not parse_result or (self.hass and self.hass.config.legacy_templates):
return self.template
return self._parse_result(self.template)
assert self.hass is not None, "hass variable not set on template"
return run_callback_threadsafe(
self.hass.loop,
partial(self.async_render, variables, parse_result, limited, **kwargs),
).result()
@callback
def async_render(
self,
variables: TemplateVarsType = None,
parse_result: bool = True,
limited: bool = False,
strict: bool = False,
log_fn: Callable[[int, str], None] | None = None,
**kwargs: Any,
) -> Any:
"""Render given template.
This method must be run in the event loop.
If limited is True, the template is not allowed to access any function
or filter depending on hass or the state machine.
"""
self._renders += 1
if self.is_static:
if not parse_result or (self.hass and self.hass.config.legacy_templates):
return self.template
return self._parse_result(self.template)
compiled = self._compiled or self._ensure_compiled(limited, strict, log_fn)
if variables is not None:
kwargs.update(variables)
try:
render_result = _render_with_context(self.template, compiled, **kwargs)
except Exception as err:
raise TemplateError(err) from err
if len(render_result) > MAX_TEMPLATE_OUTPUT:
raise TemplateError(
f"Template output exceeded maximum size of {MAX_TEMPLATE_OUTPUT} characters"
)
render_result = render_result.strip()
if not parse_result or (self.hass and self.hass.config.legacy_templates):
return render_result
return self._parse_result(render_result)
def _parse_result(self, render_result: str) -> Any:
"""Parse the result."""
try:
return _cached_parse_result(render_result)
except (ValueError, TypeError, SyntaxError, MemoryError):
pass
return render_result
async def async_render_will_timeout(
self,
timeout: float,
variables: TemplateVarsType = None,
strict: bool = False,
log_fn: Callable[[int, str], None] | None = None,
**kwargs: Any,
) -> bool:
"""Check to see if rendering a template will timeout during render.
This is intended to check for expensive templates
that will make the system unstable. The template
is rendered in the executor to ensure it does not
tie up the event loop.
This function is not a security control and is only
intended to be used as a safety check when testing
templates.
This method must be run in the event loop.
"""
self._renders += 1
if self.is_static:
return False
compiled = self._compiled or self._ensure_compiled(strict=strict, log_fn=log_fn)
if variables is not None:
kwargs.update(variables)
self._exc_info = None
finish_event = asyncio.Event()
def _render_template() -> None:
assert self.hass is not None, "hass variable not set on template"
try:
_render_with_context(self.template, compiled, **kwargs)
except TimeoutError:
pass
except Exception: # noqa: BLE001
self._exc_info = sys.exc_info()
finally:
self.hass.loop.call_soon_threadsafe(finish_event.set)
try:
template_render_thread = ThreadWithException(target=_render_template)
template_render_thread.start()
async with asyncio.timeout(timeout):
await finish_event.wait()
if self._exc_info:
raise TemplateError(self._exc_info[1].with_traceback(self._exc_info[2]))
except TimeoutError:
template_render_thread.raise_exc(TimeoutError)
return True
finally:
template_render_thread.join()
return False
@callback
def async_render_to_info(
self,
variables: TemplateVarsType = None,
strict: bool = False,
log_fn: Callable[[int, str], None] | None = None,
**kwargs: Any,
) -> RenderInfo:
"""Render the template and collect an entity filter."""
if self.hass and self.hass.config.debug:
self.hass.verify_event_loop_thread("async_render_to_info")
self._renders += 1
render_info = RenderInfo(self)
if not self.hass:
raise RuntimeError(f"hass not set while rendering {self}")
if _render_info.get() is not None:
raise RuntimeError(
f"RenderInfo already set while rendering {self}, "
"this usually indicates the template is being rendered "
"in the wrong thread"
)
if self.is_static:
render_info._result = self.template.strip() # noqa: SLF001
render_info._freeze_static() # noqa: SLF001
return render_info
token = _render_info.set(render_info)
try:
render_info._result = self.async_render( # noqa: SLF001
variables, strict=strict, log_fn=log_fn, **kwargs
)
except TemplateError as ex:
render_info.exception = ex
finally:
_render_info.reset(token)
render_info._freeze() # noqa: SLF001
return render_info
def render_with_possible_json_value(self, value, error_value=_SENTINEL):
"""Render template with value exposed.
If valid JSON will expose value_json too.
"""
if self.is_static:
return self.template
return run_callback_threadsafe(
self.hass.loop,
self.async_render_with_possible_json_value,
value,
error_value,
).result()
@callback
def async_render_with_possible_json_value(
self,
value: Any,
error_value: Any = _SENTINEL,
variables: dict[str, Any] | None = None,
parse_result: bool = False,
) -> Any:
"""Render template with value exposed.
If valid JSON will expose value_json too.
This method must be run in the event loop.
"""
self._renders += 1
if self.is_static:
return self.template
compiled = self._compiled or self._ensure_compiled()
variables = dict(variables or {})
variables["value"] = value
try: # noqa: SIM105 - suppress is much slower
variables["value_json"] = json_loads(value)
except JSON_DECODE_EXCEPTIONS:
pass
try:
render_result = _render_with_context(
self.template, compiled, **variables
).strip()
except jinja2.TemplateError as ex:
if error_value is _SENTINEL:
_LOGGER.error(
"Error parsing value: %s (value: %s, template: %s)",
ex,
value,
self.template,
)
return value if error_value is _SENTINEL else error_value
if not parse_result or (self.hass and self.hass.config.legacy_templates):
return render_result
return self._parse_result(render_result)
def _ensure_compiled(
self,
limited: bool = False,
strict: bool = False,
log_fn: Callable[[int, str], None] | None = None,
) -> jinja2.Template:
"""Bind a template to a specific hass instance."""
self.ensure_valid()
assert self.hass is not None, "hass variable not set on template"
assert self._limited is None or self._limited == limited, (
"can't change between limited and non limited template"
)
assert self._strict is None or self._strict == strict, (
"can't change between strict and non strict template"
)
assert not (strict and limited), "can't combine strict and limited template"
assert self._log_fn is None or self._log_fn == log_fn, (
"can't change custom log function"
)
assert self._compiled_code is not None, "template code was not compiled"
self._limited = limited
self._strict = strict
self._log_fn = log_fn
env = self._env
self._compiled = jinja2.Template.from_code(
env, self._compiled_code, env.globals, None
)
return self._compiled
def __eq__(self, other):
"""Compare template with another."""
return (
self.__class__ == other.__class__
and self.template == other.template
and self.hass == other.hass
)
def __hash__(self) -> int:
"""Hash code for template."""
return self._hash_cache
def __repr__(self) -> str:
"""Representation of Template."""
return f"Template<template=({self.template}) renders={self._renders}>"
@cache
def _domain_states(hass: HomeAssistant, name: str) -> DomainStates:
return DomainStates(hass, name)
def _readonly(*args: Any, **kwargs: Any) -> Any:
"""Raise an exception when a states object is modified."""
raise RuntimeError(f"Cannot modify template States object: {args} {kwargs}")
class AllStates:
"""Class to expose all HA states as attributes."""
__setitem__ = _readonly
__delitem__ = _readonly
__slots__ = ("_hass",)
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize all states."""
self._hass = hass
def __getattr__(self, name):
"""Return the domain state."""
if "." in name:
return _get_state_if_valid(self._hass, name)
if name in _RESERVED_NAMES:
return None
if not valid_domain(name):
raise TemplateError(f"Invalid domain name '{name}'")
return _domain_states(self._hass, name)
# Jinja will try __getitem__ first and it avoids the need
# to call is_safe_attribute
__getitem__ = __getattr__
def _collect_all(self) -> None:
if (render_info := _render_info.get()) is not None:
render_info.all_states = True
def _collect_all_lifecycle(self) -> None:
if (render_info := _render_info.get()) is not None:
render_info.all_states_lifecycle = True
def __iter__(self) -> Generator[TemplateState]:
"""Return all states."""
self._collect_all()
return _state_generator(self._hass, None)
def __len__(self) -> int:
"""Return number of states."""
self._collect_all_lifecycle()
return self._hass.states.async_entity_ids_count()
def __call__(
self,
entity_id: str,
rounded: bool | object = _SENTINEL,
with_unit: bool = False,
) -> str:
"""Return the states."""
state = _get_state(self._hass, entity_id)
if state is None:
return STATE_UNKNOWN
if rounded is _SENTINEL:
rounded = with_unit
if rounded or with_unit:
return state.format_state(rounded, with_unit) # type: ignore[arg-type]
return state.state
def __repr__(self) -> str:
"""Representation of All States."""
return "<template AllStates>"
class StateTranslated:
"""Class to represent a translated state in a template."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize all states."""
self._hass = hass
def __call__(self, entity_id: str) -> str | None:
"""Retrieve translated state if available."""
state = _get_state_if_valid(self._hass, entity_id)
if state is None:
return STATE_UNKNOWN
state_value = state.state
domain = state.domain
device_class = state.attributes.get("device_class")
entry = entity_registry.async_get(self._hass).async_get(entity_id)
platform = None if entry is None else entry.platform
translation_key = None if entry is None else entry.translation_key
return async_translate_state(
self._hass, state_value, domain, platform, translation_key, device_class
)
def __repr__(self) -> str:
"""Representation of Translated state."""
return "<template StateTranslated>"
class DomainStates:
"""Class to expose a specific HA domain as attributes."""
__slots__ = ("_domain", "_hass")
__setitem__ = _readonly
__delitem__ = _readonly
def __init__(self, hass: HomeAssistant, domain: str) -> None:
"""Initialize the domain states."""