fgcz / bfabricPy

API and commad line tools for b-fabric

Home Page:https://fgcz.github.io/bfabricPy/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

python3

cpanse opened this issue · comments

cp@fgcz-113:~/bin > diff bfabric-suds.py bfabric-zeep.py 
1c1
< #!/usr/bin/env python2.7
---
> #!/usr/bin/env python3
32,33c32
<     from suds.client import Client
<     from suds.client import WebFault
---
>     from zeep import Client
44,48d42
< # fixes bfabric8 wsdl problems
< import httplib
< httplib.HTTPConnection._http_vsn = 10
< httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'
< 
135,136c129
<         except WebFault, e:
<             print (e)
---
>         except:
166a160
> 
172c166
<                 print ("{}\t{}\t{}\t{}".format(x._id, x.createdby, x.modified, x.name))
---
>                 print ("{}\t{}\t{}\t{}".format(x.id, x.createdby, x.modified, x.name))
cp@fgcz-113:~/bin > 
cp@fgcz-113:~/bin > cat bfabric-*.py
#!/usr/bin/env python2.7
# -*- coding: latin1 -*-

"""

B-Fabric Appliaction Interface using WSDL

The code contains classes for wrapper_creator and submitter.

Ensure that this file is available on the bfabric exec host.

Copyright (C) 2014, 2015, 2016, 2017 Functional Genomics Center Zurich ETHZ|UZH. All rights reserved.

Authors:
  Marco Schmidt <marco.schmidt@fgcz.ethz.ch>
  Christian Panse <cp@fgcz.ethz.ch>

Licensed under GPL version 3

$Id: bfabric.py 3000 2017-08-18 14:18:30Z cpanse $
$HeadURL: http://fgcz-svn.uzh.ch/repos/scripts/trunk/linux/bfabric/apps/python/bfabric/bfabric.py $
$Date: 2017-08-18 16:18:30 +0200 (Fri, 18 Aug 2017) $
$Revision: 3000 $

"""

import yaml
import sys
from pprint import pprint

try:
    from suds.client import Client
    from suds.client import WebFault
except:
    raise

import hashlib
import os
import base64
import datetime
import re
import unittest

# fixes bfabric8 wsdl problems
import httplib
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'

class Bfabric(object):
    """
    Implements read and save object methods for BFabric wsdl interface
    """

    __version__ = "0.9.10"
    verbose = False
    bflogin = None
    bfpassword = None
    webbase = 'https://fgcz-bfabric.uzh.ch/bfabric'
    bfabricrc = dict()
    query_counter = 0
    bfabricfilename = os.path.normpath("{0}/{1}"
        .format(os.path.expanduser("~"), ".bfabricrc.py"))

    def warning(self, msg):
        sys.stderr.write("\033[93m{}\033[0m\n".format(msg))

    def _read_bfabric(self):
        if self.verbose:
            print ("self.bfabricfilename='{}'".format(self.bfabricfilename))
        if not os.path.isfile(self.bfabricfilename):
            self.warning("could not find '.bfabricrc.py' file in home directory.")
            return

        try:
            with open(self.bfabricfilename) as myfile:
                for line in myfile:
                    if not re.match("^#", line):
                        A = line.strip().replace("\"", "").replace("'", "").partition('=')
                        if not A[0] in ['_PASSWD', '_LOGIN', '_WEBBASE']:
                            continue
                        if not A[0] in self.bfabricrc:
                            self.bfabricrc[A[0]] = A[2]
                        else:
                            self.warning("while reading {0}. '{1}' is already set."
                                .format(self.bfabricfilename, A[0]))
        except:
            raise

    def __init__(self, login=None, password=None, webbase=None, externaljobid=None, bfabricrc=None, verbose=False):
        if bfabricrc:
            self.bfabricfilename = bfabricrc

        self.verbose = verbose
        self._read_bfabric()

        if '_PASSWD' in self.bfabricrc.keys() and password is None:
            password = self.bfabricrc['_PASSWD']

        if '_LOGIN' in self.bfabricrc.keys() and login is None:
            login = self.bfabricrc['_LOGIN']

        if '_WEBBASE' in self.bfabricrc.keys() and webbase is None:
            self.webbase = self.bfabricrc['_WEBBASE']

        if not login is None:
            self.bflogin = login

        if not password is None:
            self.bfpassword = password

        if not webbase is None:
            self.webbase = webbase

        if not password or not login:
            print ("login or password missing")
            raise

        if self.verbose:
            pprint(self.bfabricrc)

    def get_para(self):
        return {'bflogin': self.bflogin, 'webbase': self.webbase}

    def read_object(self, endpoint, obj):
        """
        A generic methode which can connect to any endpoint, e.g., workunit, project,
        externaljob, etc, and returns the object with the requested id.
        obj is a python dictionary which contains all the attributes of the endpoint 
        for the "query".
        """
        self.query_counter = self.query_counter + 1
        QUERY = dict(login=self.bflogin, page='', password=self.bfpassword, query=obj)
        try:
            client = Client("".join((self.webbase, '/', endpoint, "?wsdl")))
        except WebFault, e:
            print (e)
            raise

        QUERYRES = getattr(client.service.read(QUERY), endpoint, None)
        if self.verbose:
            pprint (QUERYRES)
        return QUERYRES



if __name__ == "__main__":
    bfapp = Bfabric()

    endpoints = ['access', 'annotation', 'application',
        'attachement', 'comment', 'dataset', 'executable',
        'externaljob', 'groupingvar', 'importresource', 'mail',
        'parameter', 'project', 'resource', 'sample',
        'storage', 'user', 'workunit', 'order', 'instrument']
    query_obj = {}
    
    print (len(sys.argv))

    endpoint = sys.argv[1]

    if len(sys.argv) == 4:
        attribute = sys.argv[2]
        name = sys.argv[3]
        query_obj[attribute] = name

    if endpoint in endpoints:
        res = bfapp.read_object(endpoint=endpoint, obj=query_obj)
        if len(res) == 1:
            for i in res:
                print (i)
        try:
            for x in res:
                print ("{}\t{}\t{}\t{}".format(x._id, x.createdby, x.modified, x.name))
        except:
            print (res)
    else:
        raise "1st argument must be a valid endpoint."
#!/usr/bin/env python3
# -*- coding: latin1 -*-

"""

B-Fabric Appliaction Interface using WSDL

The code contains classes for wrapper_creator and submitter.

Ensure that this file is available on the bfabric exec host.

Copyright (C) 2014, 2015, 2016, 2017 Functional Genomics Center Zurich ETHZ|UZH. All rights reserved.

Authors:
  Marco Schmidt <marco.schmidt@fgcz.ethz.ch>
  Christian Panse <cp@fgcz.ethz.ch>

Licensed under GPL version 3

$Id: bfabric.py 3000 2017-08-18 14:18:30Z cpanse $
$HeadURL: http://fgcz-svn.uzh.ch/repos/scripts/trunk/linux/bfabric/apps/python/bfabric/bfabric.py $
$Date: 2017-08-18 16:18:30 +0200 (Fri, 18 Aug 2017) $
$Revision: 3000 $

"""

import yaml
import sys
from pprint import pprint

try:
    from zeep import Client
except:
    raise

import hashlib
import os
import base64
import datetime
import re
import unittest

class Bfabric(object):
    """
    Implements read and save object methods for BFabric wsdl interface
    """

    __version__ = "0.9.10"
    verbose = False
    bflogin = None
    bfpassword = None
    webbase = 'https://fgcz-bfabric.uzh.ch/bfabric'
    bfabricrc = dict()
    query_counter = 0
    bfabricfilename = os.path.normpath("{0}/{1}"
        .format(os.path.expanduser("~"), ".bfabricrc.py"))

    def warning(self, msg):
        sys.stderr.write("\033[93m{}\033[0m\n".format(msg))

    def _read_bfabric(self):
        if self.verbose:
            print ("self.bfabricfilename='{}'".format(self.bfabricfilename))
        if not os.path.isfile(self.bfabricfilename):
            self.warning("could not find '.bfabricrc.py' file in home directory.")
            return

        try:
            with open(self.bfabricfilename) as myfile:
                for line in myfile:
                    if not re.match("^#", line):
                        A = line.strip().replace("\"", "").replace("'", "").partition('=')
                        if not A[0] in ['_PASSWD', '_LOGIN', '_WEBBASE']:
                            continue
                        if not A[0] in self.bfabricrc:
                            self.bfabricrc[A[0]] = A[2]
                        else:
                            self.warning("while reading {0}. '{1}' is already set."
                                .format(self.bfabricfilename, A[0]))
        except:
            raise

    def __init__(self, login=None, password=None, webbase=None, externaljobid=None, bfabricrc=None, verbose=False):
        if bfabricrc:
            self.bfabricfilename = bfabricrc

        self.verbose = verbose
        self._read_bfabric()

        if '_PASSWD' in self.bfabricrc.keys() and password is None:
            password = self.bfabricrc['_PASSWD']

        if '_LOGIN' in self.bfabricrc.keys() and login is None:
            login = self.bfabricrc['_LOGIN']

        if '_WEBBASE' in self.bfabricrc.keys() and webbase is None:
            self.webbase = self.bfabricrc['_WEBBASE']

        if not login is None:
            self.bflogin = login

        if not password is None:
            self.bfpassword = password

        if not webbase is None:
            self.webbase = webbase

        if not password or not login:
            print ("login or password missing")
            raise

        if self.verbose:
            pprint(self.bfabricrc)

    def get_para(self):
        return {'bflogin': self.bflogin, 'webbase': self.webbase}

    def read_object(self, endpoint, obj):
        """
        A generic methode which can connect to any endpoint, e.g., workunit, project,
        externaljob, etc, and returns the object with the requested id.
        obj is a python dictionary which contains all the attributes of the endpoint 
        for the "query".
        """
        self.query_counter = self.query_counter + 1
        QUERY = dict(login=self.bflogin, page='', password=self.bfpassword, query=obj)
        try:
            client = Client("".join((self.webbase, '/', endpoint, "?wsdl")))
        except:
            raise

        QUERYRES = getattr(client.service.read(QUERY), endpoint, None)
        if self.verbose:
            pprint (QUERYRES)
        return QUERYRES



if __name__ == "__main__":
    bfapp = Bfabric()

    endpoints = ['access', 'annotation', 'application',
        'attachement', 'comment', 'dataset', 'executable',
        'externaljob', 'groupingvar', 'importresource', 'mail',
        'parameter', 'project', 'resource', 'sample',
        'storage', 'user', 'workunit', 'order', 'instrument']
    query_obj = {}
    
    print (len(sys.argv))

    endpoint = sys.argv[1]

    if len(sys.argv) == 4:
        attribute = sys.argv[2]
        name = sys.argv[3]
        query_obj[attribute] = name

    if endpoint in endpoints:
        res = bfapp.read_object(endpoint=endpoint, obj=query_obj)

        if len(res) == 1:
            for i in res:
                print (i)
        try:
            for x in res:
                print ("{}\t{}\t{}\t{}".format(x.id, x.createdby, x.modified, x.name))
        except:
            print (res)
    else:
        raise "1st argument must be a valid endpoint."

replacing suds with suds-py3