Skip to content

Commit 058d56b

Browse files
committed
Fix response validation for JSON compatible #26
1 parent d961886 commit 058d56b

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

custom_components/python_script/__init__.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
"""Some dummy docs for execute_script."""
21
import hashlib
32
import logging
43

@@ -10,6 +9,7 @@
109
SupportsResponse,
1110
)
1211
from homeassistant.helpers import config_validation as cv
12+
from homeassistant.helpers.json import JSON_DUMP
1313
from homeassistant.helpers.typing import ConfigType
1414
from homeassistant.requirements import async_process_requirements
1515

@@ -105,14 +105,24 @@ def execute_script(hass: HomeAssistant, data: dict, logger, code) -> ServiceResp
105105
vars = {**globals(), **locals()}
106106
exec(code, vars)
107107
response = {
108-
k: v
109-
for k, v in vars.items()
110-
if isinstance(v, (dict, list, str, int, float, bool))
111-
and k not in globals()
112-
and k != "data"
113-
or v is None
108+
k: v for k, v in vars.items() if k not in globals() and simple_type(v)
114109
}
115110
return response
116111
except Exception as e:
117112
_LOGGER.error(f"Error executing script", exc_info=e)
118113
return {"error": str(e)}
114+
115+
116+
def simple_type(value) -> bool:
117+
"""Can be converted to JSON."""
118+
# https://github.com/AlexxIT/PythonScriptsPro/issues/26
119+
if value is None or isinstance(value, (str, int, float, bool)):
120+
return True
121+
122+
if isinstance(value, (dict, list)):
123+
try:
124+
return JSON_DUMP(value) is not None
125+
except TypeError:
126+
pass
127+
128+
return False

0 commit comments

Comments
 (0)