Esempio n. 1
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)
Esempio n. 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()
Esempio n. 3
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
    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'))
Esempio n. 5
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 []]
 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:')
 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)
Esempio n. 8
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
Esempio n. 9
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)
Esempio n. 10
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)
Esempio n. 12
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)
    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)
 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)