Jazz.Min
Jazz.Min

Reputation: 55

Simple way to process xml from data input on python server

Ive just started the project that should use the pythonic simple web-server(I need only one "config" page) for getting data from user in a really multiply fields (over 150) and then convert all these data (field+data) into xml file and send it to another python module. So the question is - what the simple way to deal with this? I found cherryPy(as webserver) and Genshi(as xml parser) but it is not even light obvious for me how to combine this(as I understood Genshi providing template (even xml) for Publishing, but how to get(convert) data in xml). Ive red cherryPy and Genshi tutorial but it is a little different of what I really need to, and I`m not so strong in python(and especially web) right now to get the right direction. If you can show me any example of smthing like that for understanding the concept it would be great!

Sorry for my english!

Thanks in advance.

Upvotes: 1

Views: 247

Answers (1)

saaj
saaj

Reputation: 25174

Python comes with convenient xml.etree and you don't need extra dependencies to output simple XML. Here's the example.

#!/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)

Upvotes: 0

Related Questions