Created
March 23, 2009 00:39
-
-
Save wrboyce/83353 to your computer and use it in GitHub Desktop.
Interface to the AQL (aql.co.uk/telecoms) Reseller APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Interface to the AQL (aql.co.uk/telecoms) Reseller APIs. """ | |
import urllib | |
class ApiInterface(object): | |
""" Abstract AQL API """ | |
url = '' | |
exports = () | |
def call(self, action, **kwargs): | |
kwargs.update({'action':action}) | |
data = urllib.urlencode(kwargs) | |
return urllib.urlopen(self.url, data).read() | |
class VoipApiInterface(ApiInterface): | |
""" Implements Extendted VOIP Api """ | |
url = 'http://aql.com/reseller/voipapi.php' | |
exports = ('getuser', 'changeuser', 'listusers') | |
class NumberApiInterface(ApiInterface): | |
url = { | |
'querynumber': 'http://gw1.aql.com/telecoms/checknumberapi.php', | |
'provisionnumber': 'http://gw1.aql.com/telecoms/assignnumberapi.php', | |
} | |
exports = url.keys() | |
def _call(self, url, **kwargs): | |
data = urllib.urlencode(kwargs) | |
return urllib.urlopen(url, data).read() | |
def call(self, action, **kwargs): | |
try: | |
return self._call(self.url[action], **kwargs) | |
except KeyError: | |
raise UnknownAPIFunction(action) | |
class Api(object): | |
apis = { | |
'voip': VoipApiInterface(), | |
'number': NumberApiInterface(), | |
} | |
required = ('username', 'password') | |
def __init__(self, **kwargs): | |
# attempt to build a basic dictionary of args to work from for requests | |
try: | |
self.required_args = dict((arg,kwargs[arg]) for arg in self.required) | |
except KeyError: | |
raise RequiredArgumentMissing(self.required) | |
# build a map of functions to apis for transparency | |
self._funmap = dict((f,api) for api in self.apis.itervalues() for f in api.exports) | |
def __getattr__(self, attr): | |
""" Provide a transparent interface to all known API calls. """ | |
def _dyncall(**kwargs): | |
# attempt to find the requested function's ApiInterface object | |
try: | |
api = self._funmap[attr] | |
except KeyError: | |
raise UnknownAPIFunction(attr) | |
kwargs.update(self.required_args) | |
return api.call(attr, **kwargs) | |
return _dyncall | |
# Exceptions | |
class UnknownAPIFunction(Exception): pass | |
class RequiredArgumentMissing(Exception): pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment