3
3
from urllib3 import connection_from_url
4
4
from urllib import urlencode , quote
5
5
6
+
7
+ class AdafruitIOError (Exception ):
8
+ """Base class for all Adafruit IO request failures."""
9
+ pass
10
+
11
+ class RequestError (Exception ):
12
+ """General error for a failed Adafruit IO request."""
13
+ def __init__ (self , response ):
14
+ super (RequestError , self ).__init__ ("Adafruit IO request failed: {0} {1}" .format (
15
+ response .status , response .reason ))
16
+
17
+ class ThrottlingError (AdafruitIOError ):
18
+ """Too many requests have been made to Adafruit IO in a short period of time.
19
+ Reduce the rate of requests and try again later.
20
+ """
21
+ def __init__ (self ):
22
+ super (ThrottlingError , self ).__init__ ("Exceeded the limit of Adafruit IO " \
23
+ "requests in a short period of time. Please reduce the rate of requests " \
24
+ "and try again later." )
25
+
6
26
#fork of ApiClient Class: https://github.com/shazow/apiclient
7
27
class Client (object ):
8
- #BASE_URL = 'http://localhost:3002/'
9
- BASE_URL = 'http://io.ladyada.org/'
28
+ BASE_URL = 'https://io.adafruit.com/'
10
29
11
30
def __init__ (self , key , rate_limit_lock = None ):
12
31
self .key = key
@@ -22,7 +41,17 @@ def _compose_url(self, path):
22
41
def _compose_get_url (self , path , params = None ):
23
42
return self .BASE_URL + path + '?' + urlencode (params )
24
43
44
+ def _handle_error (sefl , response ):
45
+ # Handle explicit errors.
46
+ if response .status == 429 :
47
+ raise ThrottlingError ()
48
+ # Handle all other errors (400 & 500 level HTTP responses)
49
+ elif response .status >= 400 :
50
+ raise RequestError (response )
51
+ # Else do nothing if there was no error.
52
+
25
53
def _handle_response (self , response ):
54
+ self ._handle_error (response )
26
55
return json .loads (response .data )
27
56
28
57
def _request (self , method , path , params = None ):
@@ -37,7 +66,7 @@ def _request(self, method, path, params=None):
37
66
r = self .connection_pool .urlopen (method .upper (), url , headers = headers )
38
67
else :
39
68
r = self .connection_pool .urlopen (method .upper (), url , headers = headers , body = json .dumps (params ))
40
-
69
+
41
70
return self ._handle_response (r )
42
71
43
72
def _get (self , path , ** params ):
@@ -106,4 +135,3 @@ def groups(self, group_id_or_key):
106
135
def create_group (self , group_id_or_key , data ):
107
136
path = "api/groups/{}" .format (group_id_or_key )
108
137
return self ._post (path , data )
109
-
0 commit comments