-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path__init__.py
More file actions
60 lines (50 loc) · 1.71 KB
/
__init__.py
File metadata and controls
60 lines (50 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Base details for the myStrom Python bindings."""
import asyncio
import json
import aiohttp
import async_timeout
from typing import Any, Mapping, Optional
import socket
from .exceptions import MyStromConnectionError, MyStromError
import pkg_resources
__version__ = pkg_resources.get_distribution("setuptools").version
TIMEOUT = 10
USER_AGENT = f"PythonMyStrom/{__version__}"
async def _request(
self,
uri: str,
method: str = "GET",
data: Optional[Any] = None,
json_data: Optional[dict] = None,
params: Optional[Mapping[str, str]] = None,
token: str = ''
) -> Any:
"""Handle a request to the myStrom device."""
headers = {
"User-Agent": USER_AGENT,
"Accept": "application/json, text/plain, */*",
"Token": token
}
if self._session is None:
self._session = aiohttp.ClientSession()
self._close_session = True
try:
with async_timeout.timeout(TIMEOUT):
response = await self._session.request(
method, uri, data=data, json=json_data, params=params, headers=headers,
)
except asyncio.TimeoutError as exception:
raise MyStromConnectionError(
"Timeout occurred while connecting to myStrom device."
) from exception
except (aiohttp.ClientError, socket.gaierror) as exception:
raise MyStromConnectionError(
"Error occurred while communicating with myStrom device."
) from exception
content_type = response.headers.get("Content-Type", "")
if (response.status // 100) in [4, 5]:
response.close()
if "application/json" in content_type:
response_json = await response.json()
return response_json
return response.text