当前位置: 首页>>代码示例>>Python>>正文


Python builder.ElementMaker方法代码示例

本文整理汇总了Python中lxml.builder.ElementMaker方法的典型用法代码示例。如果您正苦于以下问题:Python builder.ElementMaker方法的具体用法?Python builder.ElementMaker怎么用?Python builder.ElementMaker使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lxml.builder的用法示例。


在下文中一共展示了builder.ElementMaker方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def __init__(self, configuration):
        self.context = {}

        self.connectors = {}
        self.connectors['XML'] = connector.XMLAPIConnector(configuration)
        self.connectors['SSH'] = connector.SSHConnector(configuration)

        elt_maker = builder.ElementMaker(nsmap={None: constants.XML_NAMESPACE})
        xml_parser = parser.XMLAPIParser()

        obj_types = StorageObject.__subclasses__()  # pylint: disable=no-member
        for item in obj_types:
            key = item.__name__
            self.context[key] = eval(key)(self.connectors,
                                          elt_maker,
                                          xml_parser,
                                          self) 
开发者ID:openstack,项目名称:manila,代码行数:19,代码来源:object_manager.py

示例2: __init__

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def __init__(self, configuration):
        self.context = dict()

        self.connectors = dict()
        self.connectors['XML'] = connector.XMLAPIConnector(configuration)
        self.connectors['SSH'] = connector.SSHConnector(configuration)

        elt_maker = builder.ElementMaker(nsmap={None: constants.XML_NAMESPACE})
        xml_parser = parser.XMLAPIParser()

        obj_types = StorageObject.__subclasses__()  # pylint: disable=no-member
        for item in obj_types:
            key = item.__name__
            self.context[key] = eval(key)(self.connectors,
                                          elt_maker,
                                          xml_parser,
                                          self) 
开发者ID:openstack,项目名称:manila,代码行数:19,代码来源:object_manager.py

示例3: test_xml_api_retry

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def test_xml_api_retry(self):
        hook = utils.RequestSideEffect()
        hook.append(self.base.resp_need_retry())
        hook.append(self.base.resp_task_succeed())
        elt_maker = builder.ElementMaker(nsmap={None: constants.XML_NAMESPACE})
        xml_parser = parser.XMLAPIParser()
        storage_object = manager.StorageObject(self.manager.connectors,
                                               elt_maker, xml_parser,
                                               self.manager)
        storage_object.conn['XML'].request = utils.EMCMock(side_effect=hook)
        fake_req = storage_object._build_task_package(
            elt_maker.StartFake(name='foo')
        )
        resp = storage_object._send_request(fake_req)
        self.assertEqual('ok', resp['maxSeverity'])

        expected_calls = [
            mock.call(self.base.req_fake_start_task()),
            mock.call(self.base.req_fake_start_task())
        ]
        storage_object.conn['XML'].request.assert_has_calls(expected_calls) 
开发者ID:openstack,项目名称:manila,代码行数:23,代码来源:test_object_manager.py

示例4: test_xml_api_retry

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def test_xml_api_retry(self):
        hook = utils.RequestSideEffect()
        hook.append(self.base.resp_need_retry())
        hook.append(self.base.resp_task_succeed())
        elt_maker = builder.ElementMaker(nsmap={None: constants.XML_NAMESPACE})
        xml_parser = parser.XMLAPIParser()
        storage_object = manager.StorageObject(self.manager.connectors,
                                               elt_maker, xml_parser,
                                               self.manager)
        storage_object.conn['XML'].request = utils.EMCMock(side_effect=hook)
        fake_req = storage_object._build_task_package(
            elt_maker.StartFake(name='foo')
        )
        self.mock_object(time, 'sleep')
        resp = storage_object._send_request(fake_req)
        self.assertEqual('ok', resp['maxSeverity'])

        expected_calls = [
            mock.call(self.base.req_fake_start_task()),
            mock.call(self.base.req_fake_start_task())
        ]
        storage_object.conn['XML'].request.assert_has_calls(expected_calls) 
开发者ID:openstack,项目名称:manila,代码行数:24,代码来源:test_object_manager.py

示例5: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E

        self.plot(filedir=self.report_dir, file_format='jpg')

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("ABINIT Ion Relaxation")),
                                  E.body(E.h1("ABINIT Ion Relaxation"),
                                         E.h2('Initial Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Forces Minimization'),
                                         E.p(E.img(src='forces.jpg', width="800", height="600", alt="Forces")),
                                         E.h2('Stress Minimization'),
                                         E.p(E.img(src='stress.jpg', width="800", height="600", alt="Stress"))
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:19,代码来源:relax.py

示例6: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E

        self.plot(filedir=self.report_dir, file_format='jpg')

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("VASP Ion Relaxation")),
                                  E.body(E.h1("VASP Ion Relaxation"),
                                         E.h2('Initial Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Forces Minimization'),
                                         E.p(E.img(src='forces.jpg', width="800", height="600", alt="Forces")),
                                         E.h2('Stress Minimization'),
                                         E.p(E.img(src='stress.jpg', width="800", height="600", alt="Stress"))
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:19,代码来源:relax2.py

示例7: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E

        if not os.path.isdir(self.report_dir):
            os.mkdir(self.report_dir)

        self.plot(filedir=self.report_dir, file_format='jpg')

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("VASP K-point grid Convergence")),
                                  E.body(E.h1("VASP K-point grid Convergence"),
                                         E.h2('Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Convergence'),
                                         E.p(E.img(src='convergence.jpg', width="800", height="600", alt="Forces")),
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:20,代码来源:convergence.py

示例8: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E
        self.plot(figname=self.report_dir + os.sep + 'static.jpg')

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("ABINIT Static Calculation")),
                                  E.body(E.h1("ABINIT Static Calculation"),
                                         E.h2('Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Self Consistent Field Convergence'),
                                         E.p(E.img(src='static.jpg', width="800", height="600",
                                                   alt="Static Calculation"))
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:17,代码来源:static.py

示例9: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E
        self.plot(figname=self.report_dir + os.sep + 'static.jpg')

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("VASP Static Calculation")),
                                  E.body(E.h1("VASP Static Calculation"),
                                         E.h2('Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Self Consistent Field Convergence'),
                                         E.p(E.img(src='static.jpg', width="800", height="600",
                                                   alt="Static Calculation"))
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:17,代码来源:static.py

示例10: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E
        self.plot(filedir=self.report_dir, file_format='jpg')

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("VASP Ideal Strength")),
                                  E.body(E.h1("VASP Ideal Strength"),
                                         E.h2('Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Ideal Strength'),
                                         E.p(E.img(src='strenth.jpg', width="800", height="600", alt="Strength")),
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:16,代码来源:stregth.py

示例11: __init__

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def __init__(self, out_path=None, output=None, out_pyramid=None):
        # see if lxml is installed before checking all output tiles
        from lxml.builder import ElementMaker
        self.path = out_path
        self._tp = out_pyramid
        self._output = output
        self._bucket = self.path.split("/")[2] if self.path.startswith("s3://") else None
        self.bucket_resource = get_boto3_bucket(self._bucket) if self._bucket else None
        logger.debug("initialize VRT writer for %s", self.path)
        if path_exists(self.path):
            if self._bucket:
                key = "/".join(self.path.split("/")[3:])
                for obj in self.bucket_resource.objects.filter(Prefix=key):
                    if obj.key == key:
                        self._existing = {
                            k: v for k, v in self._xml_to_entries(
                                obj.get()['Body'].read().decode()
                            )
                        }
            else:
                with open(self.path) as src:
                    self._existing = {k: v for k, v in self._xml_to_entries(src.read())}
        else:
            self._existing = {}
        logger.debug("%s existing entries", len(self._existing))
        self.new_entries = 0
        self._new = {} 
开发者ID:ungarj,项目名称:mapchete,代码行数:29,代码来源:index.py

示例12: create

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def create(cls, outfile, basevm_hashvalue,
               base_disk, base_memory, disk_hash, memory_hash):
        # Generate manifest XML
        e = ElementMaker(namespace=cls.NS, nsmap={None: cls.NS})
        tree = e.image(
            e.disk(path=os.path.basename(base_disk)),
            e.memory(path=os.path.basename(base_memory)),
            e.disk_hash(path=os.path.basename(disk_hash)),
            e.memory_hash(path=os.path.basename(memory_hash)),
            hash_value=str(basevm_hashvalue),
        )
        cls.schema.assertValid(tree)
        xml = etree.tostring(tree, encoding='UTF-8', pretty_print=True,
                             xml_declaration=True)
        zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED, True)
        zip.comment = 'Cloudlet package for base VM'
        zip.writestr(cls.MANIFEST_FILENAME, xml)
        zip.close()

        # zip library bug at python 2.7.3
        # see more at http://bugs.python.org/issue9720

        #filelist = [base_disk, base_memory, disk_hash, memory_hash]
        # for filepath in filelist:
        #    basename = os.path.basename(filepath)
        #    filesize = os.path.getsize(filepath)
        #    LOG.info("Zipping %s (%ld bytes) into %s" % (basename, filesize, outfile))
        #    zip.write(filepath, basename)
        # zip.close()

        cmd = ['zip', '-j', '-9']
        cmd += ["%s" % outfile]
        cmd += [str(base_disk),str(base_memory),str(disk_hash),str(memory_hash)]
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, close_fds=True)
        LOG.info("Start compressing")
        LOG.info("%s" % ' '.join(cmd))
        for line in iter(proc.stdout.readline, ''):
            line = line.replace('\r', '')
            sys.stdout.write(line)
            sys.stdout.flush() 
开发者ID:cmusatyalab,项目名称:elijah-provisioning,代码行数:43,代码来源:package.py

示例13: __init__

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def __init__(self,
                 prefix_namespaces="minimal",
                 netconf_ns=NETCONF_NS_1_0,
                 nsmap=None):
        """Create an RPC builder to help construct RPC XML.

        Args:
          prefix_namespaces (str): "always" to always prefix XML namespaces,
            "minimal" to only prefix when necessary.
          netconf_ns (str): XML namespace to use for building NETCONF elements.
            Defaults to netconf 1.0 namespace, but can be overridden for e.g.
            netconf 1.1 namespace or no namespace at all.
          nsmap (dict): Mapping of prefixes to XML namespaces
        """
        self.netconf_ns = netconf_ns
        if not nsmap:
            nsmap = {}
        else:
            nsmap = nsmap.copy()
        self.nsmap = nsmap
        if prefix_namespaces == "always":
            if netconf_ns:
                self.nsmap['nc'] = netconf_ns
        elif prefix_namespaces == "minimal":
            if netconf_ns:
                self.nsmap[None] = netconf_ns
        else:
            raise ValueError('Unknown prefix_namespaces value "{0}"'
                             .format(prefix_namespaces))

        self.prefix_namespaces = prefix_namespaces

        self.keep_prefixes = set()
        """Namespace prefixes to keep even if 'unused'.

        Primarily used to ensure that namespaced **values** retain
        their prefixes.
        """

        self.netconf_element = ElementMaker(namespace=netconf_ns,
                                            nsmap=self.nsmap)
        """Factory used to create XML elements in the NETCONF namespace."""

        yanglib_pfx = None if prefix_namespaces == 'minimal' else 'yanglib'
        self.yang_element = ElementMaker(namespace=YANG_NS_1,
                                         nsmap={yanglib_pfx: YANG_NS_1})
        """Factory used to create XML elements in the YANG namespace."""

        ncwd_pfx = None if prefix_namespaces == 'minimal' else 'ncwd'
        self.ncwd_element = ElementMaker(namespace=WITH_DEFAULTS_NS,
                                         nsmap={ncwd_pfx: WITH_DEFAULTS_NS})
        """Factory to create XML elements in the with-defaults namespace."""

        self.get_data = ElementMaker(namespace=NMDA_NS,
                                     nsmap={'ds': NMDA_DATASTORE_NS,
                                            'or': NMDA_ORIGIN})
        """Factory to create "get-data" element RFC 8526."""

        self.edit_data = ElementMaker(namespace=NMDA_NS,
                                      nsmap={'ds': NMDA_DATASTORE_NS})
        """Factory to create "edit-data" element RFC 8526.""" 
开发者ID:CiscoTestAutomation,项目名称:genielibs,代码行数:63,代码来源:rpcbuilder.py

示例14: write

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def write(self):
        def number(v):
            return {'number': str(v)}

        E = ElementMaker()

        config = E.settings(
                    E.currentProfile(self.currentProfile) if self.currentProfile else E.currentProfile(),
                    E.currentFormat(self.currentFormat) if self.currentFormat else E.currentFormat(),
                    E.embedFontFamily(self.embedFontFamily) if self.embedFontFamily else E.embedFontFamily(),
                    E.hyphens(self.hyphens) if self.hyphens else E.hyphens(),
                    E.outputFolder(self.outputFolder) if self.outputFolder else E.outputFolder(),
                    E.lastUsedTargetPath(self.lastUsedTargetPath) if self.lastUsedTargetPath else E.lastUsedTargetPath(),
                    E.lastUsedPath(self.lastUsedPath) if self.lastUsedPath else E.lastUsedPath(),
                    E.writeLog(str(self.writeLog)),
                    E.clearLogAfterExit(str(self.clearLogAfterExit)),
                    E.logLevel(self.logLevel) if self.logLevel else E.logLevel(),
                    E.kindlePath(self.kindlePath) if self.kindlePath else E.kindlePath(),
                    E.kindleSyncCovers(str(self.kindleSyncCovers)),
                    E.kindleDocsSubfolder(self.kindleDocsSubfolder) if self.kindleDocsSubfolder else E.kindleDocsSubfolder(),
                    E.GoogleMail(self.GoogleMail) if self.GoogleMail else E.GoogleMail(),
                    E.GooglePassword(self.GooglePassword) if self.GooglePassword else E.GooglePassword(),
                    E.KindleMail(self.KindleMail) if self.KindleMail else E.KindleMail(),
                    E.bookInfoVisible(str(self.bookInfoVisible)),
                    E.bookInfoSplitterState(self.bookInfoSplitterState) if self.bookInfoSplitterState else E.bookInfoSplitterState(),
                    E.authorPattern(self.authorPattern) if self.authorPattern else E.authorPattern(),
                    E.filenamePattern(self.filenamePattern) if self.filenamePattern else E.filenamePattern(),
                    E.renameDestDir(self.renameDestDir) if self.renameDestDir else E.renameDestDir(),
                    E.deleteAfterRename(str(self.deleteAfterRename)),
                    E.columns(
                        *[E.column(str(self.columns[col]), number(col)) for col in self.columns.keys()]
                    ),
                    E.geometry(
                        E.x(str(self.geometry['x'])) if self.geometry['x'] else E.x(),
                        E.y(str(self.geometry['y'])) if self.geometry['y'] else E.y(),
                        E.width(str(self.geometry['width'])) if self.geometry['width'] else E.width(),
                        E.height(str(self.geometry['height'])) if self.geometry['height'] else E.height()
                    )

        )
        config_dir = os.path.dirname(self.config_file)
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)
            
        with codecs.open(self.config_file, "wb") as f:
            f.write(etree.tostring(config, encoding="utf-8", pretty_print=True, xml_declaration=True))
            f.close() 
开发者ID:rupor-github,项目名称:fb2mobi,代码行数:49,代码来源:gui_config.py

示例15: report

# 需要导入模块: from lxml import builder [as 别名]
# 或者: from lxml.builder import ElementMaker [as 别名]
def report(self, file_format='html'):
        from lxml.builder import ElementMaker, E
        self.plot(filedir=self.workdir + os.sep + 'REPORT', file_format='jpg')

        style = """
table {
    width:70%;
}
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;
}
table#t01 tr:nth-child(even) {
    background-color: #eee;
}
table#t01 tr:nth-child(odd) {
   background-color:#fff;
}
table#t01 th	{
    background-color: black;
    color: white;
}
"""
        mech = self.get_mechanical_properties()
        table = []
        for i in mech:
            table.append(E.tr(E.td(i), E.td(mech[i]['units']),
                              E.td('%7.3f' % mech[i]['Voigt']),
                              E.td('%7.3f' % mech[i]['Reuss']),
                              E.td('%7.3f' % (0.5 * (mech[i]['Voigt'] + mech[i]['Reuss'])))))

        element_maker = ElementMaker(namespace=None, nsmap={None: "http://www.w3.org/1999/xhtml"})
        html = element_maker.html(E.head(E.title("VASP Elastic Moduli"), E.style(style)),
                                  E.body(E.h1("VASP Elastic Moduli"),
                                         E.h2('Structure'),
                                         E.pre(str(self.structure)),
                                         E.h2('Elastic Moduli'),
                                         E.p(E.img(src='elastic.jpg', width="900", height="500",
                                                   alt="Static Calculation")),
                                         E.table(E.tr(E.th('Property'), E.th('Units'), E.th('Voigt'), E.th('Reuss'),
                                                      E.th('Average')), E.tr(*tuple(table)), id="t01"), E.br()
                                         ))

        return self.report_end(html, file_format) 
开发者ID:MaterialsDiscovery,项目名称:PyChemia,代码行数:50,代码来源:elastic.py


注:本文中的lxml.builder.ElementMaker方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。