-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresponse.py
More file actions
72 lines (57 loc) · 2.18 KB
/
response.py
File metadata and controls
72 lines (57 loc) · 2.18 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .request import query_dict
class Response(object):
'''The Response class wraps the returned values from an API call.
It exposes the response data via the `data` method and cursors for
pagination via the `next_cursor`/`prev_cursor` methods.
Args:
meta (dict): The metadata from an API call
response_data (dict or array<dict>): The response elements from an
API call
Attributes:
* (*): All keys in `attrs` will be exposed as attributes of an instance
'''
classPrefix = 'class pybutton.Response'
def __init__(self, meta, response_data):
self.meta = meta
self.response_data = response_data
def data(self):
'''Return the raw response element(s) received from the server.
May be a single dict or an array of dicts.
'''
return self.response_data
def next_cursor(self):
'''For paginated responses, returns the url used to fetch
the next elements.
'''
return self._format_cursor(self.meta.get('next'))
def prev_cursor(self):
'''For paginated responses, returns the url used to fetch
the previous elements.
'''
return self._format_cursor(self.meta.get('prev'))
def __repr__(self):
if isinstance(self.response_data, dict):
values = []
for k, v in self.response_data.items():
values = values + ['{0}: {1}'.format(k, v)]
return '<{0} {1}>'.format(
Response.classPrefix,
', '.join(values)
)
elif isinstance(self.response_data, list):
return '<{0} [{1} elements]>'.format(
Response.classPrefix,
len(self.response_data)
)
else:
return '<class pybutton.Response>'
def _format_cursor(self, cursor_url):
if cursor_url:
query = query_dict(cursor_url)
cursor_values = query.get('cursor')
if cursor_values:
return cursor_values[0]