-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource.py
75 lines (58 loc) · 1.98 KB
/
resource.py
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
try:
import json
except ImportError:
import simplejson as json
try:
from UserList import UserList
except ImportError:
from collections import UserList
class Resource(object):
"""Object wrapper for resources.
Provides an object interface to resources returned by the Soundcloud API.
"""
def __init__(self, obj):
self.obj = obj
if hasattr(self, 'origin'):
self.origin = Resource(self.origin)
def __getstate__(self):
return self.obj.items()
def __setstate__(self, items):
if not hasattr(self, 'obj'):
self.obj = {}
for key, val in items:
self.obj[key] = val
def __getattr__(self, name):
if name in self.obj:
return self.obj.get(name)
raise AttributeError
def fields(self):
return self.obj
def keys(self):
return self.obj.keys()
class ResourceList(UserList):
"""Object wrapper for lists of resources."""
def __init__(self, resources=[]):
data = [Resource(resource) for resource in resources]
super(ResourceList, self).__init__(data)
def wrapped_resource(response):
"""Return a response wrapped in the appropriate wrapper type.
Lists will be returned as a ```ResourceList``` instance,
dicts will be returned as a ```Resource``` instance.
"""
# decode response text, assuming utf-8 if unset
response_content = response.content.decode(response.encoding or 'utf-8')
try:
content = json.loads(response_content)
except ValueError:
# not JSON
content = response_content
if isinstance(content, list):
result = ResourceList(content)
else:
result = Resource(content)
if hasattr(result, 'collection'):
result.collection = ResourceList(result.collection)
result.raw_data = response_content
for attr in ('encoding', 'url', 'status_code', 'reason'):
setattr(result, attr, getattr(response, attr))
return result