pyemoncms 0.0.6__tar.gz → 0.0.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyemoncms
3
- Version: 0.0.6
3
+ Version: 0.0.7
4
4
  Summary: A python library to interrogate emoncms API
5
5
  Home-page: https://github.com/Open-Building-Management/pyemoncms
6
6
  Author: Alexandre CUER
@@ -44,10 +44,32 @@ async def get_feed_fields(feed_id):
44
44
 
45
45
 
46
46
  loop = asyncio.get_event_loop()
47
- loop.create_task(get_path("/feed/list.json"))
47
+ loop.create_task(get_path("feed/list.json"))
48
48
  loop.create_task(get_path("/user/getuuid.json"))
49
49
  loop.create_task(list_feeds())
50
50
  loop.create_task(list_feeds(uuid=True))
51
51
  loop.create_task(get_feed_fields(1))
52
- loop.run_forever()
52
+ try:
53
+ loop.run_forever()
54
+ except Exception:
55
+ client.logger.error("something happened")
56
+ finally:
57
+ loop.run_until_complete(client.close())
58
+ loop.close()
59
+ ```
60
+
61
+ even simpler with a context manager :
62
+
63
+ ```
64
+ async def main():
65
+ """fetches somes datas in emoncms"""
66
+ async with EmoncmsClient(url, key, request_timeout=1) as client:
67
+ client.logger.setLevel("DEBUG")
68
+ print(await client.async_request("/feed/list.json"))
69
+ print(await client.async_request("/user/getuuid.json"))
70
+ print(await client.async_list_feeds())
71
+ print(await client.async_get_feed_fields(1))
72
+
73
+ if __name__ == "__main__":
74
+ asyncio.run(main())
53
75
  ```
@@ -28,10 +28,32 @@ async def get_feed_fields(feed_id):
28
28
 
29
29
 
30
30
  loop = asyncio.get_event_loop()
31
- loop.create_task(get_path("/feed/list.json"))
31
+ loop.create_task(get_path("feed/list.json"))
32
32
  loop.create_task(get_path("/user/getuuid.json"))
33
33
  loop.create_task(list_feeds())
34
34
  loop.create_task(list_feeds(uuid=True))
35
35
  loop.create_task(get_feed_fields(1))
36
- loop.run_forever()
36
+ try:
37
+ loop.run_forever()
38
+ except Exception:
39
+ client.logger.error("something happened")
40
+ finally:
41
+ loop.run_until_complete(client.close())
42
+ loop.close()
43
+ ```
44
+
45
+ even simpler with a context manager :
46
+
47
+ ```
48
+ async def main():
49
+ """fetches somes datas in emoncms"""
50
+ async with EmoncmsClient(url, key, request_timeout=1) as client:
51
+ client.logger.setLevel("DEBUG")
52
+ print(await client.async_request("/feed/list.json"))
53
+ print(await client.async_request("/user/getuuid.json"))
54
+ print(await client.async_list_feeds())
55
+ print(await client.async_get_feed_fields(1))
56
+
57
+ if __name__ == "__main__":
58
+ asyncio.run(main())
37
59
  ```
@@ -13,10 +13,11 @@ so there is a type error if you search for a key in the response
13
13
  """
14
14
 
15
15
  import asyncio
16
+ from dataclasses import dataclass
16
17
  import logging
17
- from typing import Any
18
+ from typing import Any, TypeVar
18
19
 
19
- import aiohttp
20
+ from aiohttp import ClientError, ClientSession
20
21
 
21
22
  HTTP_STATUS = {
22
23
  400: "invalid request",
@@ -30,19 +31,19 @@ SUCCESS_KEY = "success"
30
31
 
31
32
  logging.basicConfig()
32
33
 
34
+ Self = TypeVar("Self", bound="EmoncmsClient")
33
35
 
36
+ @dataclass
34
37
  class EmoncmsClient:
35
38
  """Emoncms client."""
36
39
 
40
+ url: str = None
41
+ api_key: str = None
42
+ request_timeout: int = 20
43
+ session: ClientSession | None = None
44
+ _close_session: bool = False
37
45
  logger = logging.getLogger(__name__)
38
46
 
39
- def __init__(self, url: str, api_key: str, request_timeout: int = 20) -> None:
40
- """Initialize the client."""
41
- self.logger.info("Initializing Emoncms client")
42
- self.api_key = api_key
43
- self.url = url
44
- self.request_timeout = request_timeout
45
-
46
47
  async def async_request(
47
48
  self, path: str, params: dict[str, Any] | None = None
48
49
  ) -> dict[str, Any]:
@@ -52,36 +53,40 @@ class EmoncmsClient:
52
53
  data = {SUCCESS_KEY: False, MESSAGE_KEY: None}
53
54
  if not params:
54
55
  params = {"apikey": self.api_key}
55
- async with aiohttp.ClientSession(self.url) as session:
56
+ if self.session is None:
57
+ self.session = ClientSession()
58
+ self._close_session = True
59
+ path = path.lstrip('/')
60
+ url= f'{self.url}/{path}'
61
+ try:
62
+ response = await self.session.get(
63
+ url, timeout=self.request_timeout, params=params
64
+ )
65
+ except ClientError as er:
66
+ message = f"client error : {er}"
67
+ data[MESSAGE_KEY] = message
68
+ self.logger.error(message)
69
+ return data
70
+ except asyncio.TimeoutError:
71
+ message = "time out error"
72
+ data[MESSAGE_KEY] = message
73
+ self.logger.error(message)
74
+ return data
75
+ if response.status == 200:
76
+ data[SUCCESS_KEY] = True
77
+ json_response = await response.json()
78
+ data[MESSAGE_KEY] = json_response
56
79
  try:
57
- response = await session.get(
58
- path, timeout=self.request_timeout, params=params
59
- )
60
- except aiohttp.ClientError as er:
61
- message = f"client error : {er}"
62
- data[MESSAGE_KEY] = message
63
- self.logger.error(message)
64
- return data
65
- except asyncio.TimeoutError:
66
- message = "time out error"
67
- data[MESSAGE_KEY] = message
68
- self.logger.error(message)
69
- return data
70
- if response.status == 200:
71
- data[SUCCESS_KEY] = True
72
- json_response = await response.json()
73
- data[MESSAGE_KEY] = json_response
74
- try:
75
- if MESSAGE_KEY in json_response:
76
- data[MESSAGE_KEY] = json_response[MESSAGE_KEY]
77
- except TypeError:
78
- data[SUCCESS_KEY] = False
79
- else:
80
- message = f"error {response.status}"
81
- if response.status in HTTP_STATUS:
82
- message = f"{message} {HTTP_STATUS[response.status]}"
83
- data[MESSAGE_KEY] = message
84
- self.logger.error(message)
80
+ if MESSAGE_KEY in json_response:
81
+ data[MESSAGE_KEY] = json_response[MESSAGE_KEY]
82
+ except TypeError:
83
+ data[SUCCESS_KEY] = False
84
+ else:
85
+ message = f"error {response.status}"
86
+ if response.status in HTTP_STATUS:
87
+ message = f"{message} {HTTP_STATUS[response.status]}"
88
+ data[MESSAGE_KEY] = message
89
+ self.logger.error(message)
85
90
  return data
86
91
 
87
92
  async def async_list_feeds(self, uuid: bool = False) -> list[dict[str, Any]] | None:
@@ -110,3 +115,16 @@ class EmoncmsClient:
110
115
  if feed_data[SUCCESS_KEY]:
111
116
  return feed_data[MESSAGE_KEY]
112
117
  return None
118
+
119
+ async def close(self) -> None:
120
+ """Close open client session."""
121
+ if self.session and self._close_session:
122
+ await self.session.close()
123
+
124
+ async def __aenter__(self) -> Self:
125
+ """Async enter for context manager."""
126
+ return self
127
+
128
+ async def __aexit__(self, *_exc_info: object) -> None:
129
+ """Async exit for content manager."""
130
+ await self.close()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyemoncms
3
- Version: 0.0.6
3
+ Version: 0.0.7
4
4
  Summary: A python library to interrogate emoncms API
5
5
  Home-page: https://github.com/Open-Building-Management/pyemoncms
6
6
  Author: Alexandre CUER
@@ -44,10 +44,32 @@ async def get_feed_fields(feed_id):
44
44
 
45
45
 
46
46
  loop = asyncio.get_event_loop()
47
- loop.create_task(get_path("/feed/list.json"))
47
+ loop.create_task(get_path("feed/list.json"))
48
48
  loop.create_task(get_path("/user/getuuid.json"))
49
49
  loop.create_task(list_feeds())
50
50
  loop.create_task(list_feeds(uuid=True))
51
51
  loop.create_task(get_feed_fields(1))
52
- loop.run_forever()
52
+ try:
53
+ loop.run_forever()
54
+ except Exception:
55
+ client.logger.error("something happened")
56
+ finally:
57
+ loop.run_until_complete(client.close())
58
+ loop.close()
59
+ ```
60
+
61
+ even simpler with a context manager :
62
+
63
+ ```
64
+ async def main():
65
+ """fetches somes datas in emoncms"""
66
+ async with EmoncmsClient(url, key, request_timeout=1) as client:
67
+ client.logger.setLevel("DEBUG")
68
+ print(await client.async_request("/feed/list.json"))
69
+ print(await client.async_request("/user/getuuid.json"))
70
+ print(await client.async_list_feeds())
71
+ print(await client.async_get_feed_fields(1))
72
+
73
+ if __name__ == "__main__":
74
+ asyncio.run(main())
53
75
  ```
@@ -6,7 +6,7 @@ with open("README.md", "r", encoding="utf-8") as fh:
6
6
 
7
7
  setuptools.setup(
8
8
  name="pyemoncms",
9
- version="0.0.6",
9
+ version="0.0.7",
10
10
  author="Alexandre CUER",
11
11
  author_email="alexandre.cuer@wanadoo.fr",
12
12
  description="A python library to interrogate emoncms API",
File without changes
File without changes
File without changes