def get_times(out, to_add = {}, stops = [], lines = []): from suds.client import Client hellobus = 'https://solweb.tper.it/tperit/webservices/hellobus.asmx?wsdl' hourslots = ["00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"] minslots = ["00","15","30","45"] times = [] hbclient = Client(hellobus) hbclient.set_options(port="HelloBusSoap") for hour in hourslots: for minute in minslots: for stop in stops: for line in lines: print "getting", hour, minute, stop, line for coming in hbclient.service.QueryHellobus4ivr(stop,line, hour+minute).split("\n")[2].split(" "): if "P" in coming: time = coming.split("P")[0].strip() times.append(time) times = list(set(times)) for time in times: to_add["arrival_time"] = time[:2]+":"+time[2:] to_add["departure_time"] = time[:2]+":"+time[2:] out.writerow(to_add)
def connect(self): try: cert = os.environ[self.cert_var] except KeyError: cert = raw_input('\nEnter Certificate:\n\t') try: app = os.environ[self.app_var] except KeyError: app = raw_input('\nEnter Application name:\n\t') try: toke_fn = os.environ[self.toke_var] except KeyError: toke_fn = raw_input("Enter UserToken file location:\n\t") try: with open(toke_fn, 'r') as toke_file: toke = pickle.load(toke_file).rstrip() except IOError: toke = raw_input('\nEnter UserToken:\n\t') wsdl = 'https://ecomapi.networksolutions.com/soapservice.asmx?wsdl' #Set up the SOAP client based on the nsCommerce WSDl client = Client(wsdl) #Create security headers and pass them to the client headers = client.factory.create('SecurityCredential') headers.Application = app headers.Certificate = cert headers.UserToken = toke client.set_options(soapheaders=headers) #send the client back for manipulation self.client = client return client
class SwisClient(object): def __init__(self, username=None, password=None): self.wsdl = 'https://%s:17778/SolarWinds/InformationService/v3?wsdl' % CONF.solarwinds_host LOG.debug('wsdl = %s', self.wsdl) self.client = Client(self.wsdl, username=username, password=password) self.client.set_options(port='BasicHttpBinding_InformationService') LOG.debug('client = %s', self.client) prog = os.path.basename(sys.argv[0]) self.cursor_file = '%s/%s.cursor' % (CONF.pid_dir, prog) self.npm_event_id_cursor = None self.ucs_event_id_cursor = None if os.path.isfile(self.cursor_file): try: self.npm_event_id_cursor, self.ucs_event_id_cursor = open(self.cursor_file).read().splitlines() LOG.info('Event IDs cursor read from file: %s, %s', self.npm_event_id_cursor, self.ucs_event_id_cursor) except Exception, e: LOG.error('Failed to read event IDs from cursor file: %s', e) if not self.npm_event_id_cursor: self.npm_event_id_cursor = self._get_max_npm_event_id() LOG.info('NPM Event ID cursor queried from db: %s', self.npm_event_id_cursor) if not self.ucs_event_id_cursor: self.ucs_event_id_cursor = self._get_max_ucs_event_id() LOG.info('UCS Event ID cursor queried from db: %s', self.ucs_event_id_cursor)
def get_order_list_test(): # date_from = "2010-05-05" date_from = None date_to = None UID = "5f719f9e-3b78-4f83-8b3e-6a64cbc84206" client = Client(_DEVELOPING_ADDRESS_+'privetoffice.1cws?wsdl', location = _DEVELOPING_ADDRESS_+"privetoffice.1cws") client.set_options(cache=DocumentCache()) result = client.service.OrderLists(UID,date_from,date_to) orders = "" i = 0 for order in result[2][0]: print """ <div class="orderItem """+str(i)+""" "> <div> <span class="openOrderDownload">"""+str(order[3])+"""</span> <span>"""+str(order[2])+"""</span> <span class="orderDate">"""+str(order[1].split(" ")[0])+"""</span> </div> <p class="orderDownload"> Скачать заказ: <a href='javascript:openLink(\""""+str(order[0])+"""\","xlsx")' title="Скачать заказ в формате xls"> xls </a> <a href='javascript:openLink(\""""+str(order[0])+"""\","pdf")' title="Скачать заказ в формате pdf"> pdf </a> <a href='javascript:openLink(\""""+str(order[0])+"""\","odf")' title="Скачать заказ в формате ods"> ods </a> </p> </div> """ i = i + 1
def __init__(self, preprocessors=None, postprocessors=None, settings=None): # First, initialize the usual geocoder stuff like settings and # processors _EsriGeocodeService.__init__(self, preprocessors, postprocessors, settings) # Our suds client self._client = None # The CandidateFields returned by an ESRI geocoder. The result rows are # ordered just as they are - there are no 'keys' in the results self._fields = None # Used to map the returned results' fields to a Candidate's fields self._mapping = {} # Set up the URLs necessary to get soap and create a suds clients if 'api_key' in self._settings: self._endpoint = self._endpoint + "?token=" + self._settings['api_key'] self._client = Client(self._endpoint + '&wsdl') # WSDL's url doesn't set your token so we have to do that, too. self._client.set_options(location=self._endpoint) else: self._client = Client(self._endpoint + '?wsdl') # Grab the candidate fields for later - we'll use them in every call self.fields = self._client.service.GetCandidateFields()
def soapCreateIncident(self,summary,notes): try: client = Client(self.ITSM_URL) client.options.location = self.ITSM_LOCATION token = client.factory.create('AuthenticationInfo') token.userName = self.ITSM_USERNAME token.password = self.ITSM_PASSWORD client.set_options(soapheaders=token) result = client.service.HelpDesk_Submit_Service( Assigned_Group=self.ASSIGNED_GROUP, Assigned_Support_Company=self.ASSIGNED_SUPPORT_COMPANY, First_Name=self.FIRST_NAME, Impact=self.IMPACT, Last_Name=self.LAST_NAME, Reported_Source=self.REPORTED_SOURCE, Service_Type=self.SERVICE_TYPE, Status=self.STATUS, Action=self.ACTION, Create_Request=self.CREATE_REQUEST, Summary=summary, Notes=notes, Urgency=self.URGENCY) logging.info('ITSM Incident created. INC %s. Summary %s. Notes %s',result,summary,notes) return 0 except: logging.error('A problem ocurred when creating an Incident in ITSM. Message: %s %s. Exception: %s %s',summary,notes,str(sys.exc_info()[0]),str(sys.exc_info()[1])) return 1
def deploy_to_bas(appName, appVersion, source, url, login, password, is_library): encSource = base64.encodestring(source) BAS_WSDL_FILE = os.path.join(url,'.wsdl') client = Client(BAS_WSDL_FILE) if url.lower().startswith('https'): trans = HttpAuthUsingCert('/home/fabregas/work/BAS_new/server/conf/cert/server.crt','/home/fabregas/work/BAS_new/server/conf/cert/server.key') client.set_options(transport=trans) client.options.location = url inputVar = client.factory.create('RequestDeployApplication') inputVar.auth.login = login inputVar.auth.password = password inputVar.app_name = appName inputVar.app_version = appVersion if is_library: inputVar.app_type = 'shared_lib' else: inputVar.app_type = 'native_app' inputVar.source = encSource ret = client.service.DeployApplication(inputVar) #print ret return ret.ret_code, ret.ret_message
class JasperClient: def __init__(self,url,username,password): self.client = Client(url,username=username,password=password) def listReports(self,dir=""): req = createRequest( uriString=dir, wsType="folder", operationName="list") res = self.client.service.list(req) return [rd.get('uriString') for rd in ET.fromstring(res).findall('resourceDescriptor') if rd.get('wsType') == 'reportUnit'] def runReport(self,uri,output="PDF",params={}): """ uri should be report URI on JasperServer output may be PDF, JRPRINT, HTML, XLS, XML, CSV and RTF; default PDF but JRPRINT is useless, so don't use it params may contain parameters as a simple dict for passing to the report this method will return a dict containing 'content-type' and 'data'. """ self.client.set_options(retxml=True) # suds does not parse MIME encoded so we cancel it req = createRequest( arguments={"RUN_OUTPUT_FORMAT" : output}, uriString = uri, wsType = "reportUnit", operationName="runReport", params=params) res = self.client.service.runReport(req) self.client.set_options(retxml=False) # temporarily of course res = parseMultipart(res) return res
class sapoService(object): def __init__(self, wsdl, sapoAccessKey, loglevel = logging.ERROR): logging.basicConfig(level=loglevel) self.log = logging.getLogger('sapo.Service') self.api = Client(wsdl, autoblend=True) self.accessKey = sapoAccessKey def authenticate(self, ESBToken = None, ESBUsername = None, ESBPassword = None): # Create namespaces def_ns = ('def', 'http://services.sapo.pt/definitions') market_ns = ('market', 'http://services.sapo.pt/Metadata/Market') # Create ESBAccessKey accesskey = Element('ESBAccessKey', ns=market_ns).setText(self.accessKey) # Create ESBCredentials if ESBToken != None: token = Element('ESBToken', ns=def_ns).setText(ESBToken) credentials = Element('ESBCredentials', ns=def_ns).insert(token) self.log.debug("authenticate with ESBToken") elif ESBUsername != None and ESBPassword != None: username = Element('ESBUsername', ns=def_ns).setText(ESBUsername) password = Element('ESBPassword', ns=def_ns).setText(ESBPassword) credentials = Element('ESBCredentials', ns=def_ns).insert(password).insert(username) self.log.debug("authenticate with ESBUsername and ESBPassword") else: self.log.error("authenticate requires ESBCredentials") return False # Setup SOAP Headers self.api.set_options(soapheaders=[credentials, accesskey]) return True
def get_client(url): client = Client(url) credentials = client.factory.create('credentials') credentials.username = '******' credentials.password = '******' client.set_options(soapheaders=credentials) return client
def get_client(self, endpoint): class FixMimeMultipart(MessagePlugin): """ StudySubject.listAllByStudy replies with what looks like part of a multipart MIME message(!?) Fix this. """ def received(self, context): reply = context.reply if reply.startswith('------='): matches = re.search(r'(<SOAP-ENV:Envelope.*</SOAP-ENV:Envelope>)', reply) context.reply = matches.group(1) if endpoint not in self._clients: raise ValueError('Unknown OpenClinica API endpoint') if self._clients[endpoint] is None: client = Client( '{url}OpenClinica-ws/ws/{endpoint}/v1/{endpoint}Wsdl.wsdl'.format( url=self._base_url, endpoint=endpoint ), plugins=[FixMimeMultipart()] ) security = Security() password = hashlib.sha1(self._password).hexdigest() # SHA1, not AES as documentation says token = UsernameToken(self._username, password) security.tokens.append(token) client.set_options(wsse=security) self._clients[endpoint] = client return self._clients[endpoint]
def check_batch(mutalyzer_url): """ Check if the batch name checker can be called. """ wsdl_url = mutalyzer_url + '/services/?wsdl' service = Client(wsdl_url, cache=None).service variants = ['AB026906.1(SDHD):g.7872G>T', 'NM_003002.1:c.3_4insG', 'AL449423.14(CDKN2A_v002):c.5_400del'] data = '\n'.join(variants).encode('base64') result = service.submitBatchJob(data, 'NameChecker') job_id = result for _ in range(BATCH_MAX_POLL): try: result = service.getBatchJob(job_id) break except WebFault: time.sleep(BATCH_POLL_WAIT) else: sys.exit(1) response = result.decode('base64') assert len([_ for line in response.split('\n') if line.strip()]) - 1 == len(variants)
def soap_login(options): run_delay(options) if options.has_key("--ssl"): url = "https://" else: url = "http://" url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk" tmp_dir = tempfile.mkdtemp() tempfile.tempdir = tmp_dir atexit.register(remove_tmp_dir, tmp_dir) try: conn = Client(url + "/vimService.wsdl") conn.set_options(location = url) mo_ServiceInstance = Property('ServiceInstance') mo_ServiceInstance._type = 'ServiceInstance' ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance) mo_SessionManager = Property(ServiceContent.sessionManager.value) mo_SessionManager._type = 'SessionManager' conn.service.Login(mo_SessionManager, options["--username"], options["--password"]) except Exception: fail(EC_LOGIN_DENIED) options["ServiceContent"] = ServiceContent options["mo_SessionManager"] = mo_SessionManager return conn
def get_price(): _DEVELOPING_ADDRESS_ = "http://192.168.194.27/trimet_trade_fedorov/ws/" # _DEVELOPING_ADDRESS_ = "http://192.168.194.14/trimet_trade/ws/" _PRODUCTION_ADDRESS_ = "http://195.239.221.58:30082/trimet_trade/ws/" print "Hello, getting started<br />" _CURRENT_ADDRESS_ = _PRODUCTION_ADDRESS_ # _CURRENT_ADDRESS_ = _DEVELOPING_ADDRESS_ client = Client(_CURRENT_ADDRESS_ + "price1c.1cws?wsdl", location=_CURRENT_ADDRESS_ + "price1c.1cws", timeout=360) client.set_options(cache=DocumentCache()) print "forming new price<br />" result = client.service.GetCSV() print "trying get csv file<br />" file_csv_server = "http://195.239.221.58:30080/download/price.csv" file_csv_site = "/web/trimetru/site/www/import/price.csv" # file_csv_site = "/home/saur/web/sitenewwave/import/price.csv" import requests r = requests.get(file_csv_server) with open(file_csv_site, "wb") as csv: csv.write(r.content) print "CSV successfully loaded"
def MarketoClientFactory(ini, **kwargs): import json with open(ini) as f: ini = json.loads(f.read()) for key, item in ini.items(): ini[key] = str(item) ini.update(kwargs) wsdl = ini["wsdl"] cache = None if '://' not in wsdl: if os.path.isfile(wsdl): wsdl = 'file://' + os.path.abspath(wsdl) client = Client(wsdl, location=ini['endpoint'], cache=cache, plugins=[MarketoSignaturePlugin(ini["userid"],ini["encryption_key"])]) headers = {} client.set_options(headers=headers) if kwargs.has_key('proxy'): if kwargs['proxy'].has_key('https'): raise NotImplementedError('Connecting to a proxy over HTTPS not supported.') client.set_options(proxy=kwargs['proxy']) return client
def get_update(input): """ Returns the bus locations for a single route @params input - an integer representing the route number """ url = 'http://developer.itsmarta.com/BRDWebService/BRDService.asmx?WSDL' c = Client(url) auth_header = c.factory.create('AuthHeader') auth_header.UserName = "******" auth_header.Password = "******" c.set_options(soapheaders=auth_header) dataset = c.service.GetBRD(input).NewDataSet try: tables = dataset.Table except: return print len(tables) if len(tables) > 0: for table in tables: print table print '\n' return
def call_webservice(self, **kwargs): """Client Suds """ wsdl = kwargs.get('wsdl', '') method = kwargs.get('method', '') timeout = kwargs.get('timeout', DEFAULT_TIMEOUT) proxy = kwargs.get('proxy', False) http_proxy = kwargs.get('http_proxy', '') parameters = kwargs.get('parameters') if kwargs.get('ignore_ssl', ''): ssl._create_default_https_context = ssl._create_unverified_context imp = Import('http://schemas.xmlsoap.org/soap/encoding/') doctor = ImportDoctor(imp) client = Client(wsdl, timeout=timeout, doctor=doctor) if proxy: http_proxy = os.environ.get('HTTP_PROXY', http_proxy) client.set_options(proxy=http_proxy) if isinstance(parameters, dict): ws_value = getattr(client.service, method)(**parameters) else: if not isinstance(parameters, tuple): parameters = (parameters,) ws_value = getattr(client.service, method)(*parameters) value = node_to_dict(ws_value, {}) if isinstance(value, dict) and len(value.keys()) == 1: value = value[value.keys()[0]] return value
def get_tab_part_order(UID): # cache cleaning code # import os # import shutil # from tempfile import gettempdir as tmp # shutil.rmtree(os.path.join(tmp(), 'suds'), True) if UID is not None: client = Client(_CURRENT_ADDRESS_ + "privetoffice.1cws?wsdl", location=_CURRENT_ADDRESS_ + "privetoffice.1cws") # client.set_options(cache=None) client.set_options(cache=DocumentCache()) # print client.service.GetOrders(UID) try: result = client.service.GetTabPartOrder(UID) # return result except: return "<p>Ошибка в работе с веб сервисом</p>" # print result return result
def _load_aquo_xml(self, table, page_size=0, start_page=0, check_date=None): """ Return soap xml for aquo domain table Set page_size to 0 to get all records on a single page. Set start_page to start the page at another item. """ client = Client(self.AQUO_URL) # Because the suds client fails to tokenize (pythonize) the # returned xml Correctly, we need to do it manually via lxml / # etree. The following option Instructs suds just to return the # xml without tokenizing. client.set_options(retxml=True) request = client.factory.create('ns1:GetDomainTableRequest') request.DomaintableName = table request.PageSize = page_size request.StartPage = start_page if check_date is None: check_date = datetime.datetime.today() request.CheckDate = check_date xml_and_headers = client.service.GetDomainTable(request=request) xml = xml_and_headers.splitlines()[-2] return xml
def testWSDL(wsdlURL): replyURL = 'http://wsamplification.appspot.com/?webservice=' + wsdlURL try: client = Client(wsdlURL) wsans = ('wsa', 'http://schemas.xmlsoap.org/ws/2004/08/addressing') wsaReply = Element('ReplyTo', ns=wsans) wsaAddress = Element('Address', ns=wsans).setText(replyURL) wsaReply.insert(wsaAddress) except: print 'Moving on...' return try: client.set_options(soapheaders=wsaReply) #impl = getattr(client.service, 'submitOrderNoAck') #print impl() for method in client.wsdl.services[0].ports[0].methods.values(): print method.name result = getattr(client.service, method.name)() #print result() except suds.WebFault as detail: print 'Invoking method failed' print client except: print 'Derping...' print client
class ManageSmsService: def __init__(self, username, password, host = 'http://ws.smshosting.it'): """ManageSmsService( username, password, host = 'http://ws.smshosting.it') Instantiates an instance of ManageSmsService. Parameters: username - Your SmsHosting.it username. password - Your SmsHosting.it secret key. host - Server address. """ self.username = username self.password = password if host.endswith('/'): self.address = host + 'smsWebService/ManageSms?wsdl' else: self.address = host + '/smsWebService/ManageSms?wsdl' # Check and set up authentication if self.username is not None and self.password is not None: # Assume Basic authentication ritual self.client = Client(self.address) else: raise pySmsHostingError("Authentication failed with your provided credentials. Try again? (%s failure)" % `e.code`, e.code) self.numbers = self.client.factory.create('sendPayLoad') #print self.numbers def setNumber(self, number, customerId = None): phone = self.client.factory.create('msisdn') phone.customerId = customerId phone.number = number self.numbers.numbers.append(phone) return def send(self, text, sender = "SMSHosting.it", dateTime = None, groups = None, transactionId = None ): """send(xs:string password, xs:string username, xs:string dateTime, xs:string from, xs:string[] groups, msisdn[] numbers, xs:string text, xs:string transactionId, ) """ global errors try: result = self.client.service.send(self.password, self.username, dateTime, sender, groups, self.numbers.numbers, text, transactionId) sent = self.client.last_sent() rcvd = self.client.last_received() #print '\nreply(\n%s\n)\n' % result return result except WebFault, f: errors += 1 print f print f.fault except Exception, e: errors += 1 print e tb.print_exc()
def init_client(faults=True): ENTREPRISE_WSDL = getattr(settings, 'SALESFORCE_ENTERPRISE_WSDL') DJANGO_WSDL = getattr(settings, 'SALESFORCE_DJANGO_WSDL') SALESFORCE_ENDPOINT = getattr(settings, 'SALESFORCE_ENDPOINT') SALESFORCE_USER = getattr(settings, 'SALESFORCE_USER') SALESFORCE_PASS = getattr(settings, 'SALESFORCE_PASS') SALESFORCE_TOKEN = getattr(settings, 'SALESFORCE_TOKEN') # Use the entreprise login to get a session id entreprise_client = Client(ENTREPRISE_WSDL) #entreprise_client.wsdl.url = SALESFORCE_ENDPOINT login_result = entreprise_client.service.login(SALESFORCE_USER, SALESFORCE_PASS+SALESFORCE_TOKEN) # our client specific methods are in this specific # NOTE we have to create the endpoint url using values from the serverUrl in the loginResponse plus # the djangoAdapter schema options = urlparse(login_result.serverUrl) #DJANGO_SF_ENDPOINT = '%s://%s/services/Soap/class/dJangoAdapter' % (options.scheme, options.netloc) django_client = Client(DJANGO_WSDL, location = SALESFORCE_ENDPOINT, faults=faults) session_name_space = ('djan', 'http://soap.sforce.com/schemas/class/dJangoAdapter') session = Element('sessionId').setText(login_result.sessionId) wrapper = Element('SessionHeader') wrapper.append(session) django_client.set_options(soapheaders=wrapper) return django_client
def timbrar(self, src, opciones = { 'generarCBB': False, 'generarTXT': False, 'generarPDF': False}): try: # en caso de que src sea una ruta a archivo y no una cadena, abrir y cargar ruta if os.path.isfile(src): src = open(src, 'r').read() opciones['text2CFDI'] = base64.b64encode(src) self.opciones.update(opciones) cliente = Client(self.url) respuesta = cliente.service.requestTimbrarCFDI(self.opciones) for propiedad in ['xml', 'pdf', 'png', 'txt']: if propiedad in respuesta: self.__dict__[propiedad] = base64.b64decode(respuesta[propiedad]) if 'xml' in respuesta: xml_cfdi = ET.fromstring(self.xml) tfd = xml_cfdi.xpath('//tfd:TimbreFiscalDigital', namespaces={"tfd": "http://www.sat.gob.mx/TimbreFiscalDigital"}) self.__dict__['uuid'] = tfd[0].get('UUID') if self.debug: self.logger.info("\nSOAP request:\n %s" % cliente.last_sent()) self.logger.info("\nSOAP response:\n %s" % cliente.last_received()) return True except WebFault, e: self.__dict__['codigo_error'] = e.fault.faultcode self.__dict__['error'] = e.fault.faultstring if self.debug: self.logger.error("\nSOAP request:\n %s\nSOAP response: [%s] - %s" % (cliente.last_sent(), e.fault.faultcode, e.fault.faultstring)) return False
def __init__(self, name, url, verbose=True, cache=False): """.. rubric:: Constructor :param str name: a name e.g. Kegg, Reactome, ... :param str url: the URL of the WSDL service :param bool verbose: prints informative messages The :attr:`serv` give access to all WSDL functionalities of the service. The :attr:`methods` is an alias to self.serv.methods and returns the list of functionalities. """ super(WSDLService, self).__init__(name, url, verbose=verbose) self.logging.info("Initialising %s service (WSDL)" % self.name) self.CACHING = cache try: #: attribute to access to the methods provided by this WSDL service from suds.client import Client from suds.cache import ObjectCache oc = ObjectCache(self.settings.user_config_dir, days=0) if self.CACHING is True: self.suds = Client(self.url, cache=oc, cachingpolicy=1) else: self.suds = Client(self.url) # reference to the service self.serv = self.suds.service self._update_settings() except Exception : self.logging.error("Could not connect to the service %s " % self.url) raise Exception
def soap_setup(): # Create the service interface printDebugMessage('main', 'WSDL: ' + wsdlUrl, 1) client = Client(wsdlUrl) if outputLevel > 1: print client global dbfetch dbfetch = client.service # Set the client user-agent. clientRevision = '$Revision: 2467 $' clientVersion = '0' if len(clientRevision) > 11: clientVersion = clientRevision[11:-2] userAgent = 'EBI-Sample-Client/%s (%s; Python %s; %s) suds/%s Python-urllib/%s' % ( clientVersion, os.path.basename(__file__), platform.python_version(), platform.system(), suds.__version__, urllib2.__version__ ) printDebugMessage('main', 'userAgent: ' + userAgent, 1) httpHeaders = {'User-agent': userAgent} client.set_options(headers=httpHeaders) # Configure HTTP proxy from OS environment (e.g. http_proxy="http://proxy.example.com:8080") proxyOpts = dict() if os.environ.has_key('http_proxy'): proxyOpts['http'] = os.environ['http_proxy'].replace('http://', '') elif os.environ.has_key('HTTP_PROXY'): proxyOpts['http'] = os.environ['HTTP_PROXY'].replace('http://', '') if 'http' in proxyOpts: client.set_options(proxy=proxyOpts)
def createPayment(self, amount, currency, cardNumber, expiryMonth, expiryYear, cardSecurityCode, scheme, orderId): """ Main method, performs a createRequest payment Keyword arguments: amount -- the payment amount currency -- the currency code (978 is for Euro) cardNumber -- the credit card number expiryMonth -- the month (MM) of the credit card expiry expiryYear -- the year (YYYY) of the credit card expiry cardSecurityCode -- the security code of the credit card scheme -- the scheme of the credit card (ie 'VISA') orderId -- the identifier of the order related to the requested payment Returns: SUDS answer """ self.logger.info("'createPayment' requested for order id {} (amount: {}, currency: {})".format(orderId, amount, currency)) # Create a SUDS client of the PayZen platform client = Client(url=self.platform['wsdl']) # Each request needs a timestamp timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") # SOAP headers construction and definition headers = self.headers(timestamp) client.set_options(soapheaders=headers) # Builds the payload ## commonRequest part commonRequest = {'submissionDate': timestamp} ## paymentRequest part paymentRequest = {'amount': amount, 'currency': currency} ## orderRequest part orderRequest = {'orderId': orderId} ## cardRequest part cardRequest = { 'number': cardNumber , 'expiryMonth': expiryMonth , 'expiryYear': expiryYear , 'cardSecurityCode': cardSecurityCode , 'scheme': scheme } # Performs the query answer = client.service.createPayment( commonRequest=commonRequest, paymentRequest=paymentRequest, cardRequest=cardRequest, orderRequest=orderRequest ) # Validates the answer self.validate(client.last_received()) self.logger.info("'createPayment' response for order id {} is valid".format(orderId)) # Returns the answer return answer
class WebServiceClient: def __init__(self, webservice_type, host, port, ssl, username, password): """Base class for clients querying the Coverity web services API. Keyword arguments: webservice_type -- either 'configuration' or 'defect' host -- host of Coverity Connect port -- port of Coverity Connect ssl -- True if to use SSL username -- Coverity Connect account password -- Coverity Connect password """ url = '' if (ssl): url = 'https://' + host + ':' + port else: url = 'http://' + host + ':' + port if webservice_type == 'configuration': self.wsdlFile = url + '/ws/v9/configurationservice?wsdl' elif webservice_type == 'defect': self.wsdlFile = url + '/ws/v9/defectservice?wsdl' else: raise "unknown web service type: " + webservice_type self.client = Client(self.wsdlFile) self.security = Security() self.token = UsernameToken(username, password) self.security.tokens.append(self.token) self.client.set_options(wsse=self.security) def getwsdl(self): """Retrieve the SOAP Client.""" print(self.client)
def setSMSAOMTSoapHeader(): #http身份验证 t = HttpAuthenticated(username=SMS_USERNAME, password=SMS_PASSWORD) client = Client(SMS_WSDL_URL, transport=t,location=SMS_ISAG_URL) wsans = ('tns', SMS_NAME_SPACE) soapHeader = Element("RequestSOAPHeader",ns = wsans) spId = Element('spId',ns = wsans).setText(SMS_SOAPHEADER_SPID) #密码MD5加密 m = hashlib.md5() m.update(SMS_SOAPHEADER_SPPASSWORD) spPassword= m.hexdigest() spPassword = Element('spPassword',ns = wsans).setText(spPassword) timeStamp = Element('timeStamp',ns = wsans).setText(time.strftime('%m%d%H%M%S',time.localtime(time.time()))) productId = Element('productId',ns = wsans).setText(SMS_SOAPHEADER_PRODUCTID) transactionId = Element('transactionId',ns = wsans).setText(SMS_SOAPHEADER_TRANSID) transEnd = Element('transEnd',ns = wsans).setText(SMS_SOAPHEADER_TRANS_END) linkID = Element('linkID',ns = wsans).setText(SMS_SOAPHEADER_LINKID) OA = Element('OA',ns = wsans).setText(SMS_SOAPHEADER_OA) FA = Element('FA',ns = wsans).setText(SMS_SOAPHEADER_FA) multi_castMessaging = Element('multi_castMessaging',ns = wsans).setText(SMS_SOAPHEADER_MULTI_CASTMEG) soapHeader.append(spId) soapHeader.append(spPassword) soapHeader.append(timeStamp) soapHeader.append(productId) soapHeader.append(transactionId) soapHeader.append(transEnd) soapHeader.append(linkID) soapHeader.append(OA) soapHeader.append(FA) soapHeader.append(multi_castMessaging) client.set_options(soapheaders=soapHeader) return client
class Client(object): """ Instantiates a suds client with default parameters. Can be used as a base client (no auth) to create Marketo factory objects. """ def __init__(self, *args, **kwargs): self.wsdl = kwargs.get("wsdl", DEFAULT_WSDL) self.timeout = kwargs.get("timeout", DEFAULT_TIMEOUT) self.suds_client = SudsClient(url=self.wsdl, timeout=self.timeout) def auth(self, user_id, location, encryption_key): auth = self.create("AuthenticationHeaderInfo") auth.mktowsUserId = user_id auth.requestTimestamp = datetime.now().isoformat() auth.requestSignature = ( hmac.new(encryption_key, auth.requestTimestamp + user_id, hashlib.sha1).hexdigest().lower() ) self.suds_client.set_options(location=location, soapheaders=auth) return self def create(self, *args, **kwargs): return self.suds_client.factory.create(*args, **kwargs) def get_lead(self, lead_key): return self.suds_client.service.getLead(lead_key._to_soap()) def request_campaign(self, campaign_id, leads): return self.suds_client.service.requestCampaign("MKTOWS", str(campaign_id), leads._to_soap()) def sync_lead(self, lead, return_lead=False): return self.suds_client.service.syncLead(lead._to_soap(), return_lead, lead.get("cookie"))
class ChildcareServiceApi(object): def __init__(self): url = "https://s3-ap-northeast-1.amazonaws.com" \ "/nursery.novice.io/ReservateChildcareService.xml" self.client = Client(url) common_msg = self.client.factory.create('ComMsgHeaderRequest') common_msg.ServiceKey = CHILDCARE_SERVICE_KEY self.client.set_options(soapheaders=common_msg) def get_child_facility_item(self, search_kind, facility_id): logger.debug("Get child facility item : search_kind=%s, facility_id=%s", search_kind, facility_id) try: result = self.client.service.ChildFacilityItem("01", facility_id) except AttributeError: raise APILimitError("Getting child faiclity item API exceeds limit : facility_id=%s" % facility_id) return result def get_child_facility_list(self, search_kind, page_num): logger.debug("Get child facility list : search_kind=%s, page_num=%s", search_kind, page_num) result = self.client.service.ChildFacilityList( SearchKind="01", PageNum=page_num ) return result def get_application_waiting_result_item(self): pass
#!/usr/bin/env python3 #-*- coding:utf-8 -*- from suds.client import Client from xml.parsers.expat import ParserCreate from suds.xsd.doctor import ImportDoctor, Import # 电话号码归属地查询 url = 'http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl' client = Client(url) print(client) result = client.service.getMobileCodeInfo('18518917687') # print(result) # 天气查询 # url = 'http://ws.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl' # imp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd') # imp.filter.add('http://WebXml.com.cn/') # d = ImportDoctor(imp) # client = Client(url, doctor=d) # print(client) # result = client.service.getWeatherbyCityName("杭州") # print(result)
if __name__ == '__main__': # Code to get local ip of the machine s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) localIP = s.getsockname()[0] #Service Discovery Server URL serviceDiscoveryServerURL = ['http://'+ localIP +':8082/servicediscovery?wsdl','http://'+localIP+':8083/servicediscovery?wsdl'] #Load Balancing Server URL loadBalancingServerURL = ['http://'+ localIP +':9005/loadbalancer?wsdl','http://'+localIP+':9006/loadbalancer?wsdl'] #To registers webserver with Service Discovery server for server in serviceDiscoveryServerURL: try: discoveryClient = Client(server,timeout=5) discoveryClient.service.registerServer("",'http://'+ localIP + ':8000/aosprojectservices?wsdl') except Exception as identifier: continue #To register webserver with Load balancing server for server in loadBalancingServerURL: try: loadBalancerClient = Client(server,timeout=5) loadBalancerClient.service.registerServer("",'http://'+ localIP + ':8000/aosprojectservices?wsdl') except Exception as identifier: continue #Runs the webserver
from suds.transport.http import HttpAuthenticated from suds import WebFault from urllib2 import URLError if __name__ == "__main__": import sys try: URL_ISPYB_SAMPLE = 'http://localhost:8080/ispyb-ejb3/ispybWS/ToolsForBLSampleWebService?wsdl' URL_ISPYB_SHIPPING = 'http://localhost:8080/ispyb-ejb3/ispybWS/ToolsForShippingWebService?wsdl' URL_ISPYB_COLLECTION = 'http://localhost:8080/ispyb-ejb3/ispybWS/ToolsForCollectionWebService?wsdl' USERNAME = "******" PASSWORD = "******" clientISPYB_COLLECTION = Client(URL_ISPYB_COLLECTION, username=USERNAME, password=PASSWORD, timeout=3) clientISPYB_SAMPLE = Client(URL_ISPYB_SAMPLE, username=USERNAME, password=PASSWORD, timeout=3) clientISPYB_SHIPPING = Client(URL_ISPYB_SHIPPING, username=USERNAME, password=PASSWORD, timeout=3) response_samples = [] for i in range(1): atime = time.time() response_samples = clientISPYB_SAMPLE.service.findSampleInfoLightForProposal( 1170, "ID14-4")
def sendRequest(self, aid): url = 'http://localhost:8080/tmis-ws-laboratory/tmis-client-laboratory?wsdl' client = Client(url, username='', password='', cache=None) client.service.sendAnalysisRequest(aid)
CURRENTNORM = 15.5 # conversion to amperes from ADC PACHUBE_KEY = "" # send feeds to Sen.se SENSEURL = "http://api.sen.se/events/?sense_key=" SENSE_KEY = "" # for ThingSpeak.com THINGSPEAKURL = "api.thingspeak.com" THINGSPEAK_KEY = "" # data logger settings (uses suds libs) TINAJALOGURL = "datalogger.asmx" logwsdl = TINAJALOGURL + "?wsdl" client = Client(logwsdl) # Twitter credentials twitterusername = "******" twitterpassword = "" # open up the FTDI serial port to get data transmitted to xbee try: ser = serial.Serial(SERIALPORT, BAUDRATE) ser.open() print "TLSM - serial port opened..." syslog.syslog("TLSM.opening: serial port opened...") except Exception, e: print "Serial port exception: " + str(e) syslog.syslog("TLSM.opening exception: serial port: " + str(e)) sys.exit(0)
from suds.client import Client import traceback as tb errors = 0 def start(url): print('\n______________________________________________________________\n') print('Test @ ( %s )' % (url,)) try: url = 'http://localhost:9090/jasperserver-pro/services/repository?wsdl' start(url) client = Client(url, username='******', password='******') print(client) print(client.service.list('')) except WebFault, f: errors += 1 print(f) print(f.fault) except (KeyboardInterrupt, SystemExit): raise except Exception: errors += 1 print(sys.exc_info()[1]) tb.print_exc() print('\nFinished: errors = %d' % (errors,))
__author__ = 'mwas' import os from suds.client import Client # path of weather wsdl file weather_wsdl_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "Weather.asmx.xml")) weather_wsdl_url = "file://" + weather_wsdl_path weather_client = Client(weather_wsdl_url) # a simple example for one of the methods print weather_client.service.GetWeatherInformation()
# 1. Download suds. # # https://fedorahosted.org/releases/s/u/suds/python-suds-0.4.tar.gz # # 2. This sample may be found on GitHub at: # # https://github.com/Vindicia/CashBoxAPISamples/tree/master/Select/Python # # # Reference: # # http://developer.vindicia.com/docs/soap/Select.html?ver=1.1 (refundTransactions) # # from suds.client import Client client = Client('https://soap.vindicia.com/1.1/Select.wsdl') #client.set_options(location='https://soap.prodtest.sj.vindicia.com/soap.pl') authentication = client.factory.create('vin:Authentication') authentication.version = '1.1' authentication.userAgent = 'Vindicia Python Select v1.1 Library' authentication.evid = None env = dict(line.strip().replace(' ', '').split('=') for line in open('Environment.properties') if not line.startswith('#') and not line.startswith('\n')) #print env login = env['soap_login'] password = env['soap_password']
) #logging.getLogger('suds.client').setLevel(logging.DEBUG) def start(url): global errors print '\n________________________________________________________________\n' print 'Test @ ( %s )\nerrors = %d\n' % (url, errors) try: url = 'http://localhost:8081/axis/services/basic-rpc-encoded?wsdl' start(url) t = HttpAuthenticated(**credentials) client = Client(url, transport=t, cache=None, plugins=myplugins) print client # # create a name object using the wsdl # print 'create name' name = client.factory.create('ns0:Name') name.first = u'jeff' + unichr(1234) name.last = 'ortel' print name # # create a phone object using the wsdl # print 'create phone' phoneA = client.factory.create('ns0:Phone') phoneA.npa = 410
#!/usr/bin/python # # api_mail_get_client_unpaid_invoices # scripted in 2015 by [email protected] for the MyAdmin API # # This Function Applies to the Mail Services services. # This function returns a list of all the unpaid invoices matching the module # passed.. # # @param sid string the *Session ID* you get from the [login](#login) call # from suds.client import Client client = Client("https://my.interserver.net/api.php?wsdl") #print client ## shows detailed client info sid = client.service.api_login(argv[1], argv[2]) if (sid == '') die("Got a blank session") print "Got Session ID "+sid+"\n" result = client.service.api_mail_get_client_unpaid_invoices() print result
def download_metadata_metadata(job, org): org.status = 'Downloading Metadata' org.save() try: # instantiate the metadata WSDL metadata_client = Client( 'http://sforgcompare.herokuapp.com/static/metadata-' + str(settings.SALESFORCE_API_VERSION) + '.xml') # URL for metadata API metadata_url = org.instance_url + '/services/Soap/m/' + str( settings.SALESFORCE_API_VERSION) + '.0/' + org.org_id # set the metadata url based on the login result metadata_client.set_options(location=metadata_url) # set the session id from the login result session_header = metadata_client.factory.create("SessionHeader") session_header.sessionId = org.access_token metadata_client.set_options(soapheaders=session_header) # query for the list of metadata types all_metadata = metadata_client.service.describeMetadata( settings.SALESFORCE_API_VERSION) # Components for listing metadata component_list = [] loop_counter = 0 # loop through metadata types for component_type in all_metadata[0]: # create the component type record and save component_type_record = ComponentType() component_type_record.org = org component_type_record.name = component_type.xmlName component_type_record.save() # Component is a folder component - eg Dashboard, Document, EmailTemplate, Report if not component_type.inFolder: # set up the component type to query for components component = metadata_client.factory.create("ListMetadataQuery") component.type = component_type.xmlName # Add metadata to list component_list.append(component) else: # Append "Folder" keyword onto end of component type component = metadata_client.factory.create("ListMetadataQuery") # EmailTemplate = EmailFolder (for some reason) if component_type.xmlName == 'EmailTemplate': component.type = 'EmailFolder' else: component.type = component_type.xmlName + 'Folder' # All folders for specified metadata type all_folders = metadata_client.service.listMetadata( [component], settings.SALESFORCE_API_VERSION) folder_list = [] folder_loop_counter = 0 # Loop through folders for folder in all_folders: # Exclude managed package folders if 'namespacePrefix' not in folder or not folder.namespacePrefix: # Create component for folder to query folder_component = metadata_client.factory.create( "ListMetadataQuery") folder_component.type = component_type.xmlName folder_component.folder = folder.fullName folder_list.append(folder_component) if len(folder_list) >= 3 or (len(all_folders) - folder_loop_counter) <= 3: # Loop through folder components for folder_component in metadata_client.service.listMetadata( folder_list, settings.SALESFORCE_API_VERSION): # create the component record and save component_record = Component() component_record.component_type = component_type_record component_record.name = folder_component.fullName component_record.save() folder_list = [] folder_loop_counter = folder_loop_counter + 1 # Run the metadata query only if the list has reached 3 (the max allowed to query) # at one time, or if there is less than 3 components left to query if len(component_list) >= 3 or (len(all_metadata[0]) - loop_counter) <= 3: # loop through the components returned from the component query for component in metadata_client.service.listMetadata( component_list, settings.SALESFORCE_API_VERSION): # Exclude managed package components if 'namespacePrefix' not in component or not component.namespacePrefix: # Query database for parent component_type component_type_query = ComponentType.objects.filter( name=component.type, org=org.id) # Only add if found if component_type_query: # create the component record and save component_record = Component() component_record.component_type = component_type_query[ 0] component_record.name = component.fullName component_record.save() # clear list once done. This list will re-build to 3 components and re-query the service component_list = [] loop_counter = loop_counter + 1 # If a component type has no child components, remove the component type altogether for component_type in ComponentType.objects.filter(org=org.id): if not Component.objects.filter(component_type=component_type.id): component_type.delete() # Create retrieve request retrieve_request = metadata_client.factory.create('RetrieveRequest') retrieve_request.apiVersion = settings.SALESFORCE_API_VERSION retrieve_request.singlePackage = True retrieve_request.packageNames = None retrieve_request.specificFiles = None # List of components to retrieve files for component_retrieve_list = [] # Component types for the org component_types = ComponentType.objects.filter(org=org.id) # Now query through all components and download actual metadata for component_type in component_types: # Loop through child components of the component type for component in component_type.component_set.all(): # Create PackageTypeMember instant to retrieve component_to_retrieve = metadata_client.factory.create( 'PackageTypeMembers') component_to_retrieve.members = component.name component_to_retrieve.name = component_type.name component_retrieve_list.append(component_to_retrieve) # If more than 5k components to retrieve, run it in batches. Otherwise just do it in # one big hit if len(component_retrieve_list) <= 5000: # Execute the callout for all components retrieve_files(org, metadata_client, retrieve_request, component_retrieve_list, None) else: # Iterate over the component types and run in batches for component_type in component_types: component_retrieve_list = [] # Loop through child components of the component type for component in component_type.component_set.all(): # Create PackageTypeMember instant to retrieve component_to_retrieve = metadata_client.factory.create( 'PackageTypeMembers') component_to_retrieve.members = component.name component_to_retrieve.name = component_type.name component_retrieve_list.append(component_to_retrieve) # Execute the retrieve for the component type retrieve_files(org, metadata_client, retrieve_request, component_retrieve_list, component_type.name) except Exception as error: org.status = 'Error' org.error = error org.error_stacktrace = traceback.format_exc() org.save() # Check if both jobs are now finished check_overall_status(job)
config.read('ispyb.properties') credentialsConfig = ConfigParser.ConfigParser() credentialsConfig.read('credentials.properties') # Connection and user parameters url = config.get('Connection', 'url') proxy_http = str(config.get('Proxy', 'http')) proxy_https = str(config.get('Proxy', 'https')) username = credentialsConfig.get('Credential', 'user') password = credentialsConfig.get('Credential', 'password') pprint(url) # Authentication HTTPSoapService = HttpAuthenticated(username=username, password=password) client = Client(url, transport=HTTPSoapService, cache=None, timeout=15) # Proposal parameters proposalCode = credentialsConfig.get('Proposal', 'type') proposalNumber = credentialsConfig.get('Proposal', 'number') json_data = open('example.json') data = json.dumps(json.load(json_data)) pprint(data) json_data.close() # Store shipping shipment = client.service.findProteinAcronyms() print(str(shipment))
def task_cancel(self, taskId): client = Client( 'http://localhost:9001/TPFProxyTaskManagerService.svc/meta?wsdl') result = client.service.CancelTask(taskId) return result
def task_forward(self, strXML): client = Client( 'http://localhost:9001/TPFProxyTaskManagerService.svc/meta?wsdl') result = client.service.InitTask(strXML) return result
def task_load(self, taskId): client = Client( 'http://localhost:9001/TPFProxyTaskManagerService.svc/meta?wsdl') result = client.service.LoadTaskData(taskId) return result
class Connector(AuditConnector): MappingName = 'Jasper' Settings = { 'wsdl_path': { 'order': 1, 'default': "http://api.jasperwireless.com/ws/schema/Terminal.wsdl" }, 'username': { 'order': 2, 'example': "*****@*****.**" }, 'password': { 'order': 3, 'example': "change-me" }, 'api_token': { 'order': 4, 'example': "YOUR Jasper API TOKEN" }, 'storage': { 'order': 4, 'default': "storage.db" }, 'sync_field': { 'order': 5, 'example': '24DCF85294E411E38A52066B556BA4EE' }, 'update_only': { 'order': 6, 'default': "False" }, } def __init__(self, section, settings): super(Connector, self).__init__(section, settings) self.url_temlate = "%s/api/v1/mdm/devices/search?pagesize={0}&page={1}" % self.settings[ 'wsdl_path'] self.jasper_client = None def do_test_connection(self, options): try: self.authenticate() return {'result': True, 'error': ''} except AuthenticationError as exp: return { 'result': False, 'error': 'Connection Failed: %s' % (exp.message) } def _load_records(self, options): for id_chunk in self.get_modified_terminals(): details = self.get_terminal_details(id_chunk) for detail in details: yield detail def parse_wsdl(self): """ Parses WSDL file to determine available services and objects. Sets WSSE security object as well. """ logger.debug("Parsing WSDL: %s...", self.settings['wsdl_path']) self.jasper_client = Client(self.settings['wsdl_path']) # WSSE security security = Security() token = UsernameToken(self.settings['username'], self.settings['password']) security.tokens.append(token) self.jasper_client.set_options(wsse=security, timeout=600) def authenticate(self): return self.parse_wsdl() def get_modified_terminals(self): """ GetModifiedTerminals - SOAP Request Get the terminals accessible to this user which have been modified since the given time (not inclusive). If the "since" parameter is omitted, it means return all iccids. The result will be a list of iccids ordered by oldest first. This API call is useful for keeping client side data in sync with Jasper's. """ # extracting since variable storage_path = '../{}'.format( self.settings['storage']) # FixMe: fix me! if os.path.exists(storage_path): with open(storage_path, 'r') as f: since = unicode(f.read().strip()) else: since = '2015-03-04T00:00:00Z' logger.debug("Fetching Modified Terminal ID(s) since %s...", since) _args = dict(since=since, licenseKey=self.settings['api_token']) response = self.jasper_client.service.GetModifiedTerminals(**_args) ids = response['iccids'][0] logger.debug("Found %s modified terminals.", len(ids)) last_modified_date = since try: while ids: to_send, ids = ids[:10], ids[10:] logger.debug("yielding %r for processing.", to_send) yield to_send last_modified_date = to_send[-1]['dateModified'] finally: with open(storage_path, 'w') as f: new_since = last_modified_date f.write(new_since) def get_terminal_details(self, iccids): """ GetTerminalDetails - SOAP Request Get the attributes for a list of terminals (given list of iccids). At least one iccid should be provided, maximum limit is 50 for performance reasons. The returned results are not guaranteed to be in the same ordering as the request. Not found terminals will not be part of the result. """ _args = dict(licenseKey=self.settings['api_token'], iccids={'iccid': [v for v in iccids]}) details = self.jasper_client.service.GetTerminalDetails(**_args) details = [self.suds_to_dict(d) for d in details.terminals[0]] return details @classmethod def suds_to_dict(cls, obj): return {v[0]: v[1] for v in obj} @classmethod def default(cls, o): if hasattr(o, 'isoformat'): return o.isoformat() return None
def getclient(self): #生成客户端 client = Client(self.url) return client
class Didww(object): def get_mapping(self, type, proto, detail, pref_server, itsp_id): return { 'map_type': type, 'map_proto': proto, 'map_detail': detail, 'map_pref_server': pref_server, 'map_itsp_id': itsp_id } def __init__(self, username, api_key, sandbox): """ initialise the DIDWW API @param username : didww username @param api_key : didww api_key @param sandbox : boolean """ self.username = username if sandbox: self.url = 'https://sandbox2.didww.com/api2/?wsdl' self.auth_string = hashlib.sha1(username + api_key).hexdigest() else: self.auth_string = hashlib.sha1(username + api_key + 'sandbox').hexdigest() self.url = 'http://api.didww.com/api/?wsdl' self.client = Client(self.url) def get_regions(self, country_iso=None, city_prefix=None, last_request_gmt=None): """ This method will return list of regions from DIDWW coverage list """ return self.client.didww_getdidwwregions( auth_string=self.auth_string, country_iso=country_iso, city_prefix=city_prefix, last_request_gmt=last_request_gmt) def get_pstn_rates(self, country_iso=None, pstn_prefix=None, last_request_gmt=None): """ This method will return list of supported PSTN prefixes from DIDWW. """ return self.client.didww_getdidwwpstnrates( auth_string=self.auth_string, country_iso=country_iso, pstn_prefix=pstn_prefix, last_request_gmt=last_request_gmt) def check_pstn_number(self, pstn_number): """ This method will validate a PSTN Number. """ return self.client.didww_checkpstnnumber(auth_string=self.auth_string, pstn_number=pstn_number) def order_create(self, customer_id, country_iso, city_prefix, period, map_data, prepaid_funds, uniq_hash, city_id): """ This method will purchase new service """ return self.client.didww_ordercreate(auth_string=self.auth_string, customer_id=customer_id, country_iso=country_iso, city_prefix=city_prefix, period=period, map_data=map_data, prepaid_funds=prepaid_funds, uniq_hash=uniq_hash, city_id=city_id)
class ClientServiceMethods: """This class contains producer methods for all ClientService methods.""" wsdl = BasicRequestHelper.BuildWsdlUrl("Client") """We manually set the SoapAction field here by specifying location. Specifically, we need an https connection (for things such as modifying billing information and by default, this gets set to http.""" service = Client(wsdl, location="https://api.mindbodyonline.com/0_5/ClientService.asmx") def CreateBasicRequest(self, requestName): return BasicRequestHelper.CreateBasicRequest(self.service, requestName) """AddArrival methods""" def AddArrival(self, clientId, locationId): request = self.CreateBasicRequest("AddArrivalRequest") request.ClientID = clientId request.LocationID = locationId return self.service.service.AddArrival(request) """AddClientFormulaNote methods""" def AddClientFormulaNote(self, clientId, appointmentId, note): request = self.CreateBasicRequest("AddClientFormulaNote") request.ClientID = clientId request.AppointmentID = appointmentId request.Note = note return self.service.service.AddClientFormulaNote(request) """AddOrUpdateClient methods""" def AddOrUpdateClients(self, updateAction, test, clients): request = self.CreateBasicRequest("AddOrUpdateClients") request.UpdateAction = updateAction request.Test = test request.Clients = clients return self.service.service.AddOrUpdateClients(request) def AddCreditCardToClient(self, clientId, cc): # Call GetClientBySingleID, then grab the first client off the list. clientToEdit = self.GetClientsBySingleId(clientId).Clients.Client[0] clientToEdit.ClientCreditCard = cc Clients = BasicRequestHelper.FillArrayType(self.service, [clientToEdit], "Client", "Client") return self.AddOrUpdateClients("Fail", False, Clients) def CreateAndAddCreditCardToClient(self, clientId, cardType, lastFour, number, holderName, expMonth, expYear, address, city, state, postalCode): """This method shows how to create a credit card item from given simple types.""" cc = self.service.factory.create("ClientCreditCard") cc.CardType = cardType cc.LastFour = lastFour cc.CardNumber = number cc.CardHolder = holderName cc.ExpMonth = expMonth cc.ExpYear = expYear cc.Address = address cc.City = city cc.State = state cc.PostalCode = postalCode return self.AddCreditCardToClient(clientId, cc) """AddOrUpdateContactLogs methods""" def UpdateContactLogText(self, clientId, text): """This method will change the text of every contact log applied to clientId in the past year to text.""" request = self.CreateBasicRequest("AddOrUpdateContactLogs") contactLogs = self.GetClientContactLogsByClient(clientId, True) for log in contactLogs.ContactLogs.ContactLog: log.Text = text request.UpdateAction = "Fail" request.Test = False request.ContactLogs = contactLogs return self.service.service.AddOrUpdateContactLogs(request) """DeleteClientFormulaNote methods""" def DeleteFormulaNote(self, clientId, formulaNoteId): request = self.CreateBasicRequest("DeleteClientFormulaNote") request.ClientID = clientId request.FormulaNoteID = formulaNoteId return self.service.service.DeleteClientFormulaNote(request) """GetActiveClientMemberships Methods""" def GetActiveClientMemberships(self, clientId, locationId): request = self.CreateBasicRequest("GetActiveClientMemberships") request.ClientID = clientId request.LocationID = locationId return self.service.service.GetActiveClientMemberships(request) """GetClientAccountBalances methods""" def GetClientAccountBalances(self, clientIds, balanceDate, classId): request = self.CreateBasicRequest("GetClientAccountBalances") ClientIDs = self.service.factory.create("ArrayOfString") ClientIDs.string = clientIds request.ClientIDs = ClientIDs request.BalanceDate = balanceDate request.ClassID = classId return self.service.service.GetClientAccountBalances(request) """GetClientContactLogs methods""" def GetClientContactLogs(self, clientId, startDate, endDate, staffIds, systemGenerated, typeIds, subtypeIds): request = self.CreateBasicRequest("GetClientContactLogsRequest") request.ClientID = clientId request.StartDate = startDate request.EndDate = endDate request.StaffIDs = BasicRequestHelper.FillArrayType(self.service, staffIds, "Long") request.ShowSystemGenerated = systemGenerated request.TypeIDs = typeIds request.SubtypeIDs = subtypeIds return self.service.service.GetClientContactLogs(request) def GetClientContactLogsByClient(self, clientId, systemGenerated): """Convenience method to find all contact logs for a given client within the past year.""" return self.GetClientContactLogs(clientId, BasicRequestHelper.oneYearAgo, datetime.today(), None, systemGenerated, None, None) """GetClientContracts methods""" def GetClientContracts(self, clientId): request = self.CreateBasicRequest("GetClientContracts") request.ClientID = clientId return self.service.service.GetClientContracts(request) """GetClientFormulaNotes methods""" def GetClientFormulaNotes(self, clientId, appointmentId): request = self.CreateBasicRequest("GetClientFormulaNotes") request.ClientID = clientId request.AppointmentID = appointmentId return self.service.service.GetClientFormulaNotes(request) """GetClientIndexes methods""" def GetClientIndexes(self): request = self.CreateBasicRequest("GetClientIndexesRequest") return self.service.service.GetClientIndexes(request) """GetClientPurchases methods""" def GetClientPurchases(self, clientId, startDate, endDate): request = self.CreateBasicRequest("GetClientPurchases") request.ClientID = clientId request.StartDate = startDate request.EndDate = endDate return self.service.service.GetClientPurchases(request) """GetClientReferralTypes methods""" def GetClientReferralTypes(self): request = self.CreateBasicRequest("GetClientReferralTypes") return self.service.service.GetClientReferralTypes(request) """GetClientVisits methods""" def GetClientVisits(self, clientId, startDate, endDate, unpaidsOnly): request = self.CreateBasicRequest("GetClientVisits") request.ClientID = clientId request.StartDate = startDate request.EndDate = endDate request.UnpaidsOnly = unpaidsOnly return self.service.service.GetClientVisits(request) """GetClients methods""" def GetAllClients(self): return self.GetClientsByString(" ") def GetClientsBySingleId(self, id): return self.GetClientsByMultipleIds([id]) def GetClientsByString(self, searchStr): """Convenience method to find clients containing searchStr in their name or e-mail.""" request = self.CreateBasicRequest("GetClientsRequest") # Since SearchText is just a string, we can assign it directly. request.SearchText = searchStr print(request) return self.service.service.GetClients(request) def GetClientsByMultipleIds(self, ids): request = self.CreateBasicRequest("GetClientsRequest") """Here, we create an instance of ArrayOfString (the type of ClientIDs in the request) and fill it with our ids before assigning it to our request.""" clientIDs = self.service.factory.create("ArrayOfString") clientIDs.string = ids request.ClientIDs = clientIDs return self.service.service.GetClients(request) """GetClientSchedule methods""" def GetClientSchedule(self, clientId, startDate, endDate): request = self.CreateBasicRequest("GetClientSchedule") request.ClientID = clientId request.StartDate = startDate request.EndDate = endDate return self.service.service.GetClientSchedule(request) """GetClientServices methods""" def GetClientServices(self, clientId, classId, programIds, sessionTypeIds, locationIds, visitCount, startDate, endDate, showActiveOnly): """A few notes about GetClientServices: 1. If you don't want to pass a Class ID in, pass 0. This acts as you would expect None to. 2. ProgramIDs is a required field.""" request = self.CreateBasicRequest("GetClientServices") request.ClientID = clientId request.ClassID = classId request.ProgramIDs = BasicRequestHelper.FillArrayType(self.service, programIds, "Int") request.SessionTypeIDs = BasicRequestHelper.FillArrayType( self.service, sessionTypeIds, "Int") request.LocationIDs = BasicRequestHelper.FillArrayType(self.service, locationIds, "Int") request.VisitCount = visitCount request.StartDate = startDate request.EndDate = endDate request.ShowActiveOnly = showActiveOnly return self.service.service.GetClientServices(request) """GetContactLogTypes methods""" def GetContactLogTypes(self): request = self.CreateBasicRequest("GetContactLogTypes") return self.service.service.GetContactLogTypes(request) """GetCustomClientFields methods""" def GetCustomClientFields(self): request = self.CreateBasicRequest("GetCustomClientFieldsRequest") return self.service.service.GetCustomClientFields(request) """GetRequiredClientFields methods""" def GetRequiredClientFields(self): request = self.CreateBasicRequest("GetRequiredClientFields") return self.service.service.GetRequiredClientFields(request) """SendUserNewPassword methods""" def SendUserNewPassword(self, userEmail, userFirstName, userLastName): request = self.CreateBasicRequest("SendUserNewPassword") request.UserEmail = userEmail request.UserFirstName = userFirstName request.UserLastName = userLastName return self.service.service.SendUserNewPassword(request) """UpdateClientServices methods""" def UpdateClientServices(self, clientServices, test): request = self.CreateBasicRequest("UpdateClientServices") ServiceList = self.service.factory.create("ArrayOfClientService") ServiceList.ClientService = clientServices request.ClientServices = ServiceList request.Test = test return self.service.service.UpdateClientServices(request) """UploadClientDocument methods""" def UploadClientDocument(self, clientId, fileName, fileSize): request = self.CreateBasicRequest("UploadClientDocument") request.ClientID = clientId request.FileName = fileName request.Bytes = fileSize return self.service.service.UploadClientDocument(request) """ValidateLogin methods""" def ValidateLogin(self, username, password): request = self.CreateBasicRequest("ValidateLogin") request.Username = username request.Password = password return self.service.service.ValidateLogin(request)
def remedy_cm_create(prodvsqa, arglist, CMURL): """Function to Create a Remedy Change Management ticket The prodvsqa parameter, if set to QA will use the QA server for the creation, otherwise prod. The arglist is a dictionary of key/value pairs to be set in the CM. The keys must correspond to the keys used in the Change Management WSDL for creating a new Ticket """ # This code stolen from the kick ass L.Bur, with permission, I do not assume responsibility for this code, nor do I support it. try: cmclient = Client(CMURL, cache=NoCache()) except Exception as myexception: raise Exception('CM_CreateClientCreate:' + str(myexception)) cmOpCreate = cmclient.factory.create('OpCreate') cmOpCreate = dict([(str(key), val) for key, val in cmOpCreate]) cmOpCreateRequired = {} cmOpCreateRequired['AssociatedDivision'] = True cmOpCreateRequired['Back-out_Instructions'] = True cmOpCreateRequired['Change_Start_Time'] = True cmOpCreateRequired['Change_Stop_Time'] = True cmOpCreateRequired['Changes_Planned'] = True cmOpCreateRequired['Country'] = True cmOpCreateRequired['CustFacing_CustSupporting'] = True cmOpCreateRequired['Impact'] = True cmOpCreateRequired['ReasonForChange'] = True cmOpCreateRequired['Requestor'] = True cmOpCreateRequired['Requestor_Phone'] = True cmOpCreateRequired['RequestorEmail'] = True cmOpCreateRequired['ResponsibleGroup'] = True cmOpCreateRequired['Short_Description'] = True cmOpCreateRequired['Status'] = True cmOpCreateRequired['Submitter'] = True cmOpCreateRequired['TypeOfChange'] = True cmOpCreateRequired['KnownImpact'] = True for key in list(cmOpCreate): if key in arglist: cmOpCreate[key] = arglist[key] elif key in cmOpCreateRequired: raise Exception('CM_Create:Required_Field_Missing:' + key) else: del cmOpCreate[key] try: cmresult = cmclient.service.OpCreate(**cmOpCreate) except Exception as myexception: raise Exception('CM_Create:' + str(myexception)) return cmresult syslogmsgbeginbase = 'scriptruntime' + keysep + delim + scriptruntime + delim + sep + 'SearchName' + keysep + delim + arghash[ 'searchName'] + delim + sep + 'searchCount' + keysep + delim + arghash[ 'searchCount'] + delim + sep + 'searchPath' + keysep + delim + arghash[ 'searchPath'] + delim + sep try: resultstatus = get_search_results(arghash['searchPath']) except Exception as myexception: syslogmessage = syslogmsgbeginbase + 'ScriptStatus' + keysep + delim + 'Fail_GetResults_Exception:' + str( myexception) + delim logorprint(syslogmessage, mylogfile) quit() if resultstatus == None: for resultrow in resultdict: resultrow['Submitter'] = remedysubmitter if not 'Requestor' in resultrow: resultrow['Requestor'] = remedyrequestor if not 'Status' in resultrow: resultrow['Status'] = remedydefaultstatus if 'prodvsqa' in resultrow: if resultrow['prodvsqa'] == 'PROD': prodvsqa = 'PROD' else: prodvsqa = 'QA' mystarttime = resultrow['Change_Start_Time'][ 5:7] + '/' + resultrow['Change_Start_Time'][ 8:10] + '/' + resultrow['Change_Start_Time'][ 0:4] + ' ' + resultrow['Change_Start_Time'][ 11:13] + ':' + resultrow['Change_Start_Time'][ 14:16] + ':' + resultrow[ 'Change_Start_Time'][17:19] print(mystarttime) mystoptime = resultrow['Change_Stop_Time'][ 5:7] + '/' + resultrow['Change_Stop_Time'][ 8:10] + '/' + resultrow['Change_Stop_Time'][ 0:4] + ' ' + resultrow['Change_Stop_Time'][ 11:13] + ':' + resultrow['Change_Stop_Time'][ 14:16] + ':' + resultrow[ 'Change_Stop_Time'][17:19] print(mystoptime) cmoplist['Qualification'] = cmoplist[ 'Qualification'] + ' AND \'Change Start Time\' = "' + mystarttime + '" AND \'Change Stop Time\' = "' + mystoptime + '"' if foundcm == 1 and len(cmresult) > 1: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_MoreThan1CMReturned' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow['scriptaction'] == 'CancelCM' and foundcm == 0: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CancelNotFound' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow['scriptaction'] == 'CreateCM' and foundcm == 1: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CreateAlreadyExists' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow['scriptaction'] == 'CancelCM' and foundcm == 1: myrequestid = cmresult[0]['Request_ID'] cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Status'] = 'Cancelled' cmopset['Cancelled'] = 'Yes' cmopset['RequestedWindow'] = resultrow['RequestedWindow'] syslogmsgbegin = syslogmsgbegin + 'CM_Ticket_Created' + keysep + delim + myrequestid + delim + sep try: remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMApprovedToCancel_Exception:' + str( myexception) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue if resultrow['sendnotify'] == '1': cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['TriggerNotifyCustomer'] = 'Yes' try: cmresult = remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMCancelNotify_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Success' + delim + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow[ 'scriptaction'] == 'RescheduleCM' and foundcm == 1: mystarttime = cmresult[0]['Change_Start_Time'] mystarttime = mystarttime.strftime( '%Y-%m-%dT%H:%M:%S-04:00') mystoptime = cmresult[0]['Change_Stop_Time'] mystoptime = mystoptime.strftime('%Y-%m-%dT%H:%M:%S-04:00') if resultrow[ 'Change_Start_Time'] == mystarttime and resultrow[ 'Change_Stop_Time'] == mystoptime: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_AlreadyRescheduled' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) else: myrequestid = cmresult[0]['Request_ID'] cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Status'] = 'Re-Scheduling' syslogmsgbegin = syslogmsgbegin + 'CM_Ticket_Created' + keysep + delim + myrequestid + delim + sep try: remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMApprovedToReschedule_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Change_Start_Time'] = resultrow[ 'Change_Start_Time'] cmopset['Change_Stop_Time'] = resultrow[ 'Change_Stop_Time'] cmopset['Rescheduled'] = 'Yes' cmopset['RequestedWindow'] = resultrow[ 'RequestedWindow'] try: remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMRescheduleChangeTimes_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue if resultrow['sendnotify'] == '1': cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['TriggerNotifyCustomer'] = 'Yes' try: cmresult = remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMRescheduleNotify_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Status'] = 'Requested' try: cmresult = remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMRescheduleRequested_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Success' + delim + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif foundcm == 0 and ( resultrow['scriptaction'] == 'RescheduleCM' or resultrow['scriptaction'] == 'CreateCM'): try: cmresult = remedy_cm_create(prodvsqa, resultrow) except Exception as myexception: print(str(Exception)) continue else: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_Unknown_scriptaction' + delim + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) else: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_GetResults_Without_Exception' + delim logorprint(syslogmessage, mylogfile) quit()
def removeheader(self, key): self.headers.pop(key) self.client = Client(self.wsdl, headers=self.headers) self.writer.write(self.writer.row, 7, 'PASS') self.writer.write(self.writer.row, 8, str(self.result)) return True
def david_analysis(resF, inputIds): errors = 0 setup_logging() logging.getLogger('suds.client').setLevel(logging.DEBUG) url = 'https://david.ncifcrf.gov/webservice/services/DAVIDWebService?wsdl' print('URL : %s' % url) client = Client(url) client.wsdl.services[0].setlocation( 'https://david.ncifcrf.gov/webservice/services/DAVIDWebService.DAVIDWebServiceHttpSoap11Endpoint/' ) client.service.authenticate('*****@*****.**') idType = 'ENSEMBL_GENE_ID' listName = 'make_up' listType = 0 print(client.service.addList(inputIds, idType, listName, listType)) thd = 0.1 ct = 2 chartReport = client.service.getChartReport(thd, ct) chartRow = len(chartReport) print('Total chart records:', chartRow) with open(resF, 'w') as fOut: fOut.write( 'Category\tTerm\tCount\t%\tPvalue\tGenes\tList Total\tPop Hits\tPop Total\tFold Enrichment\tBonferroni\tBenjamini\tFDR\n' ) for simpleChartRecord in chartReport: categoryName = simpleChartRecord.categoryName termName = simpleChartRecord.termName listHits = simpleChartRecord.listHits percent = simpleChartRecord.percent ease = simpleChartRecord.ease Genes = simpleChartRecord.geneIds listTotals = simpleChartRecord.listTotals popHits = simpleChartRecord.popHits popTotals = simpleChartRecord.popTotals foldEnrichment = simpleChartRecord.foldEnrichment bonferroni = simpleChartRecord.bonferroni benjamini = simpleChartRecord.benjamini FDR = simpleChartRecord.afdr rowList = [ categoryName, termName, str(listHits), str(percent), str(ease), Genes, str(listTotals), str(popHits), str(popTotals), str(foldEnrichment), str(bonferroni), str(benjamini), str(FDR) ] fOut.write('\t'.join(rowList) + '\n') print('write file:', resF, 'finished!')
# coding:utf-8 from suds.client import Client # hello_client = Client('http://40.125.204.79:7792/bigweb/services/SafeOutAccess?wsdl') hello_client = Client('http://127.0.0.1:7789/bigweb/services/SafeOutAccess?wsdl') print hello_client hello_client.options.cache.clear() # print hello_client # result = hello_client.service.say_hello( # """<?xml version="1.0" encoding="UTF-8" ?> # <root> # <QueryCondition> # <wjm>11001901120180305000008</wjm> # </QueryCondition> # <QueryCondition> # <wjm>11001901120180305000010</wjm> # </QueryCondition> # <QueryCondition> # <wjm>09000109120171123000004</wjm> # </QueryCondition></root>""") ss = """<?xml version="1.0" encoding="UTF-8" ?> <root> <QueryCondition> <wjm>11001901120180305000008</wjm> </QueryCondition> <QueryCondition> <wjm>11001901120180305000010</wjm> </QueryCondition> <QueryCondition> <wjm>09000109120171123000004</wjm>
def query(self, sboIdList): """ Queries the SBO webservice for Ids """ client = Client("http://www.ebi.ac.uk/sbo/main/services/SBOQuery?wsdl") self.SBO = client.service for id in sboIdList: self.sboLookup.append(self._sboId2expression(id))
def setUp(self): self.client = Client( 'http://www.webservicex.com/globalweather.asmx?WSDL')
def setwsdl(self, url): self.wsdl = url self.client = Client(url, doctor=self.doctor) self.writer.write(self.writer.row, 7, 'PASS') self.writer.write(self.writer.row, 8, self.wsdl) return True
def get_link(self): return Client(self.app.base_url + "/api/soap/mantisconnect.php?wsdl")
## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. ## import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds.wsdl').setLevel(logging.DEBUG) from suds.client import Client url = 'http://anathema.flux.utah.edu/wsdl/debuginfo.wsdl.local' client = Client(url, cache=None) opts = client.factory.create('DebugFileOptsT') opts.symbolRefDepth = 8 opts.scopeRefDepth = 8 opts.doMultiRef = False opts.doManualRef = False opts.debugfileRefDepth = 8 result = client.service.LookupSymbol('/usr/lib/debug/bin/yes.debug', 'main.argc', opts)
#!/usr/bin/env python # -*- coding:utf-8-*- #@author:蜜蜜 #@file: test_bindBankCard.py #@time: 2019/01/10 #@email:[email protected] from suds.client import Client api_url4 = "http://120.24.235.105:9010/finance-user_info-war-1.0/ws/financeUserInfoFacade.ws?wsdl" client4 = Client(api_url4) print(client4) '''如何传递参数值:''' t = { "uid": 100004681, "pay_pwd": 249076, "mobile": 18827913076, "cre_id": 362201199504210418, "user_name": "彭思源", "cardid": 6212261502001124118, "bank_type": 1001, "bank_name": "中国工商银行" } #用字典的方式来传值 result4 = client4.service.bindBankCard(t) print(result4)
class BDAQApiClient(object): """ Client object to handle requests to the Betdaq Api. This simply configures the Client object from the Suds library. Instances comes in two flavors, if __init__ is called with 'secure' we have a client that for calling the 'secure' Api methods, if it is called with 'readonly' we have a client for calling the 'readonly' methods (see the BDAQ docs). The difference between these two is that the secure client will send the password in SOAP requests, the readonly client will not. """ # mapping from my names to the WSDL info _READONLY = 'readonly' _SECURE = 'secure' _sdict = {_READONLY: ['ReadOnlyService', 0], _SECURE: ['SecureService', 1]} def __init__(self, service): """ Create the SUDS client with the correct options and headers for the chosen service, which can be either 'readonly' or 'secure'. """ # allowed services aservices = BDAQApiClient._sdict.keys() if service not in aservices: raise IOError('service must be one of: {0}'.\ format(' '.join(aservices))) self.service = service self.snum = BDAQApiClient._sdict[self.service][1] # after this call, self.client will be a SUDS client object self._create_suds_client() def _create_suds_client(self): """Create SUDS client for BDAQ Api.""" self.client = Client(const.WSDLLOCAL['BDAQ']) self.client.set_options(service=BDAQApiClient._sdict[self.service][0], headers={'user-agent': const.USERAGENT}) # put username (and password if necessary) into the headers. # note that another way to do this is to call betdaq.set_user, # so the username and password in const.py do not need to be # specified. self.set_headers(const.BDAQUSER, const.BDAQPASS) def method_names(self): """Return list of methods (Api functions)""" return self.client.wsdl.services[self.snum].ports[0].methods.keys() def set_headers(self, name, password): """Set the username and password that needs to go in the SOAP header.""" # this SOAP header is required by the Api in this form header = Element('ExternalApiHeader') if self.service == BDAQApiClient._READONLY: # we send the username only in the SOAP header astring = ('version="{0}" currency="GBP" languageCode="en" ' 'username="******" ' 'xmlns="http://www.GlobalBettingExchange' '.com/ExternalAPI/"'.format(const.BDAQAPIVERSION, name)) if self.service == BDAQApiClient._SECURE: # we send the username and password in the SOAP header astring = ('version="{0}" currency="GBP" languageCode="en" ' 'username="******" password="******" ' 'xmlns="http://www.GlobalBettingExchange' '.com/ExternalAPI/"'.format(const.BDAQAPIVERSION, name, password)) # set header header.attributes = [astring] self.client.set_options(soapheaders=header)