从pythons上的数据输入处理xml的简单方法

2024-10-02 06:36:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始了一个项目,该项目应该使用pythonicsimpleweb服务器(我只需要一个“config”页面)从用户那里获取数据(超过150个字段),然后将所有这些数据(字段+数据)转换为xml文件并将其发送到另一个python模块。所以问题是-有什么简单的方法来处理这个问题? 我找到了cherryPy(作为web服务器)和Genshi(作为xml解析器),但是对于我来说,如何组合这两者(正如我所理解的那样,Genshi提供用于发布的模板(甚至是xml),但是如何获取(转换)xml中的数据对我来说并不明显。我的redcherrypy和Genshi教程,但这和我真正需要的有点不同,而且我现在对python(尤其是web)不是很在行,无法找到正确的方向。 如果你能给我展示任何类似的例子来理解这个概念,那就太好了!在

对不起我的英语!在

提前谢谢。在


Tags: 模块文件数据项目方法用户服务器web
1条回答
网友
1楼 · 发布于 2024-10-02 06:36:08

Python提供了方便的xml.etree,并且不需要额外的依赖项来输出简单的XML。下面是一个例子。在

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import xml.etree.cElementTree as etree

import cherrypy


config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}


class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <body>
        <form action="/getxml" method="post">
          <input type="text" name="key1" placeholder="Key 1" /><br/>
          <input type="text" name="key2" placeholder="Key 2" /><br/>
          <input type="text" name="key3" placeholder="Key 3" /><br/>
          <select name="key4">
            <option value="1">Value 1</option>
            <option value="2">Value 2</option>
            <option value="3">Value 3</option>
            <option value="4">Value 4</option>
          </select><br/>
          <button type="submit">Get XML</button>
        </form>
      </body>
      </html>
    '''

  @cherrypy.expose
  def getxml(self, **kwargs):
    root = etree.Element('form')
    for k, v in kwargs.items():
      etree.SubElement(root, k).text = v

    cherrypy.response.headers['content-type'] = 'text/xml'
    return etree.tostring(root, encoding = 'utf-8')


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

相关问题 更多 >

    热门问题