本文整理汇总了Python中suds.client.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:vgulaev,项目名称:sitenewwave,代码行数:33,代码来源:webservice_test.py
示例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
开发者ID:jeffery9,项目名称:mixprint_addons,代码行数:30,代码来源:jasperclient.py
示例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
开发者ID:jvdiago,项目名称:cacti-log-parser,代码行数:29,代码来源:cacti-log-parser.py
示例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
开发者ID:andreavb,项目名称:fence-agents,代码行数:31,代码来源:fence_vmware_soap.py
示例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
开发者ID:dbsiavichay,项目名称:webservicesbridge,代码行数:7,代码来源:views.py
示例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
开发者ID:collective,项目名称:collective.webservice,代码行数:34,代码来源:views.py
示例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
开发者ID:sirsgriffin,项目名称:pymarketo,代码行数:25,代码来源:client.py
示例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
开发者ID:e-fector,项目名称:gnucash-cfdi,代码行数:29,代码来源:facturacion_moderna.py
示例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
开发者ID:wndfly,项目名称:mobile,代码行数:35,代码来源:message.py
示例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
开发者ID:cokelaer,项目名称:bioservices,代码行数:33,代码来源:services.py
示例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)
开发者ID:etaijacob,项目名称:AA2CODON,代码行数:32,代码来源:FetchUtils.py
示例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)
开发者ID:rprithvi,项目名称:cvss-scoring,代码行数:33,代码来源:wscoverity.py
示例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)
开发者ID:chenyu600,项目名称:mutalyzer,代码行数:26,代码来源:mutalyzer-monitor.py
示例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)
开发者ID:sirmmo,项目名称:TPER2GTFS,代码行数:26,代码来源:transform.py
示例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
开发者ID:swinkels,项目名称:lizard-measure,代码行数:32,代码来源:synchronisation.py
示例16: ChildcareServiceApi
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
开发者ID:leehosung,项目名称:nursery-crawl,代码行数:27,代码来源:childcare_service_api.py
示例17: get_tab_part_order
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
开发者ID:vgulaev,项目名称:sitenewwave,代码行数:25,代码来源:get_tab_part_order.py
示例18: createPayment
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
开发者ID:LaurentGrimaud,项目名称:PayZen-Python-SOAP-V5-createPayment-example,代码行数:60,代码来源:PayZenSOAPV5ToolBox.py
示例19: get_price
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"
开发者ID:vgulaev,项目名称:sitenewwave,代码行数:31,代码来源:get_csv.py
示例20: testWSDL
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
开发者ID:zsmahi,项目名称:WS-Amplification,代码行数:25,代码来源:WSA_spoof.py
注:本文中的suds.client.Client类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论