forked from npinger/base-crm-api-client
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.py
More file actions
258 lines (205 loc) · 8.86 KB
/
Copy pathclient.py
File metadata and controls
258 lines (205 loc) · 8.86 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python
"""Implements clients BaseCRM's APIs"""
import logging
logger = logging.getLogger(__name__)
import json
import requests
from v2.authentication import Password, Token
from prototype import Resource, Collection
__author__ = 'Clayton Daley III'
__copyright__ = "Copyright 2015, Clayton Daley III"
__license__ = "Apache License 2.0"
__version__ = "2.0.0"
__maintainer__ = "Clayton Daley III"
__status__ = "Development"
def _unicode_dict(d):
new_dict = dict()
for k, v in d.iteritems():
new_dict[k] = unicode(v).encode('utf-8')
return new_dict
def create_from_token(token, debug=False):
auth = Token(token)
api = Rest(auth)
api.debug = debug
return api
def create_from_password(username, password, debug=False):
auth = Password(username, password)
api = Rest(auth)
api.get_token(username, password)
api.debug = debug
return api
class UnchangedError(Exception):
pass
class ConcurrencyError(Exception):
pass
class Rest(object):
"""
The BaseAPI class is a Mediator that knows how to combine authentication an entity objects to achieve specific API
actions (get, put, post, delete). It also knows how to handle a variety of common API endpoint errors.
"""
debug = False
def __init__(self, auth):
self.auth = auth
def get(self, entity):
if not isinstance(entity, Resource):
raise TypeError("Can only get() a Resource")
headers = self.auth.headers(entity.API_VERSION)
headers['Content-Type'] = 'application/json'
logger.debug("Preparing GET with:")
logger.debug("url: %s" % entity.URL(self.debug))
logger.debug("headers: %s" % headers)
response = requests.get(url=entity.URL(self.debug), headers=headers)
if requests.codes.multiple_choices > response.status_code >= requests.codes.ok:
print("GET SUCCESS: %s" % response.text)
entity.set_data(response.json()[entity.DATA_PARENT_KEY])
else:
print("GET ERROR: %s" % response.text)
# entity is mutable, but this simplifies chaining and assignment
return entity
def save(self, entity):
if not isinstance(entity, Resource):
raise TypeError("Can only save() a Resource")
if entity.id is None:
raise ValueError("ID must be set to save(), use create() instead")
data = entity.get_data()
if len(data) == 0:
raise UnchangedError("No data to save()")
# Wrap the item in the relevant key
data = {entity.DATA_PARENT_KEY: data}
headers = self.auth.headers(entity.API_VERSION)
headers['Content-Type'] = 'application/json'
logger.debug("Preparing PUT with:")
logger.debug("url: %s" % entity.URL(self.debug))
logger.debug("headers: %s" % headers)
logger.debug("data: %s" % data)
response = requests.put(url=entity.URL(self.debug), headers=headers, data=json.dumps(data))
if requests.codes.multiple_choices > response.status_code >= requests.codes.ok:
print("PUT SUCCESS: %s" % response.text)
entity.set_data(response.json()[entity.DATA_PARENT_KEY])
else:
print("PUT ERROR: %s" % response.text)
# entity is mutable, but this simplifies chaining and assignment
return entity
def create(self, entity):
if not isinstance(entity, Resource):
raise TypeError("Can only create() a Resource")
if entity.id is not None:
raise ValueError("Contact already exists, use save() instead of create()")
data = entity.get_data()
if len(data) == 0:
raise UnchangedError("No data for create()")
# Wrap the item in the relevant key
data = {entity.DATA_PARENT_KEY: data}
headers = self.auth.headers(entity.API_VERSION)
headers['Content-Type'] = 'application/json'
logger.debug("Preparing POST with:")
logger.debug("url: %s" % entity.URL(self.debug))
logger.debug("headers: %s" % headers)
logger.debug("data: %s" % data)
response = requests.post(url=entity.URL(self.debug), headers=headers, data=json.dumps(data))
if requests.codes.multiple_choices > response.status_code >= requests.codes.ok:
print("POST SUCCESS: %s" % response.text)
entity.set_data(response.json()[entity.DATA_PARENT_KEY])
else:
print("POST ERROR: %s" % response.text)
# entity is mutable, but this simplifies chaining and assignment
return entity
def delete(self, entity):
if not isinstance(entity, Resource):
raise TypeError("Can only delete() a Resource")
if entity.id is None:
raise ValueError("ID must be set to delete()")
response = requests.delete(url=entity.URL(self.debug), headers=self.auth.headers(entity.API_VERSION))
logger.debug("Response: \n%s" % response.text)
if requests.codes.multiple_choices > response.status_code >= requests.codes.ok:
print("DELETE SUCCESS: %s" % response.text)
else:
print("DELETE ERROR: %s" % response.text)
# entity is mutable, but this simplifies chaining and assignment
return entity
def get_page(self, entity, page, per_page=20, order_by=None):
if not isinstance(entity, Collection):
raise TypeError("Can only loadpage() for a Collection")
url = entity.URL(self.debug)
headers = self.auth.headers(entity.API_VERSION)
# Add page, per_page, and order_by to format_data_get
data = entity.format_data_set()
data['page'] = page
data['per_page'] = per_page
# clean up boolean formatting
for k, v in data.iteritems():
if isinstance(data[k], bool):
if data[k]:
data[k] = 'true'
else:
data[k] = 'false'
logger.debug("Preparing GET with:")
logger.debug("url: %s" % entity.URL(self.debug))
logger.debug("headers: %s" % headers)
logger.debug("format_data_get: %s" % data)
if order_by is not None:
if order_by not in entity.ORDERS:
raise ValueError('%s is not a valid sort order for %s' % order_by, entity.__class__.__name__)
data['order_by'] = order_by
response = requests.get(url=url, params=data, headers=headers)
if requests.codes.multiple_choices > response.status_code >= requests.codes.ok:
print("GET SUCCESS: %s" % response.text)
return entity.format_page(response.json()['items'])
else:
print("GET ERROR: %s" % response.text)
class Sync(object):
"""
Sync client...
"""
@staticmethod
def start(sync_service):
"""
Establishes a Sync cursor with the server
:param sync_service: an object providing the SyncService interface
:return: the id used to pull Sync data for the sync_service's device id
"""
url = 'https://sync.futuresimple.com/api/v1/sync/start.json'
headers = sync_service.headers()
headers['Content-Type'] = 'application/json'
known_types = []
types = sync_service.types()
for type, version in types.iteritems():
known_types.append({
'known_type': {
'name': type,
'version': "api.v%d" % version
}
})
data = {
'data': known_types
}
response = requests.post(url=url, headers=headers, data=data)
if 200 <= response.status_code <= 206:
return response.json()['data']['id']
@staticmethod
def get_permission(sync_service):
url = 'https://sync.futuresimple.com/api/v1/sync/start.json'
headers = sync_service.headers()
headers['Content-Type'] = 'application/json'
response = requests.get(url=url, headers=headers)
if response.status_code == 204:
raise StopIteration("The Sync API reports that no more records are available")
# TODO: Finish logic
@staticmethod
def get_main(sync_service):
url = 'https://sync.futuresimple.com/api/v1/sync/start.json'
headers = sync_service.headers()
headers['Content-Type'] = 'application/json'
response = requests.get(url=url, headers=headers)
if response.status_code == 204:
raise StopIteration("The Sync API reports that no more records are available")
# TODO: Finish logic
@staticmethod
def ack(sync_service):
url = 'https://sync.futuresimple.com/api/v1/acks.json'
headers = sync_service.headers()
headers['Content-Type'] = 'application/json'
acks = sync_service.acks()
data = {'ack': acks}
response = requests.post(url=url, headers=headers, data=data)
# TODO: Finish logic