Example #1
0
def getActiveStationsSoappy(debug=False):
    '''
    Use the old SOAPpy interface to get the stations

    Here is the results for one station:

    print response.station[1]

    <SOAPpy.Types.structType station at 20681072>: {'parameter': ['', ''], 'metadata': <SOAPpy.Types.structType metadata at 20683272>: {'date_established': '1954-11-24', 'location': <SOAPpy.Types.structType location at 20635240>: {'lat': '21 57.3 N', 'state': 'HI', 'long': '159 21.4 W'}}}



    >>> response = getActiveStationsSoappy()
    >>> str(response.station[1].metadata.location.lat)
    '21 57.3 N'
    >>> str(response.station[1].metadata.location.long)
    '159 21.4 W'
    >>> str(response.station[1].metadata.location.state)
    'HI'

    @param debug: set to true to see more information about the transaction
    @return: a large typestring
    '''
    from SOAPpy import SOAPProxy
    url = 'http://opendap.co-ops.nos.noaa.gov/axis/services/ActiveStations'
    namespace='urn:ActiveStations' # This really can be anything.  It is ignored
    server = SOAPProxy(url,namespace)
    if debug: server.config.debug=1
    response = server.getActiveStations()
    return response
Example #2
0
def getWaterLevelSoappyNow(stationId,debug=False):
    '''
    Use OLD SOAPpy interface to get the waterlevel for a station
    '''

    d = datetime.datetime.utcnow()

    print 'FIX: do this in seconds space!!!!  This is crap!'

    startD = d + datetime.timedelta(minutes=-20)
    endD = d + datetime.timedelta(minutes=10)
    #startMin = int(d.minute) - 6
    #endMin = int(d.minute) + 1
    print startD,endD,d

    beginDate = str(startD.year)+('%02d' % startD.month)+('%02d' % startD.day)+' '+ ('%02d' % (startD.hour))+':'+('%02d' % (startD.minute))
    endDate = str(endD.year)+('%02d' % endD.month)+('%02d' % endD.day)+' '+ ('%02d' % (endD.hour))+':'+('%02d' % (endD.minute))
    #print beginDate,endDate

    from SOAPpy import SOAPProxy
    url = 'http://opendap.co-ops.nos.noaa.gov/axis/services/WaterLevelRawSixMin'
    namespace='urn:WaterLevelRawSixMin' # This really can be anything.  It is ignored
    server = SOAPProxy(url,namespace)
    if debug: server.config.debug=1
    #response = server.getWaterLevelRawSixMin(stationId=str(stationId),beginDate='20051201 00:00',endDate='20051201 00:18',datum='MLLW',unit=0,timeZone=0)


    response = server.getWaterLevelRawSixMin(stationId=str(stationId),beginDate=beginDate,endDate=endDate,datum='MLLW',unit=0,timeZone=0)
    # only return the last entry
    return response.item[-1]
Example #3
0
    def __init__(self, irc):
        self.__parent = super(Mantis, self)
        self.__parent.__init__(irc)

        self.saidBugs = ircutils.IrcDict()
        sayTimeout = self.registryValue('bugSnarferTimeout')
        for k in irc.state.channels.keys():
            self.saidBugs[k] = TimeoutQueue(sayTimeout)

        self.urlbase = self.registryValue('urlbase')
        self.privateurlbase = self.registryValue('privateurlbase')

        if self.privateurlbase != "":
            serviceUrl = self.privateurlbase + '/api/soap/mantisconnect.php'
        else:
            serviceUrl = self.urlbase + '/api/soap/mantisconnect.php'

        self.server = SOAPProxy(serviceUrl)._ns(namespace)
        self.username = self.registryValue('username')
        self.password = self.registryValue('password')
        self.oldperiodic = self.registryValue('bugPeriodicCheck')
        self.irc = irc
        self.lastBug = 0

        bugPeriodicCheck = self.oldperiodic
        if bugPeriodicCheck > 0:
            schedule.addPeriodicEvent(self._bugPeriodicCheck,
                                      bugPeriodicCheck,
                                      name=self.name())

        reload(sys)
        sys.setdefaultencoding('utf-8')
 def _get_dte_status(self, signature_d, token):
     url = server_url[
         self.company_id.dte_service_provider] + 'QueryEstDte.jws?WSDL'
     ns = 'urn:' + server_url[
         self.company_id.dte_service_provider] + 'QueryEstDte.jws'
     _server = SOAPProxy(url, ns)
     receptor = self.format_vat(self.partner_id.vat)
     date_invoice = datetime.strptime(self.date_invoice,
                                      "%Y-%m-%d").strftime("%d-%m-%Y")
     respuesta = _server.getEstDte(
         signature_d['subject_serial_number'][:8],
         str(signature_d['subject_serial_number'][-1]),
         self.company_id.vat[2:-1], self.company_id.vat[-1], receptor[:8],
         receptor[2:-1], str(self.document_class_id.sii_code),
         str(self.sii_document_number), date_invoice,
         str(self.amount_total), token)
     self.sii_message = respuesta
     resp = xmltodict.parse(respuesta)
     if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == '2':
         status = {
             'warning': {
                 'title': _("Error code: 2"),
                 'message':
                 _(resp['SII:RESPUESTA']['SII:RESP_HDR']['GLOSA'])
             }
         }
         return status
     if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "EPR":
         self.state = "Proceso"
         if resp['SII:RESPUESTA']['SII:RESP_BODY']['RECHAZADOS'] == "1":
             self.state = "Rechazado"
         if resp['SII:RESPUESTA']['SII:RESP_BODY']['REPARO'] == "1":
             self.state = "Reparo"
     elif resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "RCT":
         self.state = "Rechazado"
Example #5
0
def getGrados(request):
    if request.method == "GET":
        codigo = request.GET.get('cod')
        curso = request.GET.get('curso')
        server = SOAPProxy('www.abj-ws-devborja.c9users.io:8080')
        res = server.obtenerGruposAsignaturaInformatica(codigo, curso)
        return HttpResponse(res)
Example #6
0
def getWaterLevelSoappyNow(stationId,debug=False):
    '''
    Use OLD SOAPpy interface to get the waterlevel for a station
    '''

    d = datetime.datetime.utcnow()

    print 'FIX: do this in seconds space!!!!  This is crap!'

    startD = d + datetime.timedelta(minutes=-20)
    endD = d + datetime.timedelta(minutes=10)
    #startMin = int(d.minute) - 6
    #endMin = int(d.minute) + 1
    print startD,endD,d

    beginDate = str(startD.year)+('%02d' % startD.month)+('%02d' % startD.day)+' '+ ('%02d' % (startD.hour))+':'+('%02d' % (startD.minute))
    endDate = str(endD.year)+('%02d' % endD.month)+('%02d' % endD.day)+' '+ ('%02d' % (endD.hour))+':'+('%02d' % (endD.minute))
    #print beginDate,endDate

    from SOAPpy import SOAPProxy
    url = 'http://opendap.co-ops.nos.noaa.gov/axis/services/WaterLevelRawSixMin'
    namespace='urn:WaterLevelRawSixMin' # This really can be anything.  It is ignored
    server = SOAPProxy(url,namespace)
    if debug: server.config.debug=1
    #response = server.getWaterLevelRawSixMin(stationId=str(stationId),beginDate='20051201 00:00',endDate='20051201 00:18',datum='MLLW',unit=0,timeZone=0)


    response = server.getWaterLevelRawSixMin(stationId=str(stationId),beginDate=beginDate,endDate=endDate,datum='MLLW',unit=0,timeZone=0)
    # only return the last entry
    return response.item[-1]
Example #7
0
def deleteFabricante(codigoFabricante):
    try:

        servico = SOAPProxy("http://localhost:8083")
        produtos = servico.listarProduto()

        existe = False

        for linha in linhas:
            codigo, descricao, preco, codigoFabricante_ = linha.split('|')
            if codigoFabricante == codigoFabricante_:
                existe = True

        if existe is False:

            f = open(db, "r")
            linhas = f.readlines()
            f.close()

            f = open(db, "w")
            for linha in linhas:
                codigo, descricao, localizacao = linha.split('|')
                if codigo != codigoFabricante:
                    f.write(linha)
            f.close()

            return True
    except:
        return False
Example #8
0
File: VMRC.py Project: lxhiguera/im
	def __init__(self, url, user = None, passwd = None):
		if user == None:
			self.server = SOAPProxy(url)
		else:
			self.server = SOAPProxy(url, transport = HTTPHeaderTransport)
			self.server.transport.headers = {'Username' : user,
							 'Password' : passwd}
 def _get_send_status(self, track_id, signature_d, token):
     url = server_url[
         self.company_id.dte_service_provider] + 'QueryEstUp.jws?WSDL'
     ns = 'urn:' + server_url[
         self.company_id.dte_service_provider] + 'QueryEstUp.jws'
     _server = SOAPProxy(url, ns)
     rut = self.format_vat(self.company_id.vat)
     respuesta = _server.getEstUp(rut[:8], str(rut[-1]), track_id, token)
     self.sii_message = respuesta
     resp = xmltodict.parse(respuesta)
     status = False
     if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "-11":
         status = {
             'warning': {
                 'title':
                 _('Error -11'),
                 'message':
                 _("Error -11: Espere a que sea aceptado por el SII, intente en 5s más"
                   )
             }
         }
     if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "EPR":
         self.state = "Proceso"
         if resp['SII:RESPUESTA']['SII:RESP_BODY']['RECHAZADOS'] == "1":
             self.sii_result = "Rechazado"
     elif resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "RCT":
         self.state = "Rechazado"
         status = {
             'warning': {
                 'title': _('Error RCT'),
                 'message': _(resp['SII:RESPUESTA']['GLOSA'])
             }
         }
     return status
Example #10
0
def getActiveStationsSoappy(debug=False):
    '''
    Use the old SOAPpy interface to get the stations

    Here is the results for one station:

    print response.station[1]

    <SOAPpy.Types.structType station at 20681072>: {'parameter': ['', ''], 'metadata': <SOAPpy.Types.structType metadata at 20683272>: {'date_established': '1954-11-24', 'location': <SOAPpy.Types.structType location at 20635240>: {'lat': '21 57.3 N', 'state': 'HI', 'long': '159 21.4 W'}}}



    >>> response = getActiveStationsSoappy()
    >>> str(response.station[1].metadata.location.lat)
    '21 57.3 N'
    >>> str(response.station[1].metadata.location.long)
    '159 21.4 W'
    >>> str(response.station[1].metadata.location.state)
    'HI'

    @param debug: set to true to see more information about the transaction
    @return: a large typestring
    '''
    from SOAPpy import SOAPProxy
    url = 'http://opendap.co-ops.nos.noaa.gov/axis/services/ActiveStations'
    namespace = 'urn:ActiveStations'  # This really can be anything.  It is ignored
    server = SOAPProxy(url, namespace)
    if debug: server.config.debug = 1
    response = server.getActiveStations()
    return response
    def createSNOWIncident(self, params_dict):
        import datetime
        from SOAPpy import SOAPProxy

        # instance to send to
        instance = 'Company1prod'

        # username/password
        username = '******'
        password = '******'


        # proxy - NOTE: ALWAYS use https://INSTANCE.service-now.com, not https://www.service-now.com/INSTANCE for web services URL from now on!
        proxy = 'https://%s:%s@%s.service-now.com/incident.do?SOAP' % (username, password, instance)
        namespace = 'http://www.service-now.com/'
        server = SOAPProxy(proxy, namespace)

        # uncomment these for LOTS of debugging output
        # server.config.dumpHeadersIn = 1
        # server.config.dumpHeadersOut = 1
        # server.config.dumpSOAPOut = 1
        # server.config.dumpSOAPIn = 1

        response = server.insert(impact=int(params_dict['impact']), urgency=int(params_dict['urgency']), priority=int(params_dict['priority']), category=params_dict['category'], u_current_location=params_dict['location'], caller_id=params_dict['user'], assignment_group=params_dict['assignment_group'], subcategory=params_dict['subcategory'], short_description=params_dict['short_description'], description=params_dict['description'], u_business_unit=params_dict['business_unit'])

        return response
def createincident(params_dict):

        # instance to send to
        instance='xxxxxx'

        # username/password
        username='******'
        password='******'


        # proxy - NOTE: ALWAYS use https://INSTANCE.service-now.com, not https://www.service-now.com/INSTANCE for web services URL from now on!
#        proxy = 'https://%s:%s@%s.service-now.com/u_nimsoft.do?WSDL' % (username, password, instance)
        proxy = 'https://%s:%s@%s.service-now.com/incident.do?SOAP' % (username, password, instance)
        namespace = 'http://www.service-now.com/'
        server = SOAPProxy(proxy, namespace)

        # uncomment these for LOTS of debugging output
        #server.config.dumpHeadersIn = 1
        #server.config.dumpHeadersOut = 1
        #server.config.dumpSOAPOut = 1
        #server.config.dumpSOAPIn = 1

        response = server.insert(
                impact=int(params_dict['impact']),
                urgency=int(params_dict['urgency']),
#               caller_id=params_dict['caller_id'],
                category=str(params_dict['category']),
                assignment_group=params_dict['assignment_group'],
                short_description=params_dict['short_description'],
                comments=params_dict['comments'])

        return response
Example #13
0
def switchIrcut(n):
    try:
        client = SOAPProxy(url, namespace=namespace)
        report = client.switchIRFilter("all", n)
        msg = "Subject: [FAMNET] IR CUT FILTER report\n\nreport:\n%s" % report
    except Error, s:
        msg="Subject: [FAMNET] connection to streamer failed\n%s" % s
Example #14
0
def brenda_query(EC_number, brenda_email="", brenda_pass=""):
    """
    Returns raw output string from BRENDA for an EC number.
    """
    
    # in some intranets an issue: how to use a web proxy for WS. Here
    # we assume a set environment variable 'http_proxy'.·
    # This is common in unix environments. SOAPpy does not like
    # a leading 'http://'
    if 'http_proxy' in os.environ.keys():
        my_http_proxy=os.environ["http_proxy"].replace("http://","")
    else:
        my_http_proxy=None

    endpointURL = "http://www.brenda-enzymes.org/soap/brenda_server.php"
    proxy = SOAPProxy(endpointURL, http_proxy=my_http_proxy)
    password = hashlib.sha256(brenda_pass).hexdigest()
    parameters = brenda_email + ',' + password + ',ecNumber*' + EC_number

    new_EC = proxy.getEcNumber(parameters)
    
    if('transferred to' in new_EC):
        new_EC = new_EC.rsplit(' ', 1)[1]
        new_EC = new_EC[:-1]
        parameters = brenda_email + ',' + password + ',ecNumber*' + new_EC
    
    brenda_response = proxy.getTurnoverNumber(parameters)

    return parse_brenda_raw_output(brenda_response)
Example #15
0
 def _get_cesion_dte_status(self, signature_d, token):
     url = server_url[
         self.company_id.
         dte_service_provider] + 'services/wsRPETCConsulta?wsdl'
     ns = 'urn:' + server_url[
         self.company_id.dte_service_provider] + 'services/wsRPETCConsulta'
     _server = SOAPProxy(url, ns)
     rut = signature_d['subject_serial_number']
     respuesta = _server.getEstCesion(
         token,
         rut[:8],
         str(rut[-1]),
         str(self.sii_document_class_id.sii_code),
         str(self.sii_document_number),
     )
     self.sii_cesion_message = respuesta
     resp = xmltodict.parse(respuesta)
     sii_result = 'Procesado'
     status = False
     if resp['SII:RESPUESTA']['SII:RESP_HDR']['SII:ESTADO'] in ['2', '-13']:
         status = {
             'warning': {
                 'title':
                 _("Error code: 2"),
                 'message':
                 _(resp['SII:RESPUESTA']['SII:RESP_HDR']['SII:GLOSA'])
             }
         }
         sii_result = "Rechazado"
     if resp['SII:RESPUESTA']['SII:RESP_HDR']['SII:ESTADO'] == "0":
         sii_result = "Cedido"
     elif resp['SII:RESPUESTA']['SII:RESP_HDR']['SII:ESTADO'] == "FAU":
         sii_result = "Rechazado"
     self.sii_cesion_result = sii_result
     return status
Example #16
0
def getAsignaturas(request):

    server = SOAPProxy('www.abj-ws-devborja.c9users.io:8080')
    res = json.loads(server.obtenerAsignaturasGradoInformatica())
    data = {}
    data["1"] = []
    data["2"] = []
    data["3"] = []
    data["4"] = []
    data["X"] = []
    for asig in res["asignaturas"]:
        obj = {}
        obj["nombreAsignatura"] = asig["nombreAsignatura"]
        obj["codigo"] = asig["codigo"]
        if asig["curso"] == "1":
            data["1"].append(obj)
        elif asig["curso"] == "2":
            data["2"].append(obj)
        elif asig["curso"] == "3":
            data["3"].append(obj)
        elif asig["curso"] == "4":
            data["4"].append(obj)
        else:
            data["X"].append(obj)
    return HttpResponse(json.dumps(data))
Example #17
0
def googleSearch(title):
    '''
    It is the function of the application that make the request at google WS using
    getting the first url of response.
    
    @param title: the title of the article to serach for
    @return: the first url
    '''
    
    _query=title

    
    # create SOAP proxy object
    google = SOAPProxy(_url, _namespace)
    

    
    # call search method over SOAP proxy
    results = google.doGoogleSearch( _license_key, _query, 
                                     _start, _maxResults, 
                                     _filter, _restrict,
                                     _safeSearch, _lang_restrict, '', '' )
               
    # display results
#    print 'google search for  " ' + _query + ' "\n'
#    print 'estimated result count: ' + str(results.estimatedTotalResultsCount)
#    print '           search time: ' + str(results.searchTime) + '\n'
#    print 'results ' + str(_start + 1) + ' - ' + str(_start + _maxResults) +':\n'
                                                           
    numresults = len(results.resultElements)
    if numresults:
        url = results.resultElements[0].URL
    else:
        url= "#"
    return url
Example #18
0
def textToSpeech2(name, passwd, xlatText):
    server = SOAPProxy(url, namespace)
    server.config.debug = 0
    reqStatus = server.ConvertSimple(name, passwd, xlatText)
    print "request status = ", reqStatus
    retResult = reqStatus.split('&')
    print "request result = ", retResult

    if int(retResult[0]) == 0:
        # check convert progress
        cvtResult = ['0'] * 5
        #statusCode = '0'
        while int(cvtResult[2]) in {0, 1}:  # wait completion
            cvtStatus = server.GetConvertStatus(name, passwd,
                                                int(retResult[2]))
            print "convert status = ", cvtStatus, "ID", retResult[2]
            # on success, status is return URL
            #resultCode, resultString, statusCode, status = cvtStatus.split('&')
            cvtResult = cvtStatus.split('&')
            print cvtResult
            sleep(0.5)

        # save to file
        if (int(cvtResult[2]) == 2):  # '2' means "completed"
            waveUrl = cvtResult[4]
            req = urllib2.Request(waveUrl)
            resp = urllib2.urlopen(req)
            wavFile = resp.read()
            outfile = open(xlatText + u".wav", 'wb')
            outfile.write(wavFile)
    else:
        return retResult[1]
Example #19
0
def createincident(params_dict):

    # instance to send to
    instance = 'demo'

    # username/password
    username = '******'
    password = '******'

    # proxy - NOTE: ALWAYS use https://INSTANCE.service-now.com, not https://www.service-now.com/INSTANCE for web services URL from now on!
    proxy = 'https://%s:%s@%s.service-now.com/incident.do?SOAP' % (
        username, password, instance)
    namespace = 'http://www.service-now.com/'
    server = SOAPProxy(proxy, namespace)

    # uncomment these for LOTS of debugging output
    #server.config.dumpHeadersIn = 1
    #server.config.dumpHeadersOut = 1
    #server.config.dumpSOAPOut = 1
    #server.config.dumpSOAPIn = 1

    response = server.insert(
        impact=int(params_dict['impact']),
        urgency=int(params_dict['urgency']),
        priority=int(params_dict['priority']),
        category=params_dict['category'],
        location=params_dict['location'],
        caller_id=params_dict['user'],
        assignment_group=params_dict['assignment_group'],
        assigned_to=params_dict['assigned_to'],
        short_description=params_dict['short_description'],
        comments=params_dict['comments'])

    return response
Example #20
0
def test_fc(fc_name):
    if os.environ.has_key("http_proxy"):
	my_http_proxy=os.environ["http_proxy"].replace("http://","")
    else:
	my_http_proxy=None
    doc = minidom.parse(xml_file)
    ns   = 'urn:fc.ildg.lqcd.org'
    for fc_test in doc.documentElement.getElementsByTagName("fc"):
        grid_name=fc_test.getElementsByTagName("name")[0].childNodes[0].nodeValue
        fc_url=fc_test.getElementsByTagName("url")[0].childNodes[0].nodeValue
        if grid_name == fc_name:
	    try:
		server = SOAPProxy(fc_url, namespace=ns, http_proxy=my_http_proxy)
		for test_unit in fc_test.getElementsByTagName("test-unit"):
		    lfn=test_unit.getElementsByTagName("lfn")[0].childNodes[0].nodeValue
		    response=server.getURL(lfnList=lfn)
		    val_test=True
		    for val in test_unit.getElementsByTagName("surl"):
			val_test=val_test and val.childNodes[0].nodeValue in response.resultList[0].surlList
			print '==',val.childNodes[0].nodeValue
			print val.childNodes[0].nodeValue in response.resultList[0].surlList
		    print test_unit.getElementsByTagName("surl").length
#		print response
#		print response.resultList
#		print response.resultList[0].surlList
#		    print len(response.resultList[0].surlList)
#		    for item in response.resultList[0].surlList:
#			print '--',item
#		    print val_test
		    if val_test==True: return 0
                    return 1
	    except Exception,inst:
		print inst
		return -1
Example #21
0
def Devicelist(params):
    #returns a list of firewalls
    SessionID = params['SessionID']
    device_list = []
    device_infor = []
    proxy = 'https://' + sHost + '/AFA/php/ws.php?wsdl'
    namespace = 'https://www.algosec.com/afa-ws'
    server = SOAPProxy(proxy, namespace)
    devices = server.GetDevicesListRequest(
        SessionID=SessionID)  #this makes the call to algosec
    devices = str(devices)
    devices = devices.replace("-", "_")  #cleans the data
    devices = devices.split(',')
    for device in devices:
        if "structType" in device:
            device_list.append(device_infor)
            device_infor = []
        else:
            replacement_list = ["'", "}", "{", " "]  #clean the data
            for x in replacement_list:
                device = device.replace(x, "")
            device = device.split(":")
            device_infor.append(device)

    print device_list
    return device_list
def Hostgroup(device,hostgroup,host_list): 
#get information on the Host group 
        proxy = 'https://'+sHost+'/AFA/php/ws.php?wsdl'
        host_Dat=''
        namespace = 'https://www.algosec.com/afa-ws'
        soapaction='https://www.algosec.com/afa-ws/GetEntityNameRequest'
        server = SOAPProxy(proxy, namespace,soapaction)
        if "|" in hostgroup: #handles mutiple hostgroup
                hostgroup=hostgroup.split("|")
                #print hostgroup
                for hosts in hostgroup:
                        if hosts in host_list:
                                host=host_list[hosts]
                        else:
                                host=server.GetHostGroupNameDeviceRequest(SessionID=SessionID,DeviceID=device,HostGroupName=hosts) #soap function to get hostgroup
                                #sends the request to get host
                                host=str(host)
                                host=host.split('>:')
                                host.pop(0)
                                host=host[0]
                                replacement_list=[" ","'","]",'"',"{","}"]
                                for items in replacement_list:
                                        host=host.replace(items,"")
                        #print host
                                host=host.split(",")
                                ctr=0
                                host=str(host[:])
                                host=host.replace(']',"") #cleans data
                                host=host.replace('[',"")
                                host=host.replace("'","")
                                host=host.split(",")
                                host='\n'.join(host)
                        host_Dat=host_Dat+"\n"+"\n"+host
                host_Dat=host_Dat[2:]
                host=host_Dat
        else:
                if hostgroup in host_list:
                        host=host_list[hostgroup]
                else:
                        host=server.GetHostGroupNameDeviceRequest(SessionID=SessionID,DeviceID=device,HostGroupName=hostgroup)
                        #sends the request to get host
                        host=str(host)
                        host=host.split('>:')
                        host.pop(0)
                        host=host[0]
                        replacement_list=[" ","'","]",'"',"{","}"]
                        for items in replacement_list:
                                host=host.replace(items,"")
                        #print host
                        host=host.split(",")
                        host=str(host[:])
                        host=host.replace(']',"")
                        host=host.replace('[',"") #cleans the data 
                        host=host.replace("'","")
                        host=host.replace(" ","")
                        host=host.split(",")
                        host='\n'.join(host)
                        ctr=0
        return host
Example #23
0
def test_cnr_api():
    namespace = ("m", "urn:mpc")
    url = "http://10.20.30.21:8088/"
    proxy = SOAPProxy(url,namespace)
    proxy.config.debug = 1
    proxy.mpccommit(
        strInput = "foo"
    )
def DisconnectAFA(params):
        # deconnects from algosec
        SessionID = params['SessionID']
        proxy = 'https://'+sHost+'/AFA/php/ws.php?wsdl'
        namespace = 'https://www.algosec.com/afa-ws'
        server = SOAPProxy(proxy, namespace)
        response = server.DisconnectRequest(SessionID=SessionID)
        return response
Example #25
0
 def get_token(self, seed_file,company_id):
     url = server_url[company_id.dte_service_provider] + 'GetTokenFromSeed.jws?WSDL'
     ns = 'urn:'+ server_url[company_id.dte_service_provider] +'GetTokenFromSeed.jws'
     _server = SOAPProxy(url, ns)
     tree = etree.fromstring(seed_file)
     ss = etree.tostring(tree, pretty_print=True, encoding='iso-8859-1')
     respuesta = etree.fromstring(_server.getToken(ss))
     token = respuesta[0][0].text
     return token
Example #26
0
  def __init__(self, host, secret):
    """ Creates a UAClient instance.

    Args:
      host: A string specifying the location of the UAServer.
      secret: A string specifying the deployment secret.
    """
    self.secret = secret
    self.server = SOAPProxy('https://{}:{}'.format(host, UA_SERVER_PORT))
Example #27
0
def getSemilla():
    from SOAPpy import SOAPProxy
    import lxml.etree as ET
    url =  'https://maullin.sii.cl/DTEWS/CrSeed.jws?WSDL'
    ns =  'urn:https://maullin.sii.cl/DTEWS/CrSeed.jws'
    _server = SOAPProxy(url, ns)
    root = ET.fromstring(_server.getSeed())
    semilla = root[0][0].text
    return semilla
def ConnectAFA(params):
#starts the connection to algosec 
        username = params['UserName']
        password = params['Password']
        domain = params['Domain'] 
        proxy = 'https://'+sHost+'/AFA/php/ws.php?wsdl'
        namespace = 'https://www.algosec.com/afa-ws'
        soapaction='https://www.algosec.com/afa-ws/GetEntityNameRequest'
        server = SOAPProxy(proxy, namespace,soapaction)
        response = server.ConnectRequest(UserName=username, Password=password, Domain=domain)
        return response
Example #29
0
def getToken(archivo_de_la_semilla):
    from SOAPpy import SOAPProxy
    import lxml.etree as ET
    url =  'https://maullin.sii.cl/DTEWS/GetTokenFromSeed.jws?WSDL'
    ns =  'urn:https://maullin.sii.cl/DTEWS/GetTokenFromSeed.jws'
    _server = SOAPProxy(url, ns)
    tree = ET.parse(archivo_de_la_semilla)
    ss = ET.tostring(tree, pretty_print=True, encoding='iso-8859-1')
    respuesta = ET.fromstring(_server.getToken(ss))
    token = respuesta[0][0].text
    return token
Example #30
0
 def get_seed(self, company_id):
     #En caso de que haya un problema con la validación de certificado del sii ( por una mala implementación de ellos)
     #esto omite la validacion
     import ssl
     ssl._create_default_https_context = ssl._create_unverified_context
     url = server_url[company_id.dte_service_provider] + 'CrSeed.jws?WSDL'
     ns = 'urn:'+server_url[company_id.dte_service_provider] + 'CrSeed.jws'
     _server = SOAPProxy(url, ns)
     root = etree.fromstring(_server.getSeed())
     semilla = root[0][0].text
     return semilla
Example #31
0
 def __init__(self, url, user=None, passwd=None):
     if user is None:
         self.server = SOAPProxy(url)
     else:
         self.server = SOAPProxy(url,
                                 transport=HTTPHeaderTransport,
                                 namespace=self.namespace)
         self.server.transport.headers = {
             'Username': user,
             'Password': passwd
         }
Example #32
0
def generate_keywords(text):
	server = SOAPProxy('http://metanet4u.research.um.edu.mt/services/MtPOS?wsdl')

	# '_NN' is 3 characters long
	words = [w[:-3] for w in server.tagParagraphReturn(text).split(' ') if w[-2:] == 'NN']

	word_dict = defaultdict(int)
	for word in words:
		word_dict[word] += 1

    # returning the most common keywords
	return [x[0] for x in (sorted(word_dict.iteritems(), key=itemgetter(1), reverse=True)[:5])]
Example #33
0
def calendarioanual(request):
    if request.method == 'GET':
        return render(request, 'calendarioanual.html', {})
    elif request.method == "POST":
        body_unicode = request.body.decode('utf-8')
        received_json_data = json.loads(body_unicode)
        json.dumps(received_json_data)
        server = SOAPProxy('www.abj-ws-devborja.c9users.io:8082')
        res = server.crearCalendario(received_json_data)
        calendario = {}
        calendario["calendario"] = res
        return HttpResponse(json.dumps(calendario))
Example #34
0
def consultarCliente(codigoCliente):
	try:	
		servico_venda = SOAPProxy("http://localhost:8009")
		vendas_linhas = servico_venda.listarVenda()
		
		for vendas_linhas in venda_linha:
			codigoVenda, codigoClienteVenda, codigoFuncionario, data, valortotal, codigoProduto, quantidadecodigoVenda, codigoCliente, codigoFuncionario, data, valortotal, codigoProduto, quantidade = venda_linha.split('|')
			if codigoClienteVenda == codigoCliente:
				return True
		return False
	except:
		return False
Example #35
0
    def __init__(self, host, secret):
        """ Creates a UAClient instance.

    Args:
      host: A string specifying the location of the UAServer.
      secret: A string specifying the deployment secret.
    """
        # Disable certificate verification for Python >= 2.7.9.
        if hasattr(ssl, '_create_unverified_context'):
            ssl._create_default_https_context = ssl._create_unverified_context

        self.secret = secret
        self.server = SOAPProxy('https://{}:{}'.format(host, UA_SERVER_PORT))
Example #36
0
    def __init__(self):
        # SOAP proxy 
        self.server = SOAPProxy(self.url, namespace=self.namespace,
                                encoding='ISO-8859-1')

        # Uncomment the following lines for SOAP Debug informations
        # self.server.config.dumpSOAPOut = 1
        # self.server.config.dumpSOAPIn = 1

        # Global session id
        self.session = None
        self.userid = None
        self.passwd = None
def tryHTTPServer():
    import sys
    from SOAPpy import SOAPProxy

    # Start Server: python hicloud.core/http.py -s
    if len(sys.argv) == 2 and sys.argv[1] == '-s':
        listen_port = ('172.20.0.235', 8080)
        server = MixedHTTPServer(listen_port, '')

        class Test1:
            def func1(self):
                return 'Test1 func1'

        class Test2:
            def func2(self):
                return 'Test2 func2'

            def func1(self):
                return 'Test2 func1'

        server.register_soap_module(Test1(), path='test1')
        server.register_soap_module(Test2(), path='test2')
        server.register_soap_module(tryServerclass(), path='tryServerclass')
        server.serve_loop()

    # Run Client: python hicloud.core/http.py
    else:
        proxy = SOAPProxy("http://localhost:8080/test2")
        logger.info(proxy.func1())  # Test2 func1
        logger.info(proxy.func2())  # Test2 func2
        proxy = SOAPProxy("http://localhost:8080/test1")
        logger.info(proxy.func1())  # Test1 func1

        # this call should fail
        logger.info(proxy.func2())
Example #38
0
    def __init__(self, host=None, secret=None):
        """ Creates a UAClient instance.

    Args:
      host: A string specifying the location of the UAServer.
      secret: A string specifying the deployment secret.
    """
        if host is None:
            host = random.choice(get_load_balancer_ips())

        if secret is None:
            secret = get_secret()

        self.secret = secret
        self.server = SOAPProxy('http://{}:{}'.format(host, UA_SERVER_PORT))
Example #39
0
 def setupSoapProxy(self, soapurl, namespace):
     self.soapServiceUrl = soapurl
     self.soapServiceNamespace = namespace
     self.soapServiceProxy = SOAPProxy(soapurl, namespace)
     self.soapResultUnwrappingOff()
     self.soapObjectSimplifyingOff()
     return self.soapServiceProxy
Example #40
0
def deletarVenda(codigo_venda):
    service = SOAPProxy("http://localhost:8009")
    try:
        lines = open(db, "r").readlines()
        existe = False
        for line in lines:
            codigo_venda, codigo_cliente, codigo_funcionario, data, valor_total, codigo_produto, quantidade = line.split(
                '|')
            if codigo_venda == codigo_venda:
                existe = True
        if existe:
            v = open(db, "r")
            lines = v.readlines()
            v.close()

            v = open(db, "w")
            for line in lines:
                codigo_venda, codigo_cliente, codigo_funcionario, data, valor_total, codigo_produto, quantidade = line.split(
                    '|')
                if codigo_venda != codigo_venda:
                    v.write(line)
            v.close()
            return True
    except:
        return False
Example #41
0
    def __init__(self, irc):
        self.__parent = super(Mantis, self)
        self.__parent.__init__(irc)

        self.saidBugs = ircutils.IrcDict()
        sayTimeout = self.registryValue('bugSnarferTimeout')
        for k in irc.state.channels.keys():
            self.saidBugs[k] = TimeoutQueue(sayTimeout)

        self.urlbase = self.registryValue('urlbase')
        self.privateurlbase = self.registryValue('privateurlbase')

        if self.privateurlbase != "":
            serviceUrl = self.privateurlbase + '/api/soap/mantisconnect.php'
        else:
            serviceUrl = self.urlbase + '/api/soap/mantisconnect.php'

        self.server = SOAPProxy(serviceUrl)._ns(namespace)
        self.username = self.registryValue('username')
        self.password = self.registryValue('password')
        self.oldperiodic = self.registryValue('bugPeriodicCheck')
        self.irc = irc
        self.lastBug = 0

        bugPeriodicCheck = self.oldperiodic
        if bugPeriodicCheck > 0:
            schedule.addPeriodicEvent(self._bugPeriodicCheck, bugPeriodicCheck, name=self.name())

        reload(sys)
        sys.setdefaultencoding('utf-8')
Example #42
0
 def __init__(self, url, namespace = None, authCallback = None, debug = 0,
              config = None, faultHandler = None):
     """
     @param url: the url to the service
     @param namespace: the namespace for the service
     @param authCallback: LEGACY
     @param debug: a debugging flag
     @type url: string
     @type namespace: string
     @type authCallback: python method
     @type debug: 0 or 1
     """
     if config == None:
         self.config = SOAPConfig(debug = debug)
     else:
         self.config = config
         
     self.config.debug = debug
     self.config.faultHandler = faultHandler
     print "URL: ", url
     self.url = url.replace('https', 'http')
     self.proxy = None
     self.namespace = namespace
     self.authCallback = authCallback
     self.proxy = SOAPProxy(self.url, self.namespace, config = self.config)
Example #43
0
class BoostDispatcher(Dispatcher):
    """The smsd dispatcher for Boost Communications' External Sender."""

    def __init__(self, config):
        """Constructor."""

        # Call mother's init
        Dispatcher.__init__(self)

        # Get config
        try:
            # Remote address for gateway
            self.url = config['url']
            # Username for WebService
            self.username = config['username']
            # Password for WebService
            self.password = config['password']
            # Our phonenumber
            self.sender = config['sender']
        except KeyError, error:
            raise DispatcherError, "Config option not found: %s" % error

        # Initiate connector to Boost
        try:
            self.service = SOAPProxy(self.url)
        except Exception, error:
            raise DispatcherError, "Failed to initialize SOAPProxy: %s" % error
Example #44
0
def updateRecord(status):
        # instance to send to
        instance='<your instance name>'
        # username/password
        username='******'
        password='******'
        # proxy - NOTE: ALWAYS use https://INSTANCE.service-now.com, not https://www.service-now.com/INSTANCE for web services URL from now on!
        proxy = 'https://'+username+':'+password+'@'+instance+'.service-now.com/sys_user.do?SOAP'
        namespace = 'http://www.service-now.com/'
        server = SOAPProxy(proxy, namespace)
        # uncomment these for LOTS of debugging output
        #server.config.dumpHeadersIn = 1
        #server.config.dumpHeadersOut = 1
        #server.config.dumpSOAPOut = 1
        #server.config.dumpSOAPIn = 1
        response = server.update(sys_id='<sys_id of the user record this will update>',u_presence=status)
        return response
def Devicelist(params):
#returns a list of firewalls optional 
        SessionID = params['SessionID']
        device_list=[]
        device_infor=[]#connection information
        proxy = 'https://'+sHost+'/AFA/php/ws.php?wsdl'
        namespace = 'https://www.algosec.com/afa-ws'
        server = SOAPProxy(proxy, namespace)
        devices=server.GetDevicesListRequest(SessionID=SessionID)
        devices=str(devices)
        devices=devices.split(',')
        for device in devices:
                device_par=device.split(">:")
                if "Types.structType" in device_par[0] or "at" in device_par[0]:
                        device_par.pop(0)
                        try:
                                device_par=device_par[0]
                                replacement_list=[" ","'","]",'"',"{","}"]
                                for items in replacement_list:
                                        device_par=device_par.replace(items,"")
                                device_par=device_par.split(":")
                                #print device_par
                                device_file_list.write(device_par[0]+":"+device_par[1]+"n")
                                if "Policy" in device_par[0]:
                                        device_list.append(device_par[1])
                        except IndexError:
                                pass
                else:
                        try:
                                device_par=device_par[0]
                                replacement_list=[" ","'","]",'"',"{","}"]
                                for items in replacement_list:
                                        device_par=device_par.replace(items,"")
                                device_par=device_par.split(":")
                                #printdevice_par
                                device_file_list.write(device_par[0]+":"+device_par[1]+"\n")
                                if "ID" in device_par[0]:
                                        device_list.append(device_infor)
                                        device_infor=[]
                                        device_infor.append(device_par[0])
                                else:
                                        device_infor.append(device_par[0])
                        except:
                                pass
        #printdevice_list
        return device_list
Example #46
0
 def access_protocol(self):
     '''
     Define the accession protocol information 
     '''
     self.endpointURL = "https://www.brenda-enzymes.org/soap/brenda_server.php"
     self.password = hashlib.sha256(self.pswrd).hexdigest()
     self.client = SOAPProxy(self.endpointURL)
     return None
Example #47
0
def get_brenda_info(ecnum):
    """Returns protein sequence and accompanying info from brenda database"""
    url = "http://www.brenda-enzymes.info/soap2/brenda_server.php"
    client = SOAPProxy(url)
    result = client.getSequence("ecNumber*%s" % ecnum)
    result_lines = result.split("#")
    ecnum = result_lines[0].split("*")
    final_info = []
    currinfo = {"ecNumber": ecnum[1]}
    for info in result_lines[1:-1]:
        key, value = info.split("*")
        if key == "!ecNumber":
            final_info.append(currinfo)
            currinfo = {"ecNumber": value}
        else:
            currinfo[key] = value
    final_info.append(currinfo)
    return final_info
Example #48
0
def generate_keywords(text):
    server = SOAPProxy(
        'http://metanet4u.research.um.edu.mt/services/MtPOS?wsdl')

    # '_NN' is 3 characters long
    words = [
        w[:-3] for w in server.tagParagraphReturn(text).split(' ')
        if w[-2:] == 'NN'
    ]

    word_dict = defaultdict(int)
    for word in words:
        word_dict[word] += 1

# returning the most common keywords
    return [
        x[0] for x in (
            sorted(word_dict.iteritems(), key=itemgetter(1), reverse=True)[:5])
    ]
def createincident(incident):
        proxy = 'https://%s:%s@%s.service-now.com/%s?SOAP' % (username, base64.b64decode(password), instance, interface)
        namespace = 'http://www.service-now.com/'
        server = SOAPProxy(proxy, namespace)
        server.config.dumpHeadersIn = debug
        server.config.dumpHeadersOut = debug
        server.config.dumpSOAPOut = debug
        server.config.dumpSOAPIn = debug
        response = server.insert(
            impact              = incident['impact'],
            urgency             = incident['urgency'],
            priority            = incident['priority'],
            category            = incident['category'],
            subcategory         = incident['subcategory'],
            caller              = incident['caller'],
            assignment_group    = incident['assignment_group'],
            configuration_item  = incident['configuration_item'],
            short_description   = incident['short_description'],
            additional_comments = incident['additional_comments']
        )
        return response
def build_session(resource):
    """returns a SOAP session."""

    proxy = 'https://%s:%s@%s.service-now.com/%s.do?SOAP' %\
            (servicenow_conf.USERNAME, servicenow_conf.PASSWORD,
             servicenow_conf.INSTANCE, resource)
    namespace = 'http://www.service-now.com/'

    try:
        session = SOAPProxy(proxy, namespace)
        session.simplify_objects = 1

        if (servicenow_conf.SOAP_API_DEBUG):
            session.config.dumpHeadersIn = 1
            session.config.dumpHeadersOut = 1
            session.config.dumpSOAPOut = 1
            session.config.dumpSOAPIn = 1

        return session
    except Exception, e:
        raise Exception('Error creating SOAP session: %s' % e)
Example #51
0
  def __init__(self, host, secret):
    """ Creates a UAClient instance.

    Args:
      host: A string specifying the location of the UAServer.
      secret: A string specifying the deployment secret.
    """
    # Disable certificate verification for Python >= 2.7.9.
    if hasattr(ssl, '_create_unverified_context'):
      ssl._create_default_https_context = ssl._create_unverified_context

    self.secret = secret
    self.server = SOAPProxy('https://{}:{}'.format(host, UA_SERVER_PORT))
Example #52
0
def obtenerGrupos(request):
    if request.method == "POST":
        server = SOAPProxy('www.abj-ws-devborja.c9users.io:8080')
        server2 = SOAPProxy('www.abj-ws-devborja.c9users.io:8082')
        body_unicode = request.body.decode('utf-8')
        received_json_data = json.loads(body_unicode)
        data = []
        for key, value in received_json_data.iteritems():
            for item in value:
                obj = {}
                res = server.obtenerGruposAsignaturaInformatica(item, key)
                res = json.loads(server.obtenerHorarioAsignatura(item, res["grupos"][0]))
                #res = json.loads(server.obtenerHorarioAsignatura(item, "01"))
                obj["nombreAsignatura"] = res["nombreAsignatura"]
                obj["eventos"] = res["horarioGrupoAsignatura"][0]["eventos"]
                data.append(obj)
        with open('anual.json') as data_file:
            dataCal = json.load(data_file)
        horario = server2.crearCalendarioCompleto(json.dumps(data), json.dumps(dataCal))
        calendario = {}
        calendario["calendario"] = horario
        return HttpResponse(json.dumps(calendario))
Example #53
0
    def __init__(self):
        # SOAP proxy 
        self.server = SOAPProxy(self.url, namespace=self.namespace,
                                encoding='ISO-8859-1')

        # Uncomment the following lines for SOAP Debug informations
        # self.server.config.dumpSOAPOut = 1
        # self.server.config.dumpSOAPIn = 1

        # Global session id
        self.session = None
        self.userid = None
        self.passwd = None
def main():
	url = 'http://localhost:8081'
	#namespace = 'ns-hello'

	server = SOAPProxy(url)
	#server.config.dumpSOAPOut = 1
	#server.config.dumpSOAPIn = 1

	#print server.insereOrgao('Ministerio do Planejamento', 'Esplanada dos Ministerios N 1', 'Brasilia','DF')
	
#	orgaos = server.listaOrgao(nome='Ministerio do Planejamento')
#	for orgao in orgaos:
#		print orgao['id']
		
#	if len(orgaos) == 1:
#		print orgaos[0]['id']
#		server.insereEmpregado('Debora Natsue', '01/01/2010',None,'06/10/1989','M000005','9876765','222222222-22',orgaos[0]['id'],None,None)

#	empregados = server.listaEmpregados(nome='Debora')
#	for empregado in empregados:
#		print empregado['nome']

#	dependentes = server.listaDependentes(nomeDependente='Diogo')
#	for dependente in dependentes:
#		print dependente['nome']

#	empregados = server.listaEmpregados (nome='Debora')
#	print server.insereDependente('Tassia','1234234','222.222.222-22',None,'29/09/1992','Filho',None,empregados[0]['id'])

#	file=open('/home/wanzeller/python/teste.txt', 'rb')
#	data=file.read()
#	print server.insereDocEmpregado('M000005','Comprovante de Residencia','comprv_residencia.txt',data.encode('base64'))
#	file.close()

	file=open('/home/wanzeller/python/bkp_lista_orgaos.txt', 'rb')
	data=file.read()
	print server.insereDocDependente('M808130','2649051','34347984793',None,'5216ae1f6e955269534b077f','certidao_nascimento.txt',data.encode('base64'))
	file.close()
Example #55
0
def GetWikiPaths4IDs(idList,SC):
    # Function that uses a list of IDs and a systm code as input and
    # returns a string with all the WikiPathways where th IDs exist (including the new lines) as tab separated fields:
    # No, ID, Species, Pathway ID, Pathway Name

    # Load SOAPpy and dependent modules (fpconst) and access the remote
    # SOAP server through a proxy class, SOAPProxy - see:
    # (http://diveintopython.org/soap_web_services/first_steps.html)

    from SOAPpy import SOAPProxy
    url = 'http://www.wikipathways.org/wpi/webservice/webservice.php'
    namespace = 'http://www.wikipathways.org/webservice'
    server = SOAPProxy(url, namespace)

    # Define the order of args: needed for this service
    server.config.argsOrdering = {'findPathwaysByXref': ('ids', 'codes') }
    
    index=1 # index of the result lines
    print_output = '' # output of the function
    # For each ID findPathwaysByXref (multiple args; returns list of dictionary references)
    for gi in idList:
        # checking any erors
        try:
            probeset_containing = server.findPathwaysByXref(codes=SC, ids=gi)
            NoPaths = len(probeset_containing)
            #Loops through a list of dictionary items if results
            if NoPaths > 0 :
                for object in probeset_containing:
                    #calls select dictionary keys to print out values            
                    print_output += str(int(index))+'\t'+str(gi)+'\t'+str(object['species'])+'\t'+str(object['id'])+'\t'+str(object['name'])+'\n'
                    index+=1
            else:
                print gi, "can't be found in WikiPathways!"
        except:
            #pass # if error do nothing
            print gi, 'has', NoPaths, 'pathways but it can be processed!'
    return print_output
Example #56
0
def ex2():
    service = 'http://chennaiemergency.co.in/sree/s2.php'
    #namespace = 'urn:ChnEmergency'
    #chennai_emergency = SOAPProxy(service, namespace)
    chennai_emergency = SOAPProxy(service)
    latitude = floatType(11)
    longitude = floatType(12.1)
    print 'Police: '
    print chennai_emergency.police(latitude, longitude)
    print '\nFire:'
    print chennai_emergency.fire(latitude, longitude)
    print '\nHospital:'
    print chennai_emergency.hospital(latitude, longitude)
Example #57
0
class RemoteExecutor:
    def __init__(self, url, slots):
        """ url: SOAP url for SWAMP slave
            slots: max number of running slots

            RemoteExecutor adapts a remote worker's execution resources
            so that they may be used by a parallel dispatcher.
            """
        self.url = url
        self.slots = slots
        self.rpc = SOAPProxy(url)
        log.debug("reset slave at %s with %d slots" %(url,slots))
        try:
            self.rpc.reset()
        except Exception, e:
            import traceback, sys
            tb_list = traceback.format_exception(*sys.exc_info())
            msg =  "".join(tb_list)
            raise StandardError("can't connect to "+url+str(msg))
        self.runningClusters = set()
        self.finishedClusters = set()
        self.actual = {}
        self.cmds = {}
        pass
Example #58
0
class SOAPTransport(Transport):
    def __init__(self, repository, url):

        super(SOAPTransport, self).__init__(repository)
        self.url = url

    def open(self):

        self.server = SOAPProxy(self.url, encoding="utf-8")

    def _call(self, method, *args):

        try:
            return self.server.call(method, *args)
        except Exception, e:
            raise
Example #59
0
# Check for a web proxy definition in environment
try:
   proxy_url=os.environ['http_proxy']
   phost, pport = re.search('http://([^:]+):([0-9]+)', proxy_url).group(1,2)
   proxy = "%s:%s" % (phost, pport)
except:
   proxy = None

SoapEndpointURL	   = 'http://www22.brinkster.com/prasads/BreakingNewsService.asmx?WSDL'

MethodNamespaceURI = 'http://tempuri.org/'

# Three ways to do namespaces, force it at the server level

server = SOAPProxy(SoapEndpointURL, namespace = MethodNamespaceURI,
                   soapaction='http://tempuri.org/GetCNNNews', encoding = None,
                   http_proxy=proxy)
print "[server level CNN News call]" 
print server.GetCNNNews()

# Do it inline ala SOAP::LITE, also specify the actually ns (namespace) and
# sa (soapaction)

server = SOAPProxy(SoapEndpointURL, encoding = None)
print "[inline CNNNews call]" 
print server._ns('ns1',
    MethodNamespaceURI)._sa('http://tempuri.org/GetCNNNews').GetCNNNews()

# Create an instance of your server with specific namespace and then use
# inline soapactions for each call
Example #60
0
#!/usr/bin/env python

ident = '$Id: weatherTest.py,v 1.4 2003/05/21 14:52:37 warnes Exp $'

import os, re
import sys
sys.path.insert(1, "..")

from SOAPpy import SOAPProxy

# Check for a web proxy definition in environment
try:
   proxy_url=os.environ['http_proxy']
   phost, pport = re.search('http://([^:]+):([0-9]+)', proxy_url).group(1,2)
   proxy = "%s:%s" % (phost, pport)
except:
   proxy = None

SoapEndpointURL	= 'http://services.xmethods.net:80/soap/servlet/rpcrouter'
MethodNamespaceURI = 'urn:xmethods-Temperature'

# Do it inline ala SOAP::LITE, also specify the actually ns

server = SOAPProxy(SoapEndpointURL, http_proxy=proxy)
print "inline", server._ns('ns1', MethodNamespaceURI).getTemp(zipcode='94063')