python-ox/ox/api.py
2011-10-13 19:28:18 +02:00

97 lines
3 KiB
Python

# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
# GPL 2011
import cookielib
import urllib2
from .utils import json
from .form import MultiPartForm
__all__ = ['API']
class API(object):
__version__ = 0.0
__name__ = 'ox'
DEBUG = False
debuglevel = 0
def __init__(self, url, cj=None):
if cj:
self._cj = cj
else:
self._cj = cookielib.CookieJar()
self._opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self._cj),
urllib2.HTTPHandler(debuglevel=self.debuglevel))
self._opener.addheaders = [
('User-Agent', '%s/%s' % (self.__name__, self.__version__))
]
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))
request.add_data(body)
result = self._opener.open(request).read().strip()
return json.loads(result)
except urllib2.HTTPError, e:
if self.DEBUG:
import webbrowser
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 self.DEBUG:
import webbrowser
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 = MultiPartForm()
form.add_field('action', action)
if data:
form.add_field('data', json.dumps(data))
return self._json_request(self.url, form)