Skip to content

Commit

Permalink
Use helper class in original client
Browse files Browse the repository at this point in the history
  • Loading branch information
lubomir committed Sep 21, 2015
1 parent 904b791 commit 188047a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 104 deletions.
93 changes: 10 additions & 83 deletions pdc_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@

monkey_patch.monkey_patch_kerberos()

settings = {
"url": None,
"token": None,
"insecure": True,
"develop": False,
"comment": None,
}

GLOBAL_CONFIG_FILE = '/etc/pdc/client_config.json'
USER_SPECIFIC_CONFIG_FILE = expanduser('~/.config/pdc/client_config.json')
CONFIG_URL_KEY_NAME = 'host'
Expand All @@ -46,79 +38,11 @@ def read_config_file(server_alias):
return result


def set_option(name, value):
if name in settings:
if value is not None:
settings[name] = value
else:
raise KeyError("Invalid setting %s" % name)


def make_client():
if not settings['url']:
raise ValueError("Invalid pdc instance url.")
return pdc_client(**settings)


def obtain_token(pdc):
"""
Try to obtain token from all end-points that were ever used to serve the
token. If the request returns 404 NOT FOUND, retry with older version of
the URL.
"""
token_end_points = ('token/obtain',
'obtain-token',
'obtain_token')
for end_point in token_end_points:
try:
return pdc.auth[end_point]._()['token']
except beanbag.BeanBagException, e:
if e.response.status_code != 404:
raise
raise Exception('Could not obtain token from any known URL.')


def pdc_client(url, token=None, insecure=False, develop=False, debug=False, comment=None):
session = requests.Session()

if not develop:
# For local environment, we don't need to require a token,
# just access API directly.
# REQUIRED, OPTIONAL, DISABLED
session.auth = requests_kerberos.HTTPKerberosAuth(
mutual_authentication=requests_kerberos.DISABLED)

if insecure:
# turn off for servers with insecure certificates
session.verify = False

# turn off warnings about making insecure calls
if requests.__version__ < '2.4.0':
print "Requests version is too old, please upgrade to 2.4.0 or latest."
# disable all warnings, it had better to upgrade requests.
warnings.filterwarnings("ignore")
else:
requests.packages.urllib3.disable_warnings()

pdc = beanbag.BeanBag(url, session=session)

if not develop:
# For develop environment, we don't need to require a token
if not token:
token = obtain_token(pdc)
session.headers["Authorization"] = "Token %s" % token

if comment:
session.headers["PDC-Change-Comment"] = comment

return pdc, session


class PDCClient(object):
def __init__(self, server):
if not server:
raise TypeError('Server must be specified')
session = requests.Session()
self.session = requests.Session()
config = read_config_file(server)
url = server
develop = False
Expand All @@ -139,12 +63,12 @@ def __init__(self, server):
# For local environment, we don't need to require a token,
# just access API directly.
# REQUIRED, OPTIONAL, DISABLED
session.auth = requests_kerberos.HTTPKerberosAuth(
self.session.auth = requests_kerberos.HTTPKerberosAuth(
mutual_authentication=requests_kerberos.DISABLED)

if insecure:
# turn off for servers with insecure certificates
session.verify = False
self.session.verify = False
# turn off warnings about making insecure calls
if requests.__version__ < '2.4.0':
print "Requests version is too old, please upgrade to 2.4.0 or latest."
Expand All @@ -153,13 +77,13 @@ def __init__(self, server):
else:
requests.packages.urllib3.disable_warnings()

self.client = beanbag.BeanBag(url, session=session)
self.client = beanbag.BeanBag(url, session=self.session)

if not develop:
# For develop environment, we don't need to require a token
if not token:
token = self.obtain_token()
session.headers["Authorization"] = "Token %s" % token
self.session.headers["Authorization"] = "Token %s" % token

def obtain_token(self):
"""
Expand All @@ -181,8 +105,11 @@ def obtain_token(self):
def __call__(self, *args, **kwargs):
return self.client(*args, **kwargs)

def __getattr__(self, *args, **kwargs):
return self.client.__getattr__(*args, **kwargs)
def __getattr__(self, name):
return self.client.__getattr__(name)

def __getitem__(self, *args, **kwargs):
return self.client.__getitem__(*args, **kwargs)

def set_comment(self, comment):
self.session.headers["PDC-Change-Comment"] = comment
26 changes: 5 additions & 21 deletions pdc_client/bin/pdc_client
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import optparse
import sys

from beanbag import BeanBagException
from pdc_client import make_client, set_option, read_config_file, CONFIG_URL_KEY_NAME,\
CONFIG_INSECURE_KEY_NAME, CONFIG_DEVELOP_KEY_NAME, CONFIG_TOKEN_KEY_NAME
from pdc_client import PDCClient

__version__ = '0.1'

Expand All @@ -34,9 +33,8 @@ def debug_request(func):


class RequestMethod(object):
def __init__(self, client, session, resource, traceback=False, debug=False):
def __init__(self, client, resource, traceback=False, debug=False):
self.client = client
self.session = session
self.resource = resource
self.traceback = traceback
self.debug = debug
Expand Down Expand Up @@ -155,21 +153,6 @@ if __name__ == "__main__":
print "Error: can not load data from file and command line at the same time."
sys.exit(1)

config = read_config_file(options.server)
if config:
try:
set_option("url", config[CONFIG_URL_KEY_NAME])
except KeyError:
print "'%s' must be specified in configuration file." % CONFIG_URL_KEY_NAME
sys.exit(1)
else:
set_option("url", options.server)
set_option("insecure", config.get(CONFIG_INSECURE_KEY_NAME))
set_option("develop", config.get(CONFIG_DEVELOP_KEY_NAME))
set_option("token", config.get(CONFIG_TOKEN_KEY_NAME))
if options.comment:
set_option("comment", options.comment)

data = load_data(options)

if isinstance(data, dict):
Expand All @@ -179,13 +162,14 @@ if __name__ == "__main__":
data[key] = ''

try:
client, session = make_client()
client = PDCClient(options.server)
client.set_comment(options.comment)
except BeanBagException as e:
print "%d %s" % (e.response.status_code, e.response.content)
except Exception as e:
print str(e)
else:
with RequestMethod(client, session, options.resource,
with RequestMethod(client, options.resource,
options.traceback, options.debug) as request:
print json.dumps(request.dispatch(options.request, data),
indent=4, sort_keys=True)

0 comments on commit 188047a

Please sign in to comment.