11"""Client side abstraction for commonly used REST APIs."""
22
33import logging
4- import math
4+ import random
55import time
66from typing import Any
77
1313log = logging .getLogger (__name__ )
1414
1515
16- async def fetch (url = None , method = None , body = None ):
17- """Similar to web browser JavaScript fetch."""
18- if not method :
19- method = HttpMethod .GET
20- async with aiohttp .ClientSession () as session :
21- if method == HttpMethod .GET :
22- async with session .get (url ) as response :
23- return await response
24- elif method == HttpMethod .POST :
25- async with session .post (url , data = body ) as response :
26- return await response
27- else :
28- raise NotImplementedError (
29- f"HTTP requst method { method } not implemented yet. "
30- "Contributions welcome!" )
3116
3217
3318class API :
@@ -36,27 +21,40 @@ class API:
3621 def __init__ (self , options : Any = None ):
3722 """Create API instance."""
3823 self ._options = options
24+ log .debug ('API options: %s' , options )
3925
4026 def _buildUrl (self , method : str = None ) -> str :
4127 protocol = "https://" if self ._options .secure else "http://"
42- url = \
43- protocol + \
44- self ._options .host + \
45- ":" + \
46- self ._options .port + \
47- self ._options .path + \
48- self ._options .key + \
49- "/" + \
50- method
51- queryString = "?ts=" + time .monotonous () + "" + math .random ()
28+ url = f'{ protocol } { self ._options .host } :'
29+ f'{ self ._options .port } { self ._options .path } { self ._options .key } '
30+ f'/method'
31+ queryString = f'?ts={ time .monotonic ()} { random .random ()} '
5232 url += queryString
33+ log .debug ('built url: %s' , url )
5334 return url
5435
36+ @staticmethod
37+ async def fetch (url = None , method = None , body = None ):
38+ """Similar to web browser JavaScript fetch."""
39+ if not method :
40+ method = HttpMethod .GET
41+ async with aiohttp .ClientSession () as session :
42+ if method == HttpMethod .GET :
43+ async with session .get (url ) as response :
44+ return await response
45+ elif method == HttpMethod .POST :
46+ async with session .post (url , data = body ) as response :
47+ return await response
48+ else :
49+ raise NotImplementedError (
50+ f"HTTP requst method { method } not implemented yet. "
51+ "Contributions welcome!" )
52+
5553 async def retrieveId (self ):
5654 """Get a unique ID from the server and initialize with it."""
5755 url = self ._buildUrl ("id" )
5856 try :
59- response = await fetch (url )
57+ response = await API . fetch (url )
6058 if response .status != 200 :
6159 raise ConnectionError (f'Error. Status:{ response .status } ' )
6260 return response .text ()
0 commit comments