use six.moves to get to python3-style urllib
[htsworkflow.git] / htsworkflow / util / api.py
index 4c4a6e5c3dc156b49dea72e751e390d8a8435249..f7272bce4dfe9b8b7297d0ce9faa883aac501bf4 100644 (file)
@@ -1,6 +1,8 @@
 """Common functions for accessing the HTS Workflow REST API
 """
-from ConfigParser import SafeConfigParser
+import base64
+from six.moves import configparser
+import random
 import logging
 
 # try to deal with python <2.6
@@ -11,9 +13,7 @@ except ImportError:
 
 import os
 from optparse import OptionGroup
-import urllib
-import urllib2
-import urlparse
+from six.moves import urllib
 
 LOGGER = logging.getLogger(__name__)
 
@@ -21,7 +21,7 @@ def add_auth_options(parser):
     """Add options OptParser configure authentication options
     """
     # Load defaults from the config files
-    config = SafeConfigParser()
+    config = configparser.SafeConfigParser()
     config.read([os.path.expanduser('~/.htsworkflow.ini'),
                  '/etc/htsworkflow.ini'
                  ])
@@ -47,12 +47,16 @@ def add_auth_options(parser):
     group.add_option('--sequence', default=sequence_archive,
                      help="sequence repository")
     parser.add_option_group(group)
+    return parser
 
-def make_auth_from_opts(opts, parser):
+def make_auth_from_opts(opts, parser=None):
     """Create htsw auth info dictionary from optparse info
     """
     if opts.host is None or opts.apiid is None or opts.apikey is None:
-        parser.error("Please specify host url, apiid, apikey")
+        if parser is not None:
+            parser.error("Please specify host url, apiid, apikey")
+        else:
+            raise RuntimeError("Need host, api id api key")
 
     return {'apiid': opts.apiid, 'apikey': opts.apikey }
 
@@ -123,9 +127,9 @@ def retrieve_info(url, apidata):
     Return a dictionary from the HTSworkflow API
     """
     try:
-        apipayload = urllib.urlencode(apidata)
-        web = urllib2.urlopen(url, apipayload)
-    except urllib2.URLError, e:
+        apipayload = urllib.parse.urlencode(apidata)
+        web = urllib.request.urlopen(url, apipayload)
+    except urllib.request.URLError as e:
         if hasattr(e, 'code') and e.code == 404:
             LOGGER.info("%s was not found" % (url,))
             return None
@@ -139,22 +143,54 @@ def retrieve_info(url, apidata):
     return json.loads(contents)
 
 class HtswApi(object):
-  def __init__(self, root_url, authdata):
-    self.root_url = root_url
-    self.authdata = authdata
+    def __init__(self, root_url, authdata):
+        self.root_url = root_url
+        self.authdata = authdata
+
+    def get_flowcell(self, flowcellId):
+        url = flowcell_url(self.root_url, flowcellId)
+        return retrieve_info(url, self.authdata)
 
-  def get_flowcell(self, flowcellId):
-    url = flowcell_url(self.root_url, flowcellId)
-    return retrieve_info(url, self.authdata)
+    def get_library(self, libraryId):
+        url = library_url(self.root_url, libraryId)
+        return retrieve_info(url, self.authdata)
 
-  def get_library(self, libraryId):
-    url = library_url(self.root_url, libraryId)
-    return retrieve_info(url, self.authdata)
+    def get_lanes_for_user(self, user):
+        url = lanes_for_user(self.root_url, user)
+        return retrieve_info(url, self.authdata)
 
-  def get_lanes_for_user(self, user):
-    url = lanes_for_user(self.root_url, user)
-    return retrieve_info(url, self.authdata)
+    def get_url(self, url):
+        return retrieve_info(url, self.authdata)
 
-  def get_url(self, url):
-    return retrieve_info(url, self.authdata)
+def make_django_secret_key(size=216):
+    """return key suitable for use as secret key"""
+    try:
+        source = random.SystemRandom()
+    except AttributeError as e:
+        source = random.random()
+    bits = source.getrandbits(size)
+    chars = []
+    while bits > 0:
+        byte = bits & 0xff
+        chars.append(chr(byte))
+        bits >>= 8
+    return base64.encodestring("".join(chars)).strip()
+
+if __name__ == "__main__":
+    from optparse import OptionParser
+    from pprint import pprint
+    parser = OptionParser()
+    parser = add_auth_options(parser)
+    parser.add_option('--flowcell', default=None)
+    parser.add_option('--library', default=None)
+
+    opts, args = parser.parse_args()
+    apidata =  make_auth_from_opts(opts)
+
+    api = HtswApi(opts.host, apidata)
+
+    if opts.flowcell is not None:
+        pprint(api.get_flowcell(opts.flowcell))
+    if opts.library is not None:
+        pprint(api.get_library(opts.library))