pyemoncms 0.0.5__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.5
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
@@ -9,7 +9,7 @@ Project-URL: Bug Tracker, https://github.com/Open-Building-Management/pyemoncms/
9
9
  Classifier: Programming Language :: Python :: 3
10
10
  Classifier: License :: OSI Approved :: MIT License
11
11
  Classifier: Operating System :: OS Independent
12
- Requires-Python: >=3.10
12
+ Requires-Python: >=3.9
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
15
  Requires-Dist: aiohttp
@@ -36,17 +36,40 @@ 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():
40
- print(await client.async_list_feeds())
39
+ async def list_feeds(uuid=False):
40
+ print(await client.async_list_feeds(uuid=uuid))
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))
50
51
  loop.create_task(get_feed_fields(1))
51
- 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())
52
75
  ```
@@ -0,0 +1,59 @@
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
+ 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())
59
+ ```
@@ -0,0 +1,130 @@
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
+ try:
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)
90
+ return data
91
+
92
+ async def async_list_feeds(self, uuid: bool = False) -> list[dict[str, Any]] | None:
93
+ """Request emoncms feeds list.
94
+
95
+ return a uuid per feed if available
96
+ """
97
+ feed_data = await self.async_request("/feed/list.json")
98
+ if uuid:
99
+ uuid_data = await self.async_request("/user/getuuid.json")
100
+ if not uuid_data[SUCCESS_KEY]:
101
+ message = "no uuid available"
102
+ message = f"{message} - migrate your emoncms sensor to a newer version"
103
+ self.logger.warning(message)
104
+ if feed_data[SUCCESS_KEY] and uuid_data[SUCCESS_KEY]:
105
+ for feed in feed_data[MESSAGE_KEY]:
106
+ feed["uuid"] = f"{uuid_data[MESSAGE_KEY]}_{feed['id']}"
107
+ if feed_data[SUCCESS_KEY]:
108
+ return feed_data[MESSAGE_KEY]
109
+ return None
110
+
111
+ async def async_get_feed_fields(self, feed_id: int) -> list[str, Any] | None:
112
+ """Get all fields for a single feed."""
113
+ params = {"apikey": self.api_key, "id": feed_id}
114
+ feed_data = await self.async_request("/feed/aget.json", params=params)
115
+ if feed_data[SUCCESS_KEY]:
116
+ return feed_data[MESSAGE_KEY]
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.5
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
@@ -9,7 +9,7 @@ Project-URL: Bug Tracker, https://github.com/Open-Building-Management/pyemoncms/
9
9
  Classifier: Programming Language :: Python :: 3
10
10
  Classifier: License :: OSI Approved :: MIT License
11
11
  Classifier: Operating System :: OS Independent
12
- Requires-Python: >=3.10
12
+ Requires-Python: >=3.9
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
15
  Requires-Dist: aiohttp
@@ -36,17 +36,40 @@ 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():
40
- print(await client.async_list_feeds())
39
+ async def list_feeds(uuid=False):
40
+ print(await client.async_list_feeds(uuid=uuid))
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))
50
51
  loop.create_task(get_feed_fields(1))
51
- 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())
52
75
  ```
@@ -8,4 +8,5 @@ pyemoncms.egg-info/PKG-INFO
8
8
  pyemoncms.egg-info/SOURCES.txt
9
9
  pyemoncms.egg-info/dependency_links.txt
10
10
  pyemoncms.egg-info/requires.txt
11
- pyemoncms.egg-info/top_level.txt
11
+ pyemoncms.egg-info/top_level.txt
12
+ tests/test_async_request.py
@@ -4,3 +4,6 @@ requires = [
4
4
  "wheel"
5
5
  ]
6
6
  build-backend = "setuptools.build_meta"
7
+
8
+ [tool.pytest.ini_options]
9
+ asyncio_mode = "auto"
@@ -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.5",
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",
@@ -25,5 +25,5 @@ setuptools.setup(
25
25
  install_requires=[
26
26
  'aiohttp'
27
27
  ],
28
- python_requires=">=3.10",
28
+ python_requires=">=3.9",
29
29
  )
@@ -0,0 +1,73 @@
1
+ """Tests for async_request method."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ from aiohttp import web
7
+
8
+ root_path = os.getcwd()
9
+ sys.path.insert(0, root_path)
10
+ from pyemoncms.emoncms_client import EmoncmsClient # pylint: disable=E0401,C0413
11
+
12
+ API_KEY = "123"
13
+
14
+ FEED = {
15
+ "id":"1",
16
+ "userid":"1",
17
+ "name":"Cellule_Tcircuit",
18
+ "tag":" sofrel_circuit_Cellule",
19
+ "public":"0",
20
+ "size":"35811340",
21
+ "engine":"5",
22
+ "processList":"",
23
+ "unit":"",
24
+ "time":1665509570,
25
+ "value":17.690000534058
26
+ }
27
+
28
+ FEEDS = [ FEED ]
29
+
30
+
31
+ async def feed_list_route(request):
32
+ """Emoncms feed list route."""
33
+ if "apikey" not in request.query:
34
+ return web.json_response(False)
35
+ if request.query["apikey"] != API_KEY:
36
+ raise web.HTTPUnauthorized(text="Invalid API key")
37
+ return web.json_response(FEEDS)
38
+
39
+
40
+ def create_feed_api():
41
+ """Emoncms server."""
42
+ app = web.Application()
43
+ app.router.add_route("GET", "/feed/list.json", feed_list_route)
44
+ return app
45
+
46
+ async def test_response_ok(aiohttp_server):
47
+ """Test correct response."""
48
+ await aiohttp_server(create_feed_api(), port=8080)
49
+ client = EmoncmsClient("http://127.0.0.1:8080", API_KEY)
50
+ datas = await client.async_request("/feed/list.json")
51
+ assert FEEDS == datas["message"]
52
+
53
+ async def test_no_api_auth(aiohttp_server):
54
+ """Test incorrect API key."""
55
+ await aiohttp_server(create_feed_api(), port=8080)
56
+ client = EmoncmsClient("http://127.0.0.1:8080", "666")
57
+ datas = await client.async_request("/feed/list.json")
58
+ assert not datas["success"]
59
+ assert "401" in datas["message"]
60
+
61
+ async def test_timeout():
62
+ """Test when IP does not exist."""
63
+ client = EmoncmsClient("http://192.16.1.32:8080", API_KEY, request_timeout=1)
64
+ datas = await client.async_request("/feed/list.json")
65
+ assert not datas["success"]
66
+ assert "time out" in datas["message"]
67
+
68
+ async def test_client_error():
69
+ """Test when IP exists but client not running."""
70
+ client = EmoncmsClient("http://127.0.0.1:8081", API_KEY)
71
+ datas = await client.async_request("/feed/list.json")
72
+ assert not datas["success"]
73
+ assert "client error" in datas["message"]
pyemoncms-0.0.5/README.md DELETED
@@ -1,36 +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():
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
- loop.run_forever()
36
- ```
@@ -1,111 +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) -> list[dict[str, Any]] | None:
88
- """Request emoncms feeds list.
89
-
90
- return a uuid per feed if available
91
- """
92
- uuid_data = await self.async_request("/user/getuuid.json")
93
- feed_data = await self.async_request("/feed/list.json")
94
- if not uuid_data[SUCCESS_KEY]:
95
- message = "no uuid available"
96
- message = f"{message} - migrate your emoncms sensor to a newer version"
97
- self.logger.warning(message)
98
- if feed_data[SUCCESS_KEY] and uuid_data[SUCCESS_KEY]:
99
- for feed in feed_data[MESSAGE_KEY]:
100
- feed["uuid"] = f"{uuid_data[MESSAGE_KEY]}_{feed['id']}"
101
- if feed_data[SUCCESS_KEY]:
102
- return feed_data[MESSAGE_KEY]
103
- return None
104
-
105
- async def async_get_feed_fields(self, feed_id: int) -> list[str, Any] | None:
106
- """Get all fields for a single feed."""
107
- params = {"apikey": self.api_key, "id": feed_id}
108
- feed_data = await self.async_request("/feed/aget.json", params=params)
109
- if feed_data[SUCCESS_KEY]:
110
- return feed_data[MESSAGE_KEY]
111
- return None
File without changes
File without changes