How to use the lxml.objectify.fromstring function in lxml

To help you get started, we’ve selected a few lxml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github VAMDC / NodeSoftware / nodes / wadis / node / tests.py View on Github external
def testSyncSelectSaga2_co(self):
		settings.DEBUG = DEBUG
		sql = "SELECT All WHERE ((Inchi='InChI=1S/CO/c1-2'  AND RadTransWavenumber > 2135.3135 AND RadTransWavenumber < 2135.3137) AND MethodCategory = 'experiment')"
		self.queryDict["QUERY"] = sql
		self.request.REQUEST = self.queryDict

		content = views.sync(self.request).content
		objTree = objectify.fromstring(content)
		removeSelfSource(objTree)
		actual = etree.tostring(objTree, pretty_print=True)
		xsamsXSD.assertValid(objTree)

		expected = etree.tostring(objectify.fromstring(open(settings.BASE_PATH + "/nodes/" + settings.NODENAME + "/test/co.xml").read()), pretty_print=True)
		self.assertEquals(expected, actual)
github odoo / odoo / addons / payment_ogone / models / ogone.py View on Github external
.. versionadded:: pre-v8 saas-3
         .. warning::

            Experimental code. You should not use it before OpenERP v8 official
            release.
        """
        tx = self.browse(cr, uid, id, context=context)

        tx_data = self.ogone_s2s_generate_values(cr, uid, id, values, context=context)
        _logger.info('Generated Ogone s2s data %s', pformat(tx_data))  # debug

        request = urllib2.Request(tx.acquirer_id.ogone_direct_order_url, urlencode(tx_data))
        result = urllib2.urlopen(request).read()
        _logger.info('Contacted Ogone direct order; result %s', result)  # debug

        tree = objectify.fromstring(result)
        payid = tree.get('PAYID')

        query_direct_data = dict(
            PSPID=tx.acquirer_id.ogone_pspid,
            USERID=tx.acquirer_id.ogone_userid,
            PSWD=tx.acquirer_id.ogone_password,
            ID=payid,
        )
        query_direct_url = 'https://secure.ogone.com/ncol/%s/querydirect.asp' % (tx.acquirer_id.env,)

        tries = 2
        tx_done = False
        tx_status = False
        while not tx_done or tries > 0:
            try:
                tree = objectify.fromstring(result)
github Deepwalker / fs2web / conference / views.py View on Github external
def list(request,do="",id="",cnf="",param=""):
    # Data from FreeSWITCH
    r = O.fromstring(fsapi("conference","xml_list"))

    # Commands to FreeSWITCH
    if do=="start":
        conference = Conference.objects.get(id=int(cnf))
        conference.start()
        return HttpResponseRedirect('/confs/')
    if do and id:
        fsapi("conference","%s %s %s"%(cnf,do,id))
        return HttpResponseRedirect('/confs/')

    # Invite participant
    if request.GET:
        form = InviteParticipantForm(request.GET)
        if form.is_valid():
            conf = form.cleaned_data.get('conference')
            phone = form.cleaned_data.get('phone')
github WGBH / django-multilingualfield / multilingualfield / widgets.py View on Github external
"""
        text_dict = {}
        if value:
            # Both MultiLingualCharField and MultiLingualTextField instances
            # provide `MultiLingualText` instances by default but handling
            # for raw XML has been included for convenience.
            if isinstance(value, datastructures.MultiLingualText):
                text_dict = dict(
                    (code, getattr(value, code))
                    for code, verbose in LANGUAGES
                )
            else:
                # Converting XML (passed-in as `value`) to a python object
                # via lxml
                try:
                    xml_as_python_object = objectify.fromstring(value)
                except XMLSyntaxError:
                    raise Exception(
                        '%s MultiLingualTextFieldWidget.decompress()!' %
                        INVALID_XML_ERROR
                    )
                else:
                    # Creating a dictionary of all the languages passed in the
                    # value XML with the language code (i.e. 'en', 'de', 'fr')
                    # as the key
                    text_dict = dict(
                        (unicode(l.code), unicode(l.language_text or u''))
                        for l in xml_as_python_object.language
                    )
        # Returning text from XML tree in order dictated by LANGUAGES
        return [text_dict.get(code, u'') for code, verbose in LANGUAGES]
github deontologician / restnavigator / scripts / generate_registry.py View on Github external
def emit_iana_rels(rels_url):
    '''Fetches the IANA link relation registry'''
    text = requests.get(rels_url).text.encode('ascii', 'ignore')
    xml = objectify.fromstring(text)
    iana_rels = {str(rec.value): str(rec.description)
                 for rec in xml.registry.record}
    keys = sorted(iana_rels)
    print('# IANA link relation registry last updated on:', xml.updated)
    print('# Obtained from', rels_url)
    print()
    print('iana_rels = {')
    for key in keys:
        print('    {0!r}: ('.format(key))
        desc_list = list(linewrap(iana_rels[key], width=68))
        for i, line in enumerate(desc_list):
            line_ = line.replace('"', '\\"')  # escape double quotes
            if i < len(desc_list) - 1:
                print('        "{0} "'.format(line_))
            else:
                print('        "{0}"'.format(line_))
github isrish / GPUWebDashboard / gpustate.py View on Github external
def getgpustate():
    x = nvidia_smi.XmlDeviceQuery()
    tree = objectify.fromstring(x)
    #print(etree.tostring(tree, pretty_print=True))
    return tree
github rdmorganiser / rdmo / apps / core / utils.py View on Github external
def import_xml(xml_string):
    xml_root = objectify.fromstring(xml_string)

    if xml_root.tag == 'conditions':
        import_conditions(xml_root)

    elif xml_root.tag == 'options':
        import_options(xml_root)

    elif xml_root.tag == 'domain':
        import_domain(xml_root)

    elif xml_root.tag == 'catalogs':
        import_questions(xml_root)

    else:
        raise Exception('This is not a proper RDMO XML Export.')
github flectra-hq / flectra / addons / payment_ogone / models / payment.py View on Github external
data = {
            'PAYID': self.acquirer_reference,
            'PSPID': account.ogone_pspid,
            'USERID': account.ogone_userid,
            'PSWD': account.ogone_password,
        }

        query_direct_url = 'https://secure.ogone.com/ncol/%s/querydirect.asp' % (self.acquirer_id.environment)

        _logger.debug("Ogone data %s", pformat(data))
        result = requests.post(query_direct_url, data=data).content
        _logger.debug('Ogone response = %s', result)

        try:
            tree = objectify.fromstring(result)
        except etree.XMLSyntaxError:
            # invalid response from ogone
            _logger.exception('Invalid xml response from ogone')
            raise

        return tree
github timstaley / voevent-parse / src / voeventparse / voevent.py View on Github external
stream='voevent.soton.ac.uk/super_exciting_events'
                stream_id=77

        stream_id (str): See above.

        role (str): role as defined in VOEvent spec.
            (See also  :py:class:`.definitions.roles`)

    Returns:
        Root-node of the VOEvent, as represented by an lxml.objectify element
        tree ('etree'). See also
        http://lxml.de/objectify.html#the-lxml-objectify-api
    """
    parser = objectify.makeparser(remove_blank_text=True)
    v = objectify.fromstring(voeventparse.definitions.v2_0_skeleton_str,
                             parser=parser)
    _remove_root_tag_prefix(v)
    if not isinstance(stream_id, string_types):
        stream_id = repr(stream_id)
    v.attrib['ivorn'] = ''.join(('ivo://', stream, '#', stream_id))
    v.attrib['role'] = role
    # Presumably we'll always want the following children:
    # (NB, valid to then leave them empty)
    etree.SubElement(v, 'Who')
    etree.SubElement(v, 'What')
    etree.SubElement(v, 'WhereWhen')
    v.Who.Description = (
        'VOEvent created with voevent-parse, version {}. '
        'See https://github.com/timstaley/voevent-parse for details.').format(
        __version__
    )
github kimchi-project / kimchi / model / vmhostdevs.py View on Github external
def lookup(self, vmid, dev_name):
        dom = VMModel.get_vm(vmid, self.conn)
        xmlstr = dom.XMLDesc(0)
        root = objectify.fromstring(xmlstr)
        try:
            hostdev = root.devices.hostdev
        except AttributeError:
            raise NotFoundError('KCHVMHDEV0001E', {
                                'vmid': vmid, 'dev_name': dev_name})

        for e in hostdev:
            deduced_name = DeviceModel.deduce_dev_name(e, self.conn)
            if deduced_name == dev_name:
                dev_info = self.dev_model.lookup(dev_name)
                return {
                    'name': dev_name,
                    'type': e.attrib['type'],
                    'product': dev_info.get('product', None),
                    'vendor': dev_info.get('vendor', None),
                    'multifunction': dev_info.get('multifunction', None),