Skip to content

Commit 466ceee

Browse files
committed
Fix unclosed resources
1 parent d74c007 commit 466ceee

File tree

3 files changed

+47
-15
lines changed

3 files changed

+47
-15
lines changed

karcher/cli.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ def cli(ctx: click.Context, debug: int, output: str, country: str):
7777

7878
logging.basicConfig(level=level)
7979

80-
ctx.obj = GlobalContextObject(debug=debug, output=output, country=country.upper())
80+
ctx.obj = GlobalContextObject(
81+
debug=debug, output=output, country=country.upper())
8182

8283

8384
def safe_cli():
@@ -99,6 +100,7 @@ async def urls(ctx: click.Context):
99100

100101
kh = await KarcherHome.create(country=ctx.obj.country)
101102
d = await kh.get_urls()
103+
await kh.close()
102104

103105
ctx.obj.print(d)
104106

@@ -112,8 +114,11 @@ async def login(ctx: click.Context, username: str, password: str):
112114
"""Get user session tokens."""
113115

114116
kh = await KarcherHome.create(country=ctx.obj.country)
117+
115118
ctx.obj.print(kh.login(username, password))
116119

120+
await kh.close()
121+
117122

118123
@cli.command()
119124
@click.option('--username', '-u', default=None, help='Username to login with.')
@@ -139,6 +144,8 @@ async def devices(ctx: click.Context, username: str, password: str, auth_token:
139144
if auth_token is None:
140145
await kh.logout()
141146

147+
await kh.close()
148+
142149
ctx.obj.print(devices)
143150

144151

@@ -183,4 +190,6 @@ async def device_properties(
183190
if auth_token is None:
184191
await kh.logout()
185192

193+
await kh.close()
194+
186195
ctx.obj.print(props)

karcher/karcher.py

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,18 @@ class KarcherHome:
3232
"""Main class to access Karcher Home Robots API"""
3333

3434
@classmethod
35-
async def create(cls, country: str = 'GB', language: Language = Language.EN):
35+
async def create(cls, country: str = 'GB', language: Language = Language.EN, session: aiohttp.ClientSession = None):
3636
"""Create Karcher Home Robots API instance"""
3737

3838
self = KarcherHome()
3939
self._country = country.upper()
4040
self._base_url = REGION_URLS[get_region_by_country(self._country)]
4141
self._language = language
4242

43+
if session is not None:
44+
self._http_external = True
45+
self._http = session
46+
4347
d = await self.get_urls()
4448
# Update base URLs
4549
if d.app_api != '':
@@ -62,11 +66,27 @@ def __init__(self):
6266
self._device_props = {}
6367
self._wait_events = {}
6468

69+
def __del__(self):
70+
"""Destructor"""
71+
72+
self.close()
73+
74+
async def close(self):
75+
"""Close underlying connections"""
76+
77+
if self._mqtt is not None:
78+
self._mqtt.disconnect()
79+
self._mqtt = None
80+
81+
if self._http is not None:
82+
if self._http_external:
83+
self._http.close()
84+
self._http = None
85+
6586
async def _request(self, method: str, url: str, **kwargs) -> aiohttp.ClientResponse:
66-
session = aiohttp.ClientSession()
67-
# TODO: Fix SSL
68-
# requests.packages.urllib3.disable_warnings()
69-
# session.skip = False
87+
if self._http is None:
88+
self._http_external = False
89+
self._http = aiohttp.ClientSession()
7090

7191
headers = {}
7292
if kwargs.get('headers') is not None:
@@ -113,27 +133,32 @@ async def _request(self, method: str, url: str, **kwargs) -> aiohttp.ClientRespo
113133
headers['nonce'] = nonce
114134

115135
kwargs['headers'] = headers
136+
# TODO: Fix SSL
116137
kwargs['verify_ssl'] = False
117-
return await session.request(method, self._base_url + url, **kwargs)
138+
return await self._http.request(method, self._base_url + url, **kwargs)
118139

119140
async def _download(self, url) -> bytes:
120-
session = aiohttp.ClientSession()
121141
headers = {
122142
'User-Agent': 'Android_' + TENANT_ID,
123143
}
124144

125-
resp = await session.get(url, headers=headers)
145+
resp = await self._http.get(url, headers=headers)
126146
if resp.status != 200:
127147
raise KarcherHomeException(-1,
128148
'HTTP error: ' + str(resp.status_code))
129149

130-
return await resp.content.read(-1)
150+
data = await resp.content.read(-1)
151+
resp.close()
152+
153+
return data
131154

132155
async def _process_response(self, resp: aiohttp.ClientResponse, prop=None) -> Any:
133156
if resp.status != 200:
134157
raise KarcherHomeException(-1,
135158
'HTTP error: ' + str(resp.status))
136159
data = await resp.json()
160+
resp.close()
161+
137162
# Check for error response
138163
if data['code'] != 0:
139164
handle_error_code(data['code'], data['msg'])
@@ -252,9 +277,7 @@ async def logout(self):
252277
'POST', '/user-center/auth/logout'))
253278
self._session = None
254279

255-
if self._mqtt is not None:
256-
self._mqtt.disconnect()
257-
self._mqtt = None
280+
await self.close()
258281

259282
async def get_devices(self) -> List[Device]:
260283
"""Get all user devices."""

setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@
77
name='karcher-home',
88
packages=['karcher'],
99
include_package_data=True,
10-
version='0.4.1',
10+
version='0.4.2',
1111
license='MIT',
1212
description='Kärcher Home Robots client',
1313
long_description=open('README.md').read(),
1414
long_description_content_type='text/markdown',
1515
author='Lauris BH',
1616
author_email='lauris@nix.lv',
1717
url='https://github.com/lafriks/python-karcher',
18-
download_url='https://github.com/lafriks/python-karcher/releases/download/v0.4.1/karcher-home-0.4.1.tar.gz',
18+
download_url='https://github.com/lafriks/python-karcher/releases/download/v0.4.2/karcher-home-0.4.2.tar.gz',
1919
platforms='any',
2020
install_requires=[
2121
'click',

0 commit comments

Comments
 (0)