Add timeout kwarg to call_service() and API.__call__() (#2612)

Fixes #2611

Adds a timeout kwarg to call_service and API.__call__ with default set
to 5 (as per previous behavior). Will not change existing behavior but
will allow remote Python API calls to specify a longer (or shorter)
timeout if they know that a script takes longer than 5 seconds to
return.
This commit is contained in:
Nathan Henrie 2016-07-25 23:35:33 -06:00 committed by Paulus Schoutsen
parent 78c298e563
commit 9c76b30e24

View File

@ -75,7 +75,7 @@ class API(object):
return self.status == APIStatus.OK return self.status == APIStatus.OK
def __call__(self, method, path, data=None): def __call__(self, method, path, data=None, timeout=5):
"""Make a call to the Home Assistant API.""" """Make a call to the Home Assistant API."""
if data is not None: if data is not None:
data = json.dumps(data, cls=JSONEncoder) data = json.dumps(data, cls=JSONEncoder)
@ -85,10 +85,11 @@ class API(object):
try: try:
if method == METHOD_GET: if method == METHOD_GET:
return requests.get( return requests.get(
url, params=data, timeout=5, headers=self._headers) url, params=data, timeout=timeout, headers=self._headers)
else: else:
return requests.request( return requests.request(
method, url, data=data, timeout=5, headers=self._headers) method, url, data=data, timeout=timeout,
headers=self._headers)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
_LOGGER.exception("Error connecting to server") _LOGGER.exception("Error connecting to server")
@ -510,12 +511,12 @@ def get_services(api):
return {} return {}
def call_service(api, domain, service, service_data=None): def call_service(api, domain, service, service_data=None, timeout=5):
"""Call a service at the remote API.""" """Call a service at the remote API."""
try: try:
req = api(METHOD_POST, req = api(METHOD_POST,
URL_API_SERVICES_SERVICE.format(domain, service), URL_API_SERVICES_SERVICE.format(domain, service),
service_data) service_data, timeout=timeout)
if req.status_code != 200: if req.status_code != 200:
_LOGGER.error("Error calling service: %d - %s", _LOGGER.error("Error calling service: %d - %s",