use ox.API

This commit is contained in:
j 2011-11-06 13:40:59 +01:00
parent fbc26c4e16
commit e68dd56dda

View file

@ -345,91 +345,17 @@ class Client(object):
if os.path.exists(self.prefix()): if os.path.exists(self.prefix()):
shutil.rmtree(self.prefix()) shutil.rmtree(self.prefix())
class API(object): class API(ox.API):
def __init__(self, url, cj=None, media_cache=None): __name__ = 'pandora_client'
if cj: __version__ = __version__
self._cj = cj
else:
self._cj = cookielib.CookieJar()
self._opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self._cj),
urllib2.HTTPHandler(debuglevel=0))
self._opener.addheaders = [ def __init__(self, url, cj=None, media_cache=None):
('User-Agent', 'pandora_client/%s' % __version__) super(API, self).__init__(url, cj)
]
self.media_cache = media_cache self.media_cache = media_cache
if not self.media_cache: if not self.media_cache:
self.media_cache = default_media_cache self.media_cache = default_media_cache
self.url = url
r = self._request('api', {'docs': True})
self._properties = r['data']['actions']
self._actions = r['data']['actions'].keys()
for a in r['data']['actions']:
self._add_action(a)
def _add_method(self, method, name):
if name is None:
name = method.func_name
setattr(self.__class__, name, method)
def _add_action(self, action):
def method(self, *args, **kw):
if not kw:
if args:
kw = args[0]
else:
kw = None
return self._request(action, kw)
method.__doc__ = self._properties[action]['doc']
method.func_name = str(action)
self._add_method(method, action)
def _json_request(self, url, form):
result = {}
try:
request = urllib2.Request(str(url))
body = str(form)
request.add_header('Content-type', form.get_content_type())
request.add_header('Content-length', len(body))
#print 'Content-length', len(body), type(body)
#print 'Content-type', form.get_content_type()
request.add_data(body)
result = self._opener.open(request).read().strip()
return json.loads(result)
except urllib2.HTTPError, e:
if DEBUG:
if e.code >= 500:
with open('/tmp/error.html', 'w') as f:
f.write(e.read())
webbrowser.open_new_tab('/tmp/error.html')
result = e.read()
try:
result = json.loads(result)
except:
result = {'status':{}}
result['status']['code'] = e.code
result['status']['text'] = str(e)
return result
except:
if DEBUG:
import traceback
traceback.print_exc()
if result:
with open('/tmp/error.html', 'w') as f:
f.write(str(result))
webbrowser.open_new_tab('/tmp/error.html')
raise
def _request(self, action, data=None):
form = ox.MultiPartForm()
form.add_field('action', action)
if data:
form.add_field('data', json.dumps(data))
return self._json_request(self.url, form)
def uploadVideo(self, filename, data, profile, info=None): def uploadVideo(self, filename, data, profile, info=None):
if DEBUG: if DEBUG:
print filename.encode('utf-8') print filename.encode('utf-8')