Skip to content

Instantly share code, notes, and snippets.

@k4ml
Last active April 12, 2023 20:21
Show Gist options
  • Save k4ml/5889346 to your computer and use it in GitHub Desktop.
Save k4ml/5889346 to your computer and use it in GitHub Desktop.
Python client for Webfaction API
import re
import sys
import xmlrpclib
import logging
import os.path
from configobj import ConfigObj
API_URL = 'https://api.webfaction.com/'
CONF = os.path.expanduser('~/.webfrc')
class WebFactionXmlRpc(object):
'''WebFaction XML-RPC server proxy class'''
def __init__(self, login=True):
self.log = logging.getLogger('webf')
self.log.addHandler(logging.StreamHandler())
self.session_id = None
self.server = None
if login:
self.login()
def get_config(self):
'''Get configuration file from user's directory'''
if not os.path.exists(CONF):
self.log.error("Set your username/password in %s" % CONF)
self.log.error("The format is:")
self.log.error(" username=<username>")
self.log.error(" password=<password>")
sys.exit(1)
config = ConfigObj(CONF)
username = config['username']
password = config['password']
return (username, password)
def login(self):
'''Login to WebFaction and get a session_id'''
try:
http_proxy = os.environ['http_proxy']
except KeyError:
http_proxy = None
username, password = self.get_config()
self.server = xmlrpclib.Server(API_URL, transport=http_proxy)
self.session_id, account = self.server.login(username, password)
self.log.debug("self.session_id %s account %s" % (self.session_id,
account))
def _show(self, result, id_field='name', pattern=None):
for item in result:
if pattern and pattern != 'None':
to_match = item[id_field] + ' ' + item.get('description', '')
if not re.search(pattern, to_match):
continue
for key, value in item.items():
if key == id_field:
print value
else:
print "\t", "%s: " % key, value
def _call(self, command, *args):
'''Generic command'''
func = getattr(self.server, command)
try:
result = func(self.session_id, *args)
self.log.debug(result)
except xmlrpclib.Fault, errmsg:
self.log.error(errmsg)
return 1
return result
def main():
if len(sys.argv) < 2:
print 'Need command'
sys.exit(1)
command = sys.argv[1]
args = sys.argv[2:]
new_args = []
for argument in args:
if argument in ('true', 'false'):
argument = True if argument == 'true' else False
new_args.append(argument)
continue
if ':' in argument:
mapping_list = argument.split(',')
argument = [(key, val) for key, val in [mapping.split(':') for mapping in mapping_list]]
new_args += argument
continue
if ',' in argument:
argument = argument.split(',')
new_args.append(argument)
continue
new_args.append(argument)
print command, new_args
wf = WebFactionXmlRpc()
result = wf._call(command, *new_args)
wf._show(result)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment