本文整理汇总了Python中suds.client.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_order_list_test
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
示例2: __init__
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
示例3: soapCreateIncident
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
示例4: soap_login
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
示例5: get_client
def get_client(url):
client = Client(url)
credentials = client.factory.create('credentials')
credentials.username = 'webmail'
credentials.password = 'webmail'
client.set_options(soapheaders=credentials)
return client
示例6: call_webservice
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
示例7: MarketoClientFactory
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
示例8: timbrar
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
示例9: setSMSAOMTSoapHeader
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
示例10: __init__
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
示例11: soap_setup
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)
示例12: __init__
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)
示例13: check_batch
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)
示例14: get_times
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)
示例15: _load_aquo_xml
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