Close aiohttp responses (#4624)

* Close aiohttp responses

* Update generic.py
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2016-11-30 13:05:58 -08:00
1 parent b1ef5042f9
commit e5504b39ec
6 files changed
+98 -56

No files matched your search

+18 -3
View File
@@ -34,6 +34,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
password = config.get(CONF_PASSWORD)
websession = async_get_clientsession(hass)
response = None
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.post(
@@ -41,12 +42,15 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
data={
'username': username,
'password': password})
data = yield from response.json()
data = yield from response.json()
except (asyncio.TimeoutError,
aiohttp.errors.ClientError,
aiohttp.errors.ClientDisconnectedError) as error:
_LOGGER.error("Failed authentication API call: %s", error)
return False
finally:
if response is not None:
yield from response.close()
try:
token = data['data']['token']
@@ -54,17 +58,21 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
_LOGGER.error("No token. Check username and password")
return False
response = None
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = yield from websession.get(
'{}{}'.format(HOOK_ENDPOINT, 'device'),
params={"token": data['data']['token']})
data = yield from response.json()
data = yield from response.json()
except (asyncio.TimeoutError,
aiohttp.errors.ClientError,
aiohttp.errors.ClientDisconnectedError) as error:
_LOGGER.error("Failed getting devices: %s", error)
return False
finally:
if response is not None:
yield from response.close()
yield from async_add_devices(
HookSmartHome(
@@ -102,18 +110,25 @@ class HookSmartHome(SwitchDevice):
@asyncio.coroutine
def _send(self, url):
"""Send the url to the Hook API."""
response = None
try:
_LOGGER.debug("Sending: %s", url)
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = yield from websession.get(
url, params={"token": self._token})
data = yield from response.json()
data = yield from response.json()
except (asyncio.TimeoutError,
aiohttp.errors.ClientError,
aiohttp.errors.ClientDisconnectedError) as error:
_LOGGER.error("Failed setting state: %s", error)
return False
finally:
if response is not None:
yield from response.close()
_LOGGER.debug("Got: %s", data)
return data['return_value'] == '1'