Пример #1
0
    def test_exception(self):
        xml = """<?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
           <soap:Body>
             <Divider xmlns="http://example.com/sample.wsdl">
               <a>100</a><b>2</b>
            </Divider>
           </soap:Body>
        </soap:Envelope>"""
        response = SimpleXMLElement(self.dispatcher.dispatch(xml))
        self.assertEqual(str(response.DivideResult), '50.0')

        xml = """<?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
           <soap:Body>
             <Divider xmlns="http://example.com/sample.wsdl">
               <a>100</a><b>0</b>
            </Divider>
           </soap:Body>
        </soap:Envelope>"""
        response = SimpleXMLElement(self.dispatcher.dispatch(xml))
        body = getattr(getattr(response, 'soap:Body'), 'soap:Fault')
        self.assertIsNotNone(body)
        self.assertEqual(str(body.faultcode), 'Server.DivisionByZero')
        self.assertEqual(str(body.faultstring), 'Division by zero not allowed')
        self.assertEqual(str(body.detail), 'test')
Пример #2
0
def serializar(regs):
    "Dado una lista de comprobantes (diccionarios), convierte a xml"
    xml = SimpleXMLElement(XML_BASE)

    comprobantes = []
    for reg in regs:
        dic = {}
        for k, v in MAP_ENC.items():
            dic[v] = reg[k]
                
        dic.update({
                'detalles': [{
                    'detalle': mapear({}, det, MAP_DET, swap=True),
                    } for det in reg['detalles']],                
                'tributos': [{
                    'tributo': mapear({}, trib, MAP_TRIB, swap=True),
                    } for trib in reg['tributos']],
                'ivas': [{
                    'iva': mapear({}, iva, MAP_IVA, swap=True),
                    } for iva in reg['ivas']],
                'formaspago': [{
                'formapago': {
                    'codigo': '',
                    'descripcion': reg['forma_pago'],
                    }}]
                })
        comprobantes.append(dic)

    for comprobante in comprobantes:
        xml.marshall("comprobante", comprobante)
    return xml.as_xml()
    def test_tuple_unmarshall(self):
        xml = """
        <foo>
            <boo>
                <bar>abc</bar>
                <baz>1</baz>
            </boo>
            <boo>
                <bar>qwe</bar>
                <baz>2</baz>
            </boo>
        </foo>
        """
        span = SimpleXMLElement(xml)
        d = {'foo': {'boo': ({'bar': str, 'baz': int}, )}}

        e = {
            'foo': {
                'boo': (
                    {
                        'bar': 'abc',
                        'baz': 1
                    },
                    {
                        'bar': 'qwe',
                        'baz': 2
                    },
                )
            }
        }
        self.eq(span.unmarshall(d), e)
Пример #4
0
 def call(self, method, *args, **kwargs):
     "Prepara el xml y realiza la llamada SOAP, devuelve un SimpleXMLElement"
     # Mensaje de Solicitud SOAP básico:
     xml = self.__xml % dict(method=method,
                             namespace=self.namespace,
                             ns=self.__ns,
                             soap_ns=self.__soap_ns,
                             soap_uri=soap_namespaces[self.__soap_ns])
     request = SimpleXMLElement(xml,
                                namespace=self.__ns and self.namespace,
                                prefix=self.__ns)
     # parsear argumentos
     if kwargs:
         parameters = kwargs.items()
     else:
         parameters = args
     for k, v in parameters:  # dict: tag=valor
         self.parse(getattr(request, method), k, v)
     self.xml_request = request.as_xml()
     self.xml_response = self.send(method, self.xml_request)
     response = SimpleXMLElement(self.xml_response,
                                 namespace=self.namespace)
     if self.exceptions and ("soapenv:Fault" in response
                             or "soap:Fault" in response):
         raise SoapFault(unicode(response.faultcode),
                         unicode(response.faultstring))
     return response
Пример #5
0
    def __init__(self, location):
        self.location = location

        # parse location url
        scheme, netloc, path, _, _, _ = urlparse(location)
        self.address = '%s://%s' % (scheme, netloc)

        # parse device description
        Http = get_Http()
        self.http = Http(timeout=1)
        xml = fetch(self.location, self.http)
        d = SimpleXMLElement(xml)
        self.friendly_name = str(next(d.device.friendlyName()))
        self.model_description = str(next(d.device.modelDescription()))
        self.model_name = str(next(d.modelName()))

        # set up soap clients
        self.rendering_control = SoapClient(
            location='%s/RenderingService/Control' % self.address,
            action='urn:upnp-org:serviceId:RenderingControl#',
            namespace='http://schemas.xmlsoap.org/soap/envelope/',
            soap_ns='soap',
            ns='s',
            exceptions=True)
        self.av_transport = SoapClient(
            location='%s/TransportService/Control' % self.address,
            action='urn:schemas-upnp-org:service:AVTransport:1#',
            namespace='http://schemas.xmlsoap.org/soap/envelope/',
            soap_ns='soap',
            ns='s',
            exceptions=True)
Пример #6
0
def desserializar(xml):
    "Analiza un XML y devuelve un diccionario"
    xml = SimpleXMLElement(xml)

    dic = xml.unmarshall(XML_FORMAT, strict=True)

    regs = []

    for dic_comprobante in dic['comprobantes']:
        reg = {
            'detalles': [],
            'ivas': [],
            'tributos': [],
            'permisos': [],
            'cmps_asocs': [],
        }
        comp = dic_comprobante['comprobante']
        mapear(reg, comp, MAP_ENC)
        reg['forma_pago'] = ''.join([d['formapago']['descripcion'] for d in comp['formaspago']])

        for detalles in comp['detalles']:
            det = detalles['detalle']
            reg['detalles'].append(mapear({}, det, MAP_DET))

        for ivas in comp['ivas']:
            iva = ivas['iva']
            reg['ivas'].append(mapear({}, iva, MAP_IVA))

        for tributos in comp['tributos']:
            tributo = tributos['tributo']
            reg['tributos'].append(mapear({}, tributo, MAP_TRIB))

        regs.append(reg)
    return regs
Пример #7
0
def serializar(regs):
    "Dado una lista de comprobantes (diccionarios), convierte a xml"
    xml = SimpleXMLElement(XML_BASE)

    comprobantes = []
    for reg in regs:
        dic = {}
        for k, v in list(MAP_ENC.items()):
            dic[v] = reg[k]

        dic.update({
            'detalles': [{
                'detalle': mapear({}, det, MAP_DET, swap=True),
            } for det in reg['detalles']],
            'tributos': [{
                'tributo': mapear({}, trib, MAP_TRIB, swap=True),
            } for trib in reg['tributos']],
            'ivas': [{
                'iva': mapear({}, iva, MAP_IVA, swap=True),
            } for iva in reg['ivas']],
            'formaspago': [{
                'formapago': {
                    'codigo': '',
                    'descripcion': reg['forma_pago'],
                }}]
        })
        comprobantes.append(dic)

    for comprobante in comprobantes:
        xml.marshall("comprobante", comprobante)
    return xml.as_xml()
Пример #8
0
    def __init__(self, location):
        self.location = location

        # parse location url
        scheme, netloc, path, _, _, _ = urlparse(location)
        self.address = '%s://%s' % (scheme, netloc)

        # parse device description
        Http = get_Http()
        self.http = Http(timeout=1)
        xml = fetch(self.location, self.http)
        d = SimpleXMLElement(xml)
        self.friendly_name = str(next(d.device.friendlyName()))
        self.model_description = str(next(d.device.modelDescription()))
        self.model_name = str(next(d.modelName()))

        # set up soap clients
        self.rendering_control = SoapClient(
            location='%s/RenderingService/Control' % self.address,
            action='urn:upnp-org:serviceId:RenderingControl#',
            namespace='http://schemas.xmlsoap.org/soap/envelope/',
            soap_ns='soap', ns='s', exceptions=True)
        self.av_transport = SoapClient(
            location='%s/TransportService/Control' % self.address,
            action='urn:schemas-upnp-org:service:AVTransport:1#',
            namespace='http://schemas.xmlsoap.org/soap/envelope/',
            soap_ns='soap', ns='s', exceptions=True)
Пример #9
0
def desserializar(xml):
    "Analiza un XML y devuelve un diccionario"
    xml = SimpleXMLElement(xml)

    dic = xml.unmarshall(XML_FORMAT, strict=True)
    
    regs = []

    for dic_comprobante in dic['comprobantes']:
        reg = {
            'detalles': [],
            'ivas': [],
            'tributos': [],
            'permisos': [],
            'cmps_asocs': [],
            }
        comp = dic_comprobante['comprobante']
        mapear(reg, comp, MAP_ENC)
        reg['forma_pago']= ''.join([d['formapago']['descripcion'] for d in comp['formaspago']])


        for detalles in comp['detalles']:
            det = detalles['detalle']
            reg['detalles'].append(mapear({}, det, MAP_DET))
            
        for ivas in comp['ivas']:
            iva = ivas['iva']
            reg['ivas'].append(mapear({}, iva, MAP_IVA))

        for tributos in comp['tributos']:
            tributo = tributos['tributo']
            reg['tributos'].append(mapear({}, tributo, MAP_TRIB))

        regs.append(reg)
    return regs
Пример #10
0
def generate_wsa_header_for_soap12(ns_binding, action):
    action_header = ns_binding + action

    soap_header = SimpleXMLElement('<Header></Header>')
    soap_header.add_child('To', Config.FRT_WS_URL, WSA_NS)
    soap_header.add_child('Action', action_header, WSA_NS)
    return soap_header
Пример #11
0
    def test_marshall_cdata(self):
        span = SimpleXMLElement('<span/>')
        cdata = CDATASection()
        cdata.data = 'python'
        span.add_child('a', cdata)

        xml = '<?xml version="1.0" encoding="UTF-8"?><span><a><![CDATA[python]]></a></span>'
        self.eq(span.as_xml(), xml if PY2 else xml.encode('utf-8'))
    def test_marshall_cdata(self):
        span = SimpleXMLElement('<span/>')
        cdata = CDATASection()
        cdata.data = 'python'
        span.add_child('a', cdata)

        xml = '<?xml version="1.0" encoding="UTF-8"?><span><a><![CDATA[python]]></a></span>'
        self.eq(span.as_xml(), xml if PY2 else xml.encode('utf-8'))
    def test_adv_unmarshall(self):
        xml = """
        <activations>
            <items>
                <number>01234</number>
                <status>1</status>
                <properties>
                    <name>foo</name>
                    <value>3</value>
                </properties>
                <properties>
                    <name>bar</name>
                    <value>4</value>
                </properties>
            </items>
            <items>
                <number>04321</number>
                <status>0</status>
            </items>
        </activations>
        """
        span = SimpleXMLElement(xml)
        d = {
            'activations': [{
                'items': {
                    'number': str,
                    'status': int,
                    'properties': ({
                        'name': str,
                        'value': int
                    }, )
                }
            }]
        }

        e = {
            'activations': [{
                'items': {
                    'number':
                    '01234',
                    'status':
                    1,
                    'properties': ({
                        'name': 'foo',
                        'value': 3
                    }, {
                        'name': 'bar',
                        'value': 4
                    })
                }
            }, {
                'items': {
                    'number': '04321',
                    'status': 0
                }
            }]
        }
        self.eq(span.unmarshall(d), e)
Пример #14
0
def get_bugs(*key_value):
    """Get list of bugs matching certain criteria.

    The conditions are defined by key value pairs.

    Possible keys are:
        * "package": bugs for the given package
        * "submitter": bugs from the submitter
        * "maint": bugs belonging to a maintainer
        * "src": bugs belonging to a source package
        * "severity": bugs with a certain severity
        * "status": can be either "done", "forwarded", or "open"
        * "tag": see http://www.debian.org/Bugs/Developer#tags for
           available tags
        * "owner": bugs which are assigned to `owner`
        * "bugs": takes single int or list of bugnumbers, filters the list
           according to given criteria
        * "correspondent": bugs where `correspondent` has sent a mail to

    Arguments
    ---------
    key_value : str

    Returns
    -------
    bugs : list of ints
        the bugnumbers

    Examples
    --------
    >>> get_bugs('package', 'gtk-qt-engine', 'severity', 'normal')
    [12345, 23456]

    """
    # previous versions also accepted
    # get_bugs(['package', 'gtk-qt-engine', 'severity', 'normal'])
    # if key_value is a list in a one elemented tuple, remove the
    # wrapping list
    if len(key_value) == 1 and isinstance(key_value[0], list):
        key_value = tuple(key_value[0])

    # pysimplesoap doesn't generate soap Arrays without using wsdl
    # I build body by hand, converting list to array and using standard
    # pysimplesoap marshalling for other types
    method_el = SimpleXMLElement('<get_bugs></get_bugs>')
    for arg_n, kv in enumerate(key_value):
        arg_name = 'arg' + str(arg_n)
        if isinstance(kv, (list, tuple)):
            _build_int_array_el(arg_name, method_el, kv)
        else:
            method_el.marshall(arg_name, kv)

    soap_client = _build_soap_client()
    reply = soap_client.call('get_bugs', method_el)
    items_el = reply('soapenc:Array')
    return [int(item_el) for item_el in items_el.children() or []]
Пример #15
0
def get_bugs(*key_value):
    """Get list of bugs matching certain criteria.

    The conditions are defined by key value pairs.

    Possible keys are:
        * "package": bugs for the given package
        * "submitter": bugs from the submitter
        * "maint": bugs belonging to a maintainer
        * "src": bugs belonging to a source package
        * "severity": bugs with a certain severity
        * "status": can be either "done", "forwarded", or "open"
        * "tag": see http://www.debian.org/Bugs/Developer#tags for
           available tags
        * "owner": bugs which are assigned to `owner`
        * "bugs": takes single int or list of bugnumbers, filters the list
           according to given criteria
        * "correspondent": bugs where `correspondent` has sent a mail to

    Arguments
    ---------
    key_value : str

    Returns
    -------
    bugs : list of ints
        the bugnumbers

    Examples
    --------
    >>> get_bugs('package', 'gtk-qt-engine', 'severity', 'normal')
    [12345, 23456]

    """
    # previous versions also accepted
    # get_bugs(['package', 'gtk-qt-engine', 'severity', 'normal'])
    # if key_value is a list in a one elemented tuple, remove the
    # wrapping list
    if len(key_value) == 1 and isinstance(key_value[0], list):
        key_value = tuple(key_value[0])

    # pysimplesoap doesn't generate soap Arrays without using wsdl
    # I build body by hand, converting list to array and using standard
    # pysimplesoap marshalling for other types
    method_el = SimpleXMLElement('<get_bugs></get_bugs>')
    for arg_n, kv in enumerate(key_value):
        arg_name = 'arg' + str(arg_n)
        if isinstance(kv, (list, tuple)):
            _build_int_array_el(arg_name, method_el, kv)
        else:
            method_el.marshall(arg_name, kv)

    soap_client = _build_soap_client()
    reply = soap_client.call('get_bugs', method_el)
    items_el = reply('soapenc:Array')
    return [int(item_el) for item_el in items_el.children() or []]
Пример #16
0
 def test_attributes_access(self):
     span = SimpleXMLElement('<span><a href="python.org.ar">pyar</a><prueba><i>1</i><float>1.5</float></prueba></span>')
     text = "pyar"
     self.eq(str(span.a), text, 'Access by __getattr__:')
     self.eq(str(span.a), text, 'Access by __getattr__:')
     self.eq(str(span('a')), text, 'Access by __call__:')
     self.eq(str(span.a(0)), text, 'Access by __call__ on attribute:')
     self.eq(span.a['href'], "python.org.ar", 'Access by __getitem__:')
     self.eq(int(span.prueba.i), 1, 'Casting to int:')
     self.eq(float(span.prueba.float), 1.5, 'Casting to float:')
Пример #17
0
 def AnalizarXml(self, xml=""):
     "Analiza un mensaje XML (por defecto la respuesta)"
     try:
         if not xml:
             xml = self.XmlResponse
         self.xml = SimpleXMLElement(xml)
         return True
     except Exception as e:
         self.Excepcion = u"%s" % (e)
         return False
Пример #18
0
 def test_multiple_element_unmarshall_one(self):
     xml = """
     <results>
         <foo>bar</foo>
     </results>
     """
     span = SimpleXMLElement(xml)
     d = {'results': {'foo': [str]}}
     e = {'results': {'foo': ['bar']}}
     self.eq(span.unmarshall(d), e)
Пример #19
0
 def test_multiple_element_unmarshall_one(self):
     xml = """
     <results>
         <foo>bar</foo>
     </results>
     """
     span = SimpleXMLElement(xml)
     d = {'results': {'foo': [str]}}
     e = {'results': {'foo': ['bar']}}
     self.eq(span.unmarshall(d), e)
 def test_attributes_access(self):
     span = SimpleXMLElement('<span><a href="python.org.ar">pyar</a><prueba><i>1</i><float>1.5</float></prueba></span>')
     text = "pyar"
     self.eq(str(span.a), text, 'Access by __getattr__:')
     self.eq(str(span.a), text, 'Access by __getattr__:')
     self.eq(str(span('a')), text, 'Access by __call__:')
     self.eq(str(span.a(0)), text, 'Access by __call__ on attribute:')
     self.eq(span.a['href'], "python.org.ar", 'Access by __getitem__:')
     self.eq(int(span.prueba.i), 1, 'Casting to int:')
     self.eq(float(span.prueba.float), 1.5, 'Casting to float:')
Пример #21
0
    def test_to_xml(self):
        xml = (
            '<?xml version="1.0" encoding="UTF-8"?><span><a href="python.org.ar">'
            'pyar</a><prueba><i>1</i><float>1.5</float></prueba></span>')
        self.eq(SimpleXMLElement(xml).as_xml(), xml if PY2 else xml.encode('utf-8'))

        xml = (
            '<?xml version="1.0" encoding="UTF-8"?><span><a href="google.com">'
            'google</a><a>yahoo</a><a>hotmail</a></span>')
        self.eq(SimpleXMLElement(xml).as_xml(), xml if PY2 else xml.encode('utf-8'))
    def test_unmarshall(self):
        span = SimpleXMLElement(
            '<span><name>foo</name><value>3</value></span>')
        d = {'span': {'name': str, 'value': int}}
        e = {'span': {'name': 'foo', 'value': 3}}
        self.eq(span.unmarshall(d), e)

        span = SimpleXMLElement(
            '<span><name>foo</name><name>bar</name></span>')
        d = {'span': [{'name': str}]}
        e = {'span': [{'name': 'foo'}, {'name': 'bar'}]}
        self.eq(span.unmarshall(d), e)

        span = SimpleXMLElement(
            '<activations><items><number>01234</number><status>1</status></items><items><number>04321</number><status>0</status></items></activations>'
        )
        d = {'activations': [{'items': {'number': str, 'status': int}}]}

        e = {
            'activations': [{
                'items': {
                    'number': '01234',
                    'status': 1
                }
            }, {
                'items': {
                    'number': '04321',
                    'status': 0
                }
            }]
        }
        self.eq(span.unmarshall(d), e)
Пример #23
0
def initializeReg(apitoken):
	client = SoapClient(
		wsdl = "https://www.regonline.com/api/default.asmx?WSDL"
		, trace = False)

	header = SimpleXMLElement("<Headers/>")

	MakeHeader = header.add_child("TokenHeader")
	MakeHeader.add_attribute('xmlns','http://www.regonline.com/api')
	MakeHeader.marshall('APIToken', apitoken)
	client['TokenHeader']=MakeHeader
	return client
Пример #24
0
    def changeChannels(self, principal, channels,
                       principalType=None):
        params = {u'principal': principal}
        if principalType is not None:
            params[u'principalType'] = principalType

        xml_params = SimpleXMLElement('<dummyroot><params/></dummyroot>')
        for name, value in params.items():
            xml_params.params.marshall(name, value)

        changeChannelsParameters = []
        for internal_name, channel_enabled in channels.items():
            enabled = '0'
            if channel_enabled:
                enabled = '1'

            changeChannelsParameters.append({u'channel': internal_name,
                                             u'enabled': enabled})

        for changeChannelParameters in changeChannelsParameters:
            xml_params.params.marshall('channels',
                                       changeChannelParameters)

        client = self.get_client()
        operation = client.get_operation('changeChannels')
        output = operation['output']
        soap_uri = soap_namespaces['soap']

        soap_response = client.call('changeChannels', xml_params)

        _log_response(soap_response)

        return soap_response['return']
    def listAllByStudy(self, study):
        """
        """
        params = SimpleXMLElement("""<?xml version="1.0" encoding="UTF-8"?>
            <listAllRequest>
            <v1:studyEventDefinitionListAll xmlns:v1="http://openclinica.org/ws/studyEventDefinition/v1">
            <bean:studyRef xmlns:bean="http://openclinica.org/ws/beans">
            <bean:identifier>""" + study.identifier + """</bean:identifier>
            </bean:studyRef>
            </v1:studyEventDefinitionListAll>
            </listAllRequest>""")

        response = self.client.call('listAllRequest', params)

        studyEventDefinitions = []
        for studyEventDefinition in response.studyEventDefinitions.children():

            oid = str(studyEventDefinition.oid)
            name = str(studyEventDefinition.name)

            eventDefinitionCrfs = []
            for eventDefinitionCrf in studyEventDefinition.eventDefinitionCrfs.children(
            ):

                required = str(eventDefinitionCrf.required)
                doubleDataEntry = str(eventDefinitionCrf.doubleDataEntry)
                passwordRequired = str(eventDefinitionCrf.passwordRequired)
                hideCrf = str(eventDefinitionCrf.hideCrf)
                sourceDataVerificaiton = str(
                    eventDefinitionCrf.sourceDataVerificaiton)

                # Ugly but it works
                index = 0
                defaultCrfVersionOid = None
                obtainedDefaultCrfVersion = None
                for ch in eventDefinitionCrf.children():
                    if ch.children():
                        if index == 0:
                            crfOid = str(ch.oid)
                            crfName = str(ch.name)
                            obtainedCrf = Crf(crfOid, crfName)
                        elif index == 1:
                            defaultCrfVersionOid = str(ch.oid)
                            defaultCrfVersionName = str(ch.name)
                            obtainedDefaultCrfVersion = CrfVersion(
                                defaultCrfVersionOid, defaultCrfVersionName)
                        index = index + 1

                obtainedEventDefinitionCrf = EventDefinitionCrf(
                    required, doubleDataEntry, passwordRequired, hideCrf,
                    sourceDataVerificaiton, obtainedCrf,
                    obtainedDefaultCrfVersion)

                eventDefinitionCrfs.append(obtainedEventDefinitionCrf)

            obtainedStudyEventDefintion = StudyEventDefinition(
                oid, name, eventDefinitionCrfs)
            studyEventDefinitions.append(obtainedStudyEventDefintion)

        return studyEventDefinitions
Пример #26
0
    def create(self, studySubject, study, studySite):
        """Create new StudySubject in OpenClinica
        """
        result = ""

        params = SimpleXMLElement("""<?xml version="1.0" encoding="UTF-8"?>
            <createRequest>
            <v1:studySubject xmlns:v1="http://openclinica.org/ws/studySubject/v1">
            <bean:label xmlns:bean="http://openclinica.org/ws/beans">""" + "" + """</bean:label>
            <bean:enrollmentDate xmlns:bean="http://openclinica.org/ws/beans">
            """ + studySubject.enrollmentDate.isoformat() + """
            </bean:enrollmentDate>
            <bean:subject xmlns:bean="http://openclinica.org/ws/beans">
            <bean:uniqueIdentifier>""" + studySubject.subject.uniqueIdentifier + """</bean:uniqueIdentifier>
            <bean:gender>""" + studySubject.subject.gender + """</bean:gender>
            </bean:subject>
            <bean:studyRef xmlns:bean="http://openclinica.org/ws/beans">
            <bean:identifier>""" + study.identifier() + """</bean:identifier>
            <bean:siteRef>
            <bean:identifier>""" + studySite.identifier + """</bean:identifier>
            </bean:siteRef>
            </bean:studyRef>
            </v1:studySubject>
            </createRequest>""")

        response = self.client.call('createRequest', params)

        result = str(response.result)
        return result
Пример #27
0
def submit_problem(url, params):
    p = SimpleXMLElement("<submitProblem></submitProblem>")
    for k, v in params.items():
        child = p.add_child(k, v)
        child.add_attribute("xsi:type", "xsd:string")

    client = SoapClient(
        location = url,
        action = '',
        soap_ns = 'soapenv',
        namespace = 'http://www.decision-deck.org/2009/XMCDA-2.0.0',
        trace = False)

    sp = client.call('submitProblem', p)
    reply = sp.submitProblemResponse
    return str(reply.ticket)
Пример #28
0
    def call(self, uri, method, *args):
        '''Builds the a SOAP method call and runs it

        Args:
           uri (str): the SOAP method endpoint URI.
           method (str): the name of the method to call.
           args (tuple of str): extraneous arguments to pass to the method

        Note:
           Extraneous arguments should be passed in the same order as the
           remote method expects them.
        '''
        args = ''.join([
            '<arg{argnum}>{value}</arg{argnum}>'.format(argnum=i + 2,
                                                        value=value)
            for i, value in enumerate(args)
        ])
        client = self.get_client(uri)
        client['AuthHeaderElement'] = {
            'username': self._user,
            'password': self._pass
        }
        params = SimpleXMLElement(
            VESSEL_QUERY_BODY.format(password=self._pass,
                                     login=self._user,
                                     method=method,
                                     args=args))
        return client.call(method, params)
Пример #29
0
    def create(self, studySubject, study, metadata=None):
        """Create new StudySubject in OpenClinica
        """
        result = ""

        #TODO: depending on metadata (secondaryLabel, uniqueIdentifier, dateOfBirth, yearOfBirth, siteIdentifier (multicentric?))

        params = SimpleXMLElement("""<?xml version="1.0" encoding="UTF-8"?>
            <createRequest>
            <v1:studySubject xmlns:v1="http://openclinica.org/ws/studySubject/v1">
            <bean:label xmlns:bean="http://openclinica.org/ws/beans">""" +
                                  studySubject.label + """</bean:label>
            <bean:enrollmentDate xmlns:bean="http://openclinica.org/ws/beans">
            """ + studySubject.enrollmentDate.isoformat() + """
            </bean:enrollmentDate>
            <bean:subject xmlns:bean="http://openclinica.org/ws/beans">
            <bean:uniqueIdentifier>""" +
                                  studySubject.subject.uniqueIdentifier +
                                  """</bean:uniqueIdentifier>
            <bean:gender>""" + studySubject.subject.gender + """</bean:gender>
            </bean:subject>
            <bean:studyRef xmlns:bean="http://openclinica.org/ws/beans">
            <bean:identifier>""" + study.identifier + """</bean:identifier>
            </bean:studyRef>
            </v1:studySubject>
            </createRequest>""")

        response = self.client.call('createRequest', params)

        result = str(response.result)
        return result
Пример #30
0
def form_as_XML(request):
    #import pdb; pdb.set_trace()

    os.system(
        'sh /Users/user/NIH_caDSR_SOAP/NIH_caDSR_SOAP/caDSR_SOAP_agent/run.sh')

    formID = 0  #request.RetrieveFormRequest.workflow.formID
    valid_forms = forms.keys()

    if formID in valid_forms:
        form_xml = forms[formID]
        return SimpleXMLElement(form_xml)
    else:
        return SimpleXMLElement(
            '<?xml version="1.0"?><error>There was an error \
                                     delivering your request</error>')
Пример #31
0
 def test_get_normal_xml(self):
     response = SimpleXMLElement(self.get_data('normal_xml'))
     output = client.get_operation('startRegistration')['output']
     resp = response('Body', ns=ns).children().unmarshall(output,
                                                          strict=True)
     self.assertEqual(
         resp['startRegistrationResponse']['agentIdentity']['type'], 'BTS')
Пример #32
0
    def update(self, _id, name=None, email=None, fields=None,
               principal=None, principalType=None):
        """Update an existing member"""
        params = {u'id': _id}
        if name:
            params[u'name'] = name
        if email:
            params[u'email'] = email
        # use the custom fields code below - can't marshall easily
#        if fields:
#            params[u'fields'] = fields
        if principal:
            params[u'principal'] = principal
        if principalType:
            params[u'principalType'] = principalType

        xml_params = SimpleXMLElement('<dummyroot><params/></dummyroot>')
        for name, value in params.items():
            xml_params.params.marshall(name, value)

        if fields:
            for customField in fields:
                xml_params.params.marshall('fields', customField)

        client = self.get_client()
        client.get_operation('updateMember')
        client.call('updateMember', xml_params)
Пример #33
0
    def schedule(self, study, site, studySubject, event):
        """Shedule study event for specified study subject
        """
        result = ""

        params = SimpleXMLElement(
            """<?xml version="1.0" encoding="UTF-8"?>
            <scheduleRequest>
            <v1:event xmlns:v1="http://openclinica.org/ws/event/v1">
            <bean:studySubjectRef xmlns:bean="http://openclinica.org/ws/beans">
            <bean:label>""" + studySubject.label() + """</bean:label>
            </bean:studySubjectRef>
            <bean:studyRef xmlns:bean="http://openclinica.org/ws/beans">
            <bean:identifier>""" + study.identifier() + """</bean:identifier>
            <bean:siteRef>
            <bean:identifier>""" + site.identifier + """</bean:identifier>
            </bean:siteRef>
            </bean:studyRef>
            <bean:eventDefinitionOID xmlns:bean="http://openclinica.org/ws/beans">"""
            + event.oid() + """</bean:eventDefinitionOID>
            <bean:location xmlns:bean="http://openclinica.org/ws/beans">""" +
            site.name + """</bean:location>
            <bean:startDate xmlns:bean="http://openclinica.org/ws/beans">""" +
            datetime.strftime(datetime.now(), "%Y-%m-%d") +
            """</bean:startDate>
            </v1:event>
            </scheduleRequest>""")

        response = self.client.call('scheduleRequest', params)

        # Result of WS call
        result = str(response.result)
        return result
Пример #34
0
    def updateGroup(self, _id, _groupId, _comments):
        """
        <xs:complexType name="updateMemberGroup">
            <xs:sequence>
                <xs:element minOccurs="0" name="params"
                type="tns:updateMemberGroupParameters"/>
            </xs:sequence>
        </xs:complexType>
            <xs:complexType name="updateMemberGroupParameters">
            <xs:sequence>
                <xs:element minOccurs="0" name="id" type="xs:long"/>
                <xs:element minOccurs="0" name="groupId" type="xs:long"/>
                <xs:element minOccurs="0" name="comments" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>

        Update an existing members group
        """

        params = {u'id': _id, u'groupId': _groupId, u'comments': _comments}

        xml_params = SimpleXMLElement('<dummyroot><params/></dummyroot>')
        for name, value in params.items():
            xml_params.params.marshall(name, value)

#        if fields:
#            for customField in fields:
#                xml_params.params.marshall('fields', customField)
#
        client = self.get_client()
        operation = client.get_operation('updateMemberGroup')
#
        soap_uri = soap_namespaces['soap']
        soap_response = client.call('updateMemberGroup', xml_params)
Пример #35
0
    def listManagedGroups(self):
        """Lists the groups managed by the current web service client."""
        # response = self.client.listManagedGroups()
        # Manual call, woraround no-param/empty senquence type
        client = self.get_client()
        operation = client.get_operation('listManagedGroups')
        output = operation['output']
        soap_uri = soap_namespaces['soap']

        soap_request = textwrap.dedent("""
        <soapenv:Envelope
                xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:mem="http://members.webservices.cyclos.strohalm.nl/">
           <soapenv:Header/>
           <soapenv:Body>
              <mem:listManagedGroups/>
           </soapenv:Body>
        </soapenv:Envelope>""")

        soap_response = client.send('listManagedGroups', soap_request)
        # Now mimic the 'wsdl'-based output conversion
        response_xml = SimpleXMLElement(soap_response)
        response_dict = response_xml(
            'Body', ns=soap_uri).children().unmarshall(output)
        response = response_dict and response_dict.values()[0]
        # pass Response tag children
        _log_response(response)
        return [MemberGroup(**response_item['return'])
                for response_item in response]
Пример #36
0
def _autenticar(request,
                crt,
                key,
                service="wsfe",
                ttl=60 * 60 * 10,
                cuit=None):
    "Obtener el TA"

    from pyafipws import wsaa

    CUIT = cuit
    CERTIFICATE = crt
    PRIVATE_KEY = key

    empresa = empresa_actual(request)
    H**O = empresa.homologacion

    if H**O:
        WSDL = "https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL"
        WSAA_URL = "https://wsaahomo.afip.gov.ar/ws/services/LoginCms"
    else:
        WSDL = "https://servicios1.afip.gov.ar/wsfev1/service.asmx?WSDL"
        WSAA_URL = "https://wsaa.afip.gov.ar/ws/services/LoginCms"

    if service not in ("wsfe", "wsfev1", "wsmtxca", "wsfex", "wsbfe"):
        raise HTTP(500, "Servicio %s incorrecto" % service)

    # verifico archivo temporal con el ticket de acceso
    TA = os.path.join(CERTIFICADOS_PATH, "TA-%s-%s.xml" % (cuit, service))
    ttl = 60 * 60 * 5
    if not os.path.exists(TA) or os.path.getmtime(TA) + (ttl) < time.time():
        # solicito una nueva autenticación
        # wsaa = pyafipws.wsaa
        cert = os.path.join(CERTIFICADOS_PATH, CERTIFICATE)
        privatekey = os.path.join(CERTIFICADOS_PATH, PRIVATE_KEY)
        # creo un ticket de requerimiento de acceso
        # cambiando a wsfe si es wsfe(v_)
        if "wsfev" in service: service = "wsfe"
        tra = wsaa.create_tra(service=service, ttl=ttl)

        # firmo el ticket de requerimiento de acceso
        cms = wsaa.sign_tra(str(tra), str(cert), str(privatekey))

        # llamo al webservice para obtener el ticket de acceso
        ta_string = wsaa.call_wsaa(cms, WSAA_URL, trace=False)
        # guardo el ticket de acceso obtenido:
        open(TA, "w").write(ta_string)

    # procesar el ticket de acceso y extraer TOKEN y SIGN:
    # from gluon.contrib.pysimplesoap.simplexml import SimpleXMLElement

    # agregar librería modificada para aceptar etiquetas vacías
    from pysimplesoap.simplexml import SimpleXMLElement

    ta_string = open(TA).read()
    ta = SimpleXMLElement(ta_string)
    token = str(ta.credentials.token)
    sign = str(ta.credentials.sign)
    return token, sign
Пример #37
0
    def listAll(self):
        """Get hierarchical list of studies together with their study sites
        """
        result = ""
        studies = []

        params = SimpleXMLElement("""<?xml version="1.0" encoding="UTF-8"?>
            <listAllRequest />""")
        response = self.client.call('listAllRequest', params)

        documentTree = ET.ElementTree((ET.fromstring(str(response.as_xml()))))

        # Locate Study data in XML file via XPath
        for study in documentTree.iterfind('.//study:study',
                                           namespaces=nsmaps):
            identifier = ""
            oid = ""
            name = ""
            sites = []
            for element in study:
                print element.tag
                if (str(element.tag)).strip(
                ) == "{http://openclinica.org/ws/study/v1}identifier":
                    identifier = element.text
                elif (str(element.tag)
                      ).strip() == "{http://openclinica.org/ws/study/v1}oid":
                    oid = element.text
                elif (str(element.tag)
                      ).strip() == "{http://openclinica.org/ws/study/v1}name":
                    name = element.text

                if (str(element.tag)
                    ).strip() == "{http://openclinica.org/ws/study/v1}sites":
                    for site in element:
                        siteid = ""
                        siteoid = ""
                        sitename = ""
                        for siteelement in site:
                            if (str(siteelement.tag)).strip(
                            ) == "{http://openclinica.org/ws/study/v1}identifier":
                                siteid = siteelement.text
                            elif (str(siteelement.tag)).strip(
                            ) == "{http://openclinica.org/ws/study/v1}oid":
                                siteoid = siteelement.text
                            elif (str(siteelement.tag)).strip(
                            ) == "{http://openclinica.org/ws/study/v1}name":
                                sitename = siteelement.text

                        obtainedSite = StudySite(siteid, siteoid, sitename)
                        sites.append(obtainedSite)

            obtainedStudy = Study(identifier, oid, name)
            obtainedStudy.sites = sites
            studies.append(obtainedStudy)

        # Result of WS call
        result = str(response.result)
        return result, studies
Пример #38
0
def test_status_batches_large_bug_counts(mock_build_client):
    """get_status should perform requests in batches to reduce server load."""
    mock_build_client.return_value = mock_client = mock.Mock()
    mock_client.call.return_value = SimpleXMLElement(
        '<a><s-gensym3/></a>')
    nr = bts.BATCH_SIZE + 10.0
    calls = int(math.ceil(nr / bts.BATCH_SIZE))
    bts.get_status([722226] * int(nr))
    assert mock_client.call.call_count == calls
Пример #39
0
def desserializar(xml):
    "Analiza un XML y devuelve un diccionario"
    xml = SimpleXMLElement(xml)

    dic = xml.unmarshall(XML_FORMAT, strict=True)

    regs = []

    for dic_comprobante in dic["comprobantes"]:
        reg = {
            "detalles": [],
            "ivas": [],
            "tributos": [],
            "permisos": [],
            "cbtes_asoc": [],
            "opcionales": [],
        }
        comp = dic_comprobante["comprobante"]
        mapear(reg, comp, MAP_ENC)
        reg["forma_pago"] = "".join(
            [d["formapago"]["descripcion"] for d in comp["formaspago"]])

        for detalles in comp["detalles"]:
            det = detalles["detalle"]
            reg["detalles"].append(mapear({}, det, MAP_DET))

        for ivas in comp["ivas"]:
            iva = ivas["iva"]
            reg["ivas"].append(mapear({}, iva, MAP_IVA))

        for tributos in comp.get("tributos", []):
            tributo = tributos["tributo"]
            reg["tributos"].append(mapear({}, tributo, MAP_TRIB))

        for cbte_asocs in comp.get("cmpasociados", []):
            cbte_asoc = cbte_asocs["cmpasociado"]
            reg["cbtes_asoc"].append(mapear({}, cbte_asoc, MAP_CBTE_ASOC))

        for opcionales in comp.get("opcionales", []):
            opcional = opcionales["opcional"]
            reg["opcionales"].append(mapear({}, opcional, MAP_OPCIONAL))

        regs.append(reg)
    return regs
Пример #40
0
 def call(self, method, *args, **kwargs):
     "Prepara el xml y realiza la llamada SOAP, devuelve un SimpleXMLElement"
     # Mensaje de Solicitud SOAP básico:
     xml = self.__xml % dict(method=method, namespace=self.namespace, ns=self.__ns,
                             soap_ns=self.__soap_ns, soap_uri=soap_namespaces[self.__soap_ns])
     request = SimpleXMLElement(xml,namespace=self.__ns and self.namespace, prefix=self.__ns)
     # parsear argumentos
     if kwargs:
         parameters = kwargs.items()
     else:
         parameters = args
     for k,v in parameters: # dict: tag=valor
         self.parse(getattr(request,method),k,v)
     self.xml_request = request.as_xml()
     self.xml_response = self.send(method, self.xml_request)
     response = SimpleXMLElement(self.xml_response, namespace=self.namespace)
     if self.exceptions and ("soapenv:Fault" in response or "soap:Fault" in response):
         raise SoapFault(unicode(response.faultcode), unicode(response.faultstring))
     return response
    def test_adv_unmarshall(self):
        xml = """
        <activations>
            <items>
                <number>01234</number>
                <status>1</status>
                <properties>
                    <name>foo</name>
                    <value>3</value>
                </properties>
                <properties>
                    <name>bar</name>
                    <value>4</value>
                </properties>
            </items>
            <items>
                <number>04321</number>
                <status>0</status>
            </items>
        </activations>
        """
        span = SimpleXMLElement(xml)
        d = {'activations': [
                {'items': {
                    'number': str,
                    'status': int,
                    'properties': ({
                        'name': str,
                        'value': int
                    }, )
                }}
            ]}

        e = {'activations': [
                {'items': {'number': '01234', 'status': 1, 'properties': ({'name': 'foo', 'value': 3}, {'name': 'bar', 'value': 4})}},
                {'items': {'number': '04321', 'status': 0}}
            ]}
        self.eq(span.unmarshall(d), e)
Пример #42
0
def makeNRPSrequest(seqs):
    root = SimpleXMLElement("<predict></predict>",prefix="ws",namespace="http://ws.NRPSpredictor2.roettig.org/")
    root.add_child("request",ns=True)
    print root.as_xml(pretty=True)
    arg0_node = root.children()[0]
    

    idx = 1
    for seq in seqs:
        seqs_node = arg0_node.add_child("sequence",ns=True)
        seqs_node.add_child("id","%d"%idx,ns=True)
        seqs_node.add_child("kingdom","0",ns=True)
        seqs_node.add_child("seqString",seq,ns=True)
        seqs_node.add_child("sequenceType","0",ns=True)
        idx+=1
    print root.as_xml(pretty=True)    
    return root
    def test_tuple_unmarshall(self):
        xml = """
        <foo>
            <boo>
                <bar>abc</bar>
                <baz>1</baz>
            </boo>
            <boo>
                <bar>qwe</bar>
                <baz>2</baz>
            </boo>
        </foo>
        """
        span = SimpleXMLElement(xml)
        d = {'foo': {
                'boo': ({'bar': str, 'baz': int}, )
        }}

        e = {'foo': {
                'boo': (
                {'bar': 'abc', 'baz': 1},
                {'bar': 'qwe', 'baz': 2},
            )}}
        self.eq(span.unmarshall(d), e)
    def test_unmarshall(self):
        span = SimpleXMLElement('<span><name>foo</name><value>3</value></span>')
        d = {'span': {'name': str, 'value': int}}
        e = {'span': {'name': 'foo', 'value': 3}}
        self.eq(span.unmarshall(d), e)

        span = SimpleXMLElement('<span><name>foo</name><name>bar</name></span>')
        d = {'span': [{'name': str}]}
        e = {'span': [{'name': 'foo'}, {'name': 'bar'}]}
        self.eq(span.unmarshall(d), e)

        span = SimpleXMLElement('<activations><items><number>01234</number><status>1</status></items><items><number>04321</number><status>0</status></items></activations>')
        d = {'activations': [
                {'items': {
                    'number': str,
                    'status': int
                }}
            ]}

        e = {'activations': [{'items': {'number': '01234', 'status': 1}}, {'items': {'number': '04321', 'status': 0}}]}
        self.eq(span.unmarshall(d), e)
Пример #45
0
 def test_unmarshall_cdata(self):
     span = SimpleXMLElement('<span><name><![CDATA[foo<name/>]]></name><value>3</value></span>')
     d = {'span': {'name': str, 'value': int}}
     e = {'span': {'name': 'foo<name/>', 'value': 3}}
     self.eq(span.unmarshall(d), e)
    def test_basic(self):
        span = SimpleXMLElement('<span><a href="python.org.ar">pyar</a><prueba><i>1</i><float>1.5</float></prueba></span>')
        span1 = SimpleXMLElement('<span><a href="google.com">google</a><a>yahoo</a><a>hotmail</a></span>')
        self.eq([str(a) for a in span1.a()], ['google', 'yahoo', 'hotmail'])

        span1.add_child('a', 'altavista')
        span1.b = "ex msn"
        d = {'href': 'http://www.bing.com/', 'alt': 'Bing'}
        span1.b[:] = d
        self.eq(sorted([(k, v) for k, v in span1.b[:]]), sorted(d.items()))

        xml = '<?xml version="1.0" encoding="UTF-8"?><span><a href="google.com">google</a><a>yahoo</a><a>hotmail</a><a>altavista</a><b alt="Bing" href="http://www.bing.com/">ex msn</b></span>'
        self.eq(span1.as_xml(), xml)
        self.assertTrue('b' in span1)

        span.import_node(span1)
        xml = '<?xml version="1.0" encoding="UTF-8"?><span><a href="python.org.ar">pyar</a><prueba><i>1</i><float>1.5</float></prueba><span><a href="google.com">google</a><a>yahoo</a><a>hotmail</a><a>altavista</a><b alt="Bing" href="http://www.bing.com/">ex msn</b></span></span>'
        self.eq(span.as_xml(), xml)

        types = {'when': datetime.datetime}
        when = datetime.datetime.now()
        dt = SimpleXMLElement('<when>%s</when>' % when.isoformat())
        self.eq(dt.unmarshall(types)['when'], when)