Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
executable file
·668 lines (565 loc) · 18.8 KB
/
Copy pathapi.py
File metadata and controls
executable file
·668 lines (565 loc) · 18.8 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
import urllib
import requests
import json
from assembla.lib import AssemblaObject, assembla_filter
import settings
class API(object):
cache_responses = False
cache = {}
def __init__(self, key=None, secret=None):
"""
:key,
:secret
Your Assembla API access details, available from
https://www.assembla.com/user/edit/manage_clients
"""
if not key or not secret:
raise Exception(
'The Assembla API requires your API \'key\' and \'secret\', '
'accessible from https://www.assembla.com/user/edit/manage_clients'
)
self.key = key
self.secret = secret
self.session = requests.Session()
@assembla_filter
def stream(self, extra_params=None):
"""
All Events available
"""
return self._get_json(Event, extra_params=extra_params)
@assembla_filter
def spaces(self, extra_params=None):
"""
All Spaces available
"""
return self._get_json(Space, extra_params=extra_params)
def _get_json(self, model, space=None, rel_path=None, extra_params=None,
get_all=None, get_single=False):
"""
Base level method for fetching data from the API
"""
# Only API.spaces and API.event should not provide
# the `space argument
if space is None and model not in (Space, Event):
raise Exception(
'In general, `API._get_json` should always '
'be called with a `space` argument.'
)
if not extra_params:
extra_params = {}
# Handle pagination for requests carrying large amounts of data
extra_params['page'] = extra_params.get('page', 1)
# Generate the url to hit
url = '{0}/{1}/{2}.json?{3}'.format(
settings.API_ROOT_PATH,
settings.API_VERSION,
rel_path or model.rel_path,
urllib.urlencode(extra_params),
)
# If the cache is being used and the url has been hit already
if self.cache_responses and url in self.cache:
response = self.cache[url]
else:
# Fetch the data
headers = {
'X-Api-Key': self.key,
'X-Api-Secret': self.secret,
}
response = self.session.get(url=url, headers=headers)
# If the cache is being used, update it
if self.cache_responses:
self.cache[url] = response
if response.status_code == 200: # OK
json_response = response.json()
if get_single:
instance = model(data=json_response)
instance.api = self
if space:
instance.space = space
return instance
results = []
for obj in json_response:
instance = model(data=obj)
instance.api = self
if space:
instance.space = space
results.append(instance)
# If it looks like there are more pages to fetch,
# try and fetch the next one
per_page = extra_params.get('per_page', None)
if (
get_all
and per_page
and len(json_response)
and per_page == len(json_response)
):
extra_params['page'] += 1
results = results + self._get_json(model, space, rel_path, extra_params, get_all=get_all)
return results
elif response.status_code == 204: # No Content
return None if get_single else []
else: # Most likely a 404 Not Found
raise Exception(
'Code {0} returned from `{1}`. Response text: "{2}".'.format(
response.status_code,
url,
response.text
)
)
def _post_json(self, instance, space=None, rel_path=None, extra_params=None):
"""
Base level method for updating data via the API
"""
model = type(instance)
# Only API.spaces and API.event should not provide
# the `space argument
if space is None and model not in (Space, Event):
raise Exception(
'In general, `API._post_json` should always '
'be called with a `space` argument.'
)
if 'number' in instance.data:
raise AttributeError(
'You cannot create a ticket which already has a number'
)
if not extra_params:
extra_params = {}
# Generate the url to hit
url = '{0}/{1}/{2}?{3}'.format(
settings.API_ROOT_PATH,
settings.API_VERSION,
rel_path or model.rel_path,
urllib.urlencode(extra_params),
)
# Fetch the data
response = requests.post(
url=url,
data=json.dumps(instance.data),
headers={
'X-Api-Key': self.key,
'X-Api-Secret': self.secret,
'Content-type': "application/json",
},
)
if response.status_code == 201: # OK
instance = model(data=response.json())
instance.api = self
if space:
instance.space = space
return instance
else: # Most likely a 404 Not Found
raise Exception(
'Code {0} returned from `{1}`. Response text: "{2}".'.format(
response.status_code,
url,
response.text
)
)
def _put_json(self, instance, space=None, rel_path=None, extra_params=None, id_field=None):
"""
Base level method for adding new data to the API
"""
model = type(instance)
# Only API.spaces and API.event should not provide
# the `space argument
if space is None and model not in (Space, Event):
raise Exception(
'In general, `API._put_json` should always '
'be called with a `space` argument.'
)
if not extra_params:
extra_params = {}
if not id_field:
id_field = 'number'
# Generate the url to hit
url = '{0}/{1}/{2}/{3}.json?{4}'.format(
settings.API_ROOT_PATH,
settings.API_VERSION,
rel_path or model.rel_path,
instance[id_field],
urllib.urlencode(extra_params),
)
# Fetch the data
response = requests.put(
url=url,
data=json.dumps(instance.data),
headers={
'X-Api-Key': self.key,
'X-Api-Secret': self.secret,
'Content-type': "application/json",
},
)
if response.status_code == 204: # OK
return instance
else: # Most likely a 404 Not Found
raise Exception(
'Code {0} returned from `{1}`. Response text: "{2}".'.format(
response.status_code,
url,
response.text
)
)
def _delete_json(self, instance, space=None, rel_path=None, extra_params=None, id_field=None, append_to_path=None):
"""
Base level method for removing data from the API
"""
model = type(instance)
# Only API.spaces and API.event should not provide
# the `space argument
if space is None and model not in (Space, Event):
raise Exception(
'In general, `API._delete_json` should always '
'be called with a `space` argument.'
)
if not extra_params:
extra_params = {}
if not id_field:
id_field = 'number'
if not instance.get(id_field, None):
raise AttributeError(
'%s does not have a value for the id field \'%s\'' % (
instance.__class__.__name__,
id_field
)
)
# Generate the url to hit
url = '{0}/{1}/{2}/{3}{4}.json?{5}'.format(
settings.API_ROOT_PATH,
settings.API_VERSION,
rel_path or model.rel_path,
instance[id_field],
append_to_path or '',
urllib.urlencode(extra_params),
)
# Fetch the data
response = requests.delete(
url=url,
headers={
'X-Api-Key': self.key,
'X-Api-Secret': self.secret,
'Content-type': "application/json",
},
)
if response.status_code == 204: # OK
return True
else: # Most likely a 404 Not Found
raise Exception(
'Code {0} returned from `{1}`. Response text: "{2}".'.format(
response.status_code,
url,
response.text
)
)
def _bind_variables(self, instance, space):
"""
Bind related variables to the instance
"""
instance.api = self
if space:
instance.space = space
return instance
class Event(AssemblaObject):
rel_path = 'activity'
class Space(AssemblaObject):
rel_path = 'spaces'
@assembla_filter
def documents(self, extra_params=None):
"""
All Documents in this Space
"""
# Default params
params = {
'per_page': settings.MAX_PER_PAGE
}
if extra_params:
params.update(extra_params)
return self.api._get_json(
Document,
space=self,
rel_path=self._build_rel_path('documents'),
extra_params=params,
get_all=True, # Retrieve all documents in the space
)
@assembla_filter
def tickets(self, extra_params=None):
"""
All Tickets in this Space
"""
# Default params
params = {
'per_page': settings.MAX_PER_PAGE,
'report': 0, # Report 0 is all tickets
}
if extra_params:
params.update(extra_params)
return self.api._get_json(
Ticket,
space=self,
rel_path=self._build_rel_path('tickets'),
extra_params=params,
get_all=True, # Retrieve all tickets in the space
)
def ticket(self, n):
return self.api._get_json(
Ticket,
space=self,
rel_path=self._build_rel_path('tickets/{}'.format(n)),
extra_params={},
get_single=True,
)
@assembla_filter
def milestones(self, extra_params=None):
"""
All Milestones in this Space
"""
# Default params
params = {
'per_page': settings.MAX_PER_PAGE,
}
if extra_params:
params.update(extra_params)
return self.api._get_json(
Milestone,
space=self,
rel_path=self._build_rel_path('milestones/all'),
extra_params=params,
get_all=True, # Retrieve all milestones in the space
)
@assembla_filter
def tools(self, extra_params=None):
""""
All Tools in this Space
"""
return self.api._get_json(
SpaceTool,
space=self,
rel_path=self._build_rel_path('space_tools'),
extra_params=extra_params,
)
@assembla_filter
def components(self, extra_params=None):
""""
All components in this Space
"""
return self.api._get_json(
Component,
space=self,
rel_path=self._build_rel_path('ticket_components'),
extra_params=extra_params,
)
@assembla_filter
def users(self, extra_params=None):
"""
All Users with access to this Space
"""
return self.api._get_json(
User,
space=self,
rel_path=self._build_rel_path('users'),
extra_params=extra_params,
)
@assembla_filter
def tags(self, extra_params=None):
""""
All Tags in this Space
"""
return self.api._get_json(
Tag,
space=self,
rel_path=self._build_rel_path('tags'),
extra_params=extra_params,
)
@assembla_filter
def wiki_pages(self, extra_params=None):
"""
All Wiki Pages with access to this Space
"""
return self.api._get_json(
WikiPage,
space=self,
rel_path=self._build_rel_path('wiki_pages'),
extra_params=extra_params,
)
@assembla_filter
def standup_reports(self, extra_params=None):
""""
All standup report for today
"""
return self.api._get_json(
StandupReport,
space=self,
rel_path=self._build_rel_path('standup_reports'),
extra_params=extra_params,
)
def _build_rel_path(self, to_append=None):
"""
Build a relative path to the API endpoint
"""
return '{0}/{1}/{2}'.format(
self.rel_path,
self['id'],
to_append if to_append else ''
)
class SpaceTool(AssemblaObject):
pass
class Component(AssemblaObject):
pass
class Document(AssemblaObject):
pass
class Milestone(AssemblaObject):
@assembla_filter
def tickets(self, extra_params=None):
"""
All Tickets which are a part of this Milestone
"""
return filter(
lambda ticket: ticket.get('milestone_id', None) == self['id'],
self.space.tickets(extra_params=extra_params)
)
class Ticket(AssemblaObject):
def tags(self, extra_params=None):
"""
All Tags in this Ticket
"""
# Default params
params = {
'per_page': settings.MAX_PER_PAGE,
}
if extra_params:
params.update(extra_params)
return self.api._get_json(
Tag,
space=self,
rel_path=self.space._build_rel_path(
'tickets/%s/tags' % self['number']
),
extra_params=params,
get_all=True, # Retrieve all tags in the ticket
)
def milestone(self, extra_params=None):
"""
The Milestone that the Ticket is a part of
"""
if self.get('milestone_id', None):
milestones = self.space.milestones(id=self['milestone_id'], extra_params=extra_params)
if milestones:
return milestones[0]
def user(self, extra_params=None):
"""
The User currently assigned to the Ticket
"""
if self.get('assigned_to_id', None):
users = self.space.users(
id=self['assigned_to_id'],
extra_params=extra_params
)
if users:
return users[0]
def component(self, extra_params=None):
"""
The Component currently assigned to the Ticket
"""
if self.get('component_id', None):
components = self.space.components(id=self['component_id'], extra_params=extra_params)
if components:
return components[0]
@assembla_filter
def comments(self, extra_params=None):
"""
All Comments in this Ticket
"""
# Default params
params = {
'per_page': settings.MAX_PER_PAGE,
}
if extra_params:
params.update(extra_params)
return self.api._get_json(
TicketComment,
space=self,
rel_path=self.space._build_rel_path(
'tickets/%s/ticket_comments' % self['number']
),
extra_params=params,
get_all=True, # Retrieve all comments in the ticket
)
def write(self):
"""
Create or update the Ticket on Assembla
"""
if not hasattr(self, 'space'):
raise AttributeError("A ticket must have a 'space' attribute before you can write it to Assembla.")
if self.get('number'): # Modifying an existing ticket
method = self.space.api._put_json
else: # Creating a new ticket
method = self.space.api._post_json
return method(
self,
space=self.space,
rel_path=self.space._build_rel_path('tickets'),
)
def delete(self):
"""
Remove the Ticket from Assembla
"""
if not hasattr(self, 'space'):
raise AttributeError("A ticket must have a 'space' attribute before you can remove it from Assembla.")
return self.space.api._delete_json(
self,
space=self.space,
rel_path=self.space._build_rel_path('tickets'),
)
class TicketComment(AssemblaObject):
pass
class Tag(AssemblaObject):
pass
class StandupReport(AssemblaObject):
pass
class User(AssemblaObject):
@assembla_filter
def tickets(self, extra_params=None):
"""
A User's tickets across all available spaces
"""
tickets = []
for space in self.api.spaces():
tickets += filter(
lambda ticket: ticket.get('assigned_to_id', None) == self['id'],
space.tickets(extra_params=extra_params)
)
return tickets
class WikiPage(AssemblaObject):
def write(self):
"""
Create or update a Wiki Page on Assembla
"""
if not hasattr(self, 'space'):
raise AttributeError("A WikiPage must have a 'space' attribute before you can write it to Assembla.")
self.api = self.space.api
if self.get('id'): # We are modifying an existing wiki page
return self.api._put_json(
self,
space=self.space,
rel_path=self.space._build_rel_path('wiki_pages'),
id_field='id'
)
else: # Creating a new wiki page
return self.api._post_json(
self,
space=self.space,
rel_path=self.space._build_rel_path('wiki_pages'),
)
def delete(self):
"""
Remove the WikiPage from Assembla
"""
if not hasattr(self, 'space'):
raise AttributeError("A WikiPage must have a 'space' attribute before you can remove it from Assembla.")
self.api = self.space.api
return self.api._delete_json(
self,
space=self.space,
rel_path=self.space._build_rel_path('wiki_pages'),
id_field='id',
append_to_path='/container'
)