pyemoncms 0.0.6__tar.gz → 0.0.8__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.8
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
@@ -36,18 +36,39 @@ client.logger.setLevel("DEBUG")
36
36
  async def get_path(path):
37
37
  print(await client.async_request(path))
38
38
 
39
- async def list_feeds(uuid=False):
40
- print(await client.async_list_feeds(uuid=uuid))
39
+ async def list_feeds():
40
+ print(await client.async_list_feeds())
41
41
 
42
42
  async def get_feed_fields(feed_id):
43
43
  print(await client.async_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
- loop.create_task(list_feeds(uuid=True))
51
50
  loop.create_task(get_feed_fields(1))
52
- loop.run_forever()
51
+ try:
52
+ loop.run_forever()
53
+ except Exception:
54
+ client.logger.error("something happened")
55
+ finally:
56
+ loop.run_until_complete(client.close())
57
+ loop.close()
58
+ ```
59
+
60
+ even simpler with a context manager :
61
+
62
+ ```
63
+ async def main():
64
+ """fetches somes datas in emoncms"""
65
+ async with EmoncmsClient(url, key, request_timeout=1) as client:
66
+ client.logger.setLevel("DEBUG")
67
+ print(await client.async_request("/feed/list.json"))
68
+ print(await client.async_request("/user/getuuid.json"))
69
+ print(await client.async_list_feeds())
70
+ print(await client.async_get_feed_fields(1))
71
+
72
+ if __name__ == "__main__":
73
+ asyncio.run(main())
53
74
  ```
@@ -0,0 +1,58 @@
1
+ # pyemoncms
2
+ python library for emoncms API
3
+
4
+ rely on [aiohttp](https://github.com/aio-libs/aiohttp)
5
+
6
+ to install : `pip3 install pyemoncms`
7
+
8
+ how to use :
9
+
10
+ ```
11
+ import logging
12
+ import asyncio
13
+ from pyemoncms import EmoncmsClient
14
+
15
+ key = "your32bitsAPIkey"
16
+ url = "http://url:8081"
17
+ client = EmoncmsClient(url, key, request_timeout=1)
18
+ client.logger.setLevel("DEBUG")
19
+
20
+ async def get_path(path):
21
+ print(await client.async_request(path))
22
+
23
+ async def list_feeds():
24
+ print(await client.async_list_feeds())
25
+
26
+ async def get_feed_fields(feed_id):
27
+ print(await client.async_get_feed_fields(feed_id))
28
+
29
+
30
+ loop = asyncio.get_event_loop()
31
+ loop.create_task(get_path("feed/list.json"))
32
+ loop.create_task(get_path("/user/getuuid.json"))
33
+ loop.create_task(list_feeds())
34
+ loop.create_task(get_feed_fields(1))
35
+ try:
36
+ loop.run_forever()
37
+ except Exception:
38
+ client.logger.error("something happened")
39
+ finally:
40
+ loop.run_until_complete(client.close())
41
+ loop.close()
42
+ ```
43
+
44
+ even simpler with a context manager :
45
+
46
+ ```
47
+ async def main():
48
+ """fetches somes datas in emoncms"""
49
+ async with EmoncmsClient(url, key, request_timeout=1) as client:
50
+ client.logger.setLevel("DEBUG")
51
+ print(await client.async_request("/feed/list.json"))
52
+ print(await client.async_request("/user/getuuid.json"))
53
+ print(await client.async_list_feeds())
54
+ print(await client.async_get_feed_fields(1))
55
+
56
+ if __name__ == "__main__":
57
+ asyncio.run(main())
58
+ ```
@@ -0,0 +1,123 @@
1
+ """Emoncms client.
2
+
3
+ emoncms feed module :
4
+ an inexisting json route responds by {success: false, message : "Feed does not exist"}
5
+ examples of inexisting json routes :
6
+ - feed/aget.json?id=200 if there is no feed number 200
7
+ - feed/basket.json
8
+ the feed/list.json always returns an array of json objects, which can be empty if there is no feed
9
+
10
+ emoncms user module
11
+ an inexisting json route responds by false which is not a json object
12
+ so there is a type error if you search for a key in the response
13
+ """
14
+
15
+ import asyncio
16
+ from dataclasses import dataclass
17
+ import logging
18
+ from typing import Any, TypeVar
19
+
20
+ from aiohttp import ClientError, ClientSession
21
+
22
+ HTTP_STATUS = {
23
+ 400: "invalid request",
24
+ 401: "unauthorized access",
25
+ 404: "Not found",
26
+ 406: "URI not acceptable",
27
+ }
28
+
29
+ MESSAGE_KEY = "message"
30
+ SUCCESS_KEY = "success"
31
+
32
+ logging.basicConfig()
33
+
34
+ Self = TypeVar("Self", bound="EmoncmsClient")
35
+
36
+ @dataclass
37
+ class EmoncmsClient:
38
+ """Emoncms client."""
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
45
+ logger = logging.getLogger(__name__)
46
+
47
+ async def async_request(
48
+ self, path: str, params: dict[str, Any] | None = None
49
+ ) -> dict[str, Any]:
50
+ """Request emoncms server."""
51
+ message = f"requesting emoncms on {path}"
52
+ self.logger.debug(message)
53
+ data = {SUCCESS_KEY: False, MESSAGE_KEY: None}
54
+ if not params:
55
+ params = {"apikey": self.api_key}
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
79
+ if json_response is False:
80
+ data[SUCCESS_KEY] = False
81
+ elif SUCCESS_KEY in json_response:
82
+ data = json_response
83
+ if not data[SUCCESS_KEY]:
84
+ message = data[MESSAGE_KEY].replace("ADMIN", "EMONCMS ADMIN")
85
+ self.logger.warning(message)
86
+ else:
87
+ message = f"error {response.status}"
88
+ if response.status in HTTP_STATUS:
89
+ message = f"{message} {HTTP_STATUS[response.status]}"
90
+ data[MESSAGE_KEY] = message
91
+ self.logger.error(message)
92
+ return data
93
+
94
+ async def async_list_feeds(self) -> list[dict[str, Any]] | None:
95
+ """Request emoncms feeds list.
96
+
97
+ return a uuid per feed if available
98
+ """
99
+ feed_data = await self.async_request("/feed/list.json")
100
+ if feed_data[SUCCESS_KEY]:
101
+ return feed_data[MESSAGE_KEY]
102
+ return None
103
+
104
+ async def async_get_feed_fields(self, feed_id: int) -> list[str, Any] | None:
105
+ """Get all fields for a single feed."""
106
+ params = {"apikey": self.api_key, "id": feed_id}
107
+ feed_data = await self.async_request("/feed/aget.json", params=params)
108
+ if feed_data[SUCCESS_KEY]:
109
+ return feed_data[MESSAGE_KEY]
110
+ return None
111
+
112
+ async def close(self) -> None:
113
+ """Close open client session."""
114
+ if self.session and self._close_session:
115
+ await self.session.close()
116
+
117
+ async def __aenter__(self) -> Self:
118
+ """Async enter for context manager."""
119
+ return self
120
+
121
+ async def __aexit__(self, *_exc_info: object) -> None:
122
+ """Async exit for content manager."""
123
+ 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.8
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
@@ -36,18 +36,39 @@ client.logger.setLevel("DEBUG")
36
36
  async def get_path(path):
37
37
  print(await client.async_request(path))
38
38
 
39
- async def list_feeds(uuid=False):
40
- print(await client.async_list_feeds(uuid=uuid))
39
+ async def list_feeds():
40
+ print(await client.async_list_feeds())
41
41
 
42
42
  async def get_feed_fields(feed_id):
43
43
  print(await client.async_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
- loop.create_task(list_feeds(uuid=True))
51
50
  loop.create_task(get_feed_fields(1))
52
- loop.run_forever()
51
+ try:
52
+ loop.run_forever()
53
+ except Exception:
54
+ client.logger.error("something happened")
55
+ finally:
56
+ loop.run_until_complete(client.close())
57
+ loop.close()
58
+ ```
59
+
60
+ even simpler with a context manager :
61
+
62
+ ```
63
+ async def main():
64
+ """fetches somes datas in emoncms"""
65
+ async with EmoncmsClient(url, key, request_timeout=1) as client:
66
+ client.logger.setLevel("DEBUG")
67
+ print(await client.async_request("/feed/list.json"))
68
+ print(await client.async_request("/user/getuuid.json"))
69
+ print(await client.async_list_feeds())
70
+ print(await client.async_get_feed_fields(1))
71
+
72
+ if __name__ == "__main__":
73
+ asyncio.run(main())
53
74
  ```
@@ -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.8",
10
10
  author="Alexandre CUER",
11
11
  author_email="alexandre.cuer@wanadoo.fr",
12
12
  description="A python library to interrogate emoncms API",
@@ -67,7 +67,7 @@ async def test_timeout():
67
67
 
68
68
  async def test_client_error():
69
69
  """Test when IP exists but client not running."""
70
- client = EmoncmsClient("http://127.0.0.1:8081", API_KEY)
70
+ client = EmoncmsClient("http://127.0.0.1:8087", API_KEY)
71
71
  datas = await client.async_request("/feed/list.json")
72
72
  assert not datas["success"]
73
73
  assert "client error" in datas["message"]
pyemoncms-0.0.6/README.md DELETED
@@ -1,37 +0,0 @@
1
- # pyemoncms
2
- python library for emoncms API
3
-
4
- rely on [aiohttp](https://github.com/aio-libs/aiohttp)
5
-
6
- to install : `pip3 install pyemoncms`
7
-
8
- how to use :
9
-
10
- ```
11
- import logging
12
- import asyncio
13
- from pyemoncms import EmoncmsClient
14
-
15
- key = "your32bitsAPIkey"
16
- url = "http://url:8081"
17
- client = EmoncmsClient(url, key, request_timeout=1)
18
- client.logger.setLevel("DEBUG")
19
-
20
- async def get_path(path):
21
- print(await client.async_request(path))
22
-
23
- async def list_feeds(uuid=False):
24
- print(await client.async_list_feeds(uuid=uuid))
25
-
26
- async def get_feed_fields(feed_id):
27
- print(await client.async_get_feed_fields(feed_id))
28
-
29
-
30
- loop = asyncio.get_event_loop()
31
- loop.create_task(get_path("/feed/list.json"))
32
- loop.create_task(get_path("/user/getuuid.json"))
33
- loop.create_task(list_feeds())
34
- loop.create_task(list_feeds(uuid=True))
35
- loop.create_task(get_feed_fields(1))
36
- loop.run_forever()
37
- ```
@@ -1,112 +0,0 @@
1
- """Emoncms client.
2
-
3
- emoncms feed module :
4
- an inexisting json route responds by {success: false, message : "Feed does not exist"}
5
- examples of inexisting json routes :
6
- - feed/aget.json?id=200 if there is no feed number 200
7
- - feed/basket.json
8
- the feed/list.json always returns an array of json objects, which can be empty if there is no feed
9
-
10
- emoncms user module
11
- an inexisting json route responds by false which is not a json object
12
- so there is a type error if you search for a key in the response
13
- """
14
-
15
- import asyncio
16
- import logging
17
- from typing import Any
18
-
19
- import aiohttp
20
-
21
- HTTP_STATUS = {
22
- 400: "invalid request",
23
- 401: "unauthorized access",
24
- 404: "Not found",
25
- 406: "URI not acceptable",
26
- }
27
-
28
- MESSAGE_KEY = "message"
29
- SUCCESS_KEY = "success"
30
-
31
- logging.basicConfig()
32
-
33
-
34
- class EmoncmsClient:
35
- """Emoncms client."""
36
-
37
- logger = logging.getLogger(__name__)
38
-
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
- async def async_request(
47
- self, path: str, params: dict[str, Any] | None = None
48
- ) -> dict[str, Any]:
49
- """Request emoncms server."""
50
- message = f"requesting emoncms on {path}"
51
- self.logger.debug(message)
52
- data = {SUCCESS_KEY: False, MESSAGE_KEY: None}
53
- if not params:
54
- params = {"apikey": self.api_key}
55
- async with aiohttp.ClientSession(self.url) as session:
56
- 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)
85
- return data
86
-
87
- async def async_list_feeds(self, uuid: bool = False) -> list[dict[str, Any]] | None:
88
- """Request emoncms feeds list.
89
-
90
- return a uuid per feed if available
91
- """
92
- feed_data = await self.async_request("/feed/list.json")
93
- if uuid:
94
- uuid_data = await self.async_request("/user/getuuid.json")
95
- if not uuid_data[SUCCESS_KEY]:
96
- message = "no uuid available"
97
- message = f"{message} - migrate your emoncms sensor to a newer version"
98
- self.logger.warning(message)
99
- if feed_data[SUCCESS_KEY] and uuid_data[SUCCESS_KEY]:
100
- for feed in feed_data[MESSAGE_KEY]:
101
- feed["uuid"] = f"{uuid_data[MESSAGE_KEY]}_{feed['id']}"
102
- if feed_data[SUCCESS_KEY]:
103
- return feed_data[MESSAGE_KEY]
104
- return None
105
-
106
- async def async_get_feed_fields(self, feed_id: int) -> list[str, Any] | None:
107
- """Get all fields for a single feed."""
108
- params = {"apikey": self.api_key, "id": feed_id}
109
- feed_data = await self.async_request("/feed/aget.json", params=params)
110
- if feed_data[SUCCESS_KEY]:
111
- return feed_data[MESSAGE_KEY]
112
- return None
File without changes
File without changes
File without changes