Python-Ref > Dynamic web pages in Python > Form example
 
 

<-^^->
Moduly
Knihovní funkce

Form example

Simple but useful example of form processing.
The following example shows a simple online service that lets you use xmllint on a file.
Because a file is uploaded to the script, the result rendered on this page does not show the actual function. This example is intended to be downloaded and tried manually.
Expand/Shrink
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-Type" content="text/html; charset=utf-8" />
    <title>xmllint upload form</title>
  </head>
  <body>
    <form action="dpages6-1.py" method="post" enctype="multipart/form-data">
      <div>File upload: <input type="file" name="uploaded_file" /></div>
      <div><input type="checkbox" name="include_xml" checked="checked"/>Include XML content in output</div>
      <div><input type="submit" value="Upload" /></div>
    </form>
  </body>
</html>
Zdroj: (dpages6-1.py)
  1   page_template = '''
  2   <html>
  3   <head>
  4   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5   <title>%s</title>
  6   </head>
  7   <body>
  8   %s
  9   </body>
 10   </html>'''
 11   
 12   import popen2
 13   from xml.sax.saxutils import escape
 14   
 15   def index( req, uploaded_file=None, include_xml="off"):
 16     if uploaded_file:
 17       # we create a temporary file, it is not safe to do it this way,
 18       # but for sake of simplicity we will do it anyway
 19       f = file( "/tmp/temp.xml", "w")
 20       f.write( uploaded_file.value)
 21       f.close()
 22       # run xmllint on the output
 23       p = popen2.Popen3( "xmllint /tmp/temp.xml", True)
 24       out, inp, err = p.fromchild, p.tochild, p.childerr
 25       inp.close()
 26       output = out.read()
 27       error = err.read()
 28       # now we create the body of the HTML page
 29       if error == "":
 30         error = "No errors."
 31       body = "<h1>Errors</h1><pre>%s</pre>" % escape( error)
 32       if include_xml == "on":
 33         body += "<h1>Output</h1><pre>%s</pre>" % escape( output)
 34     else:
 35       body = '<h1 style="color:red">No file was given!</h1>' 
 36   
 37     return page_template % ("xmllint output", body)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>xmllint output</title>
</head>
<body>
<h1 style="color:red">No file was given!</h1>
</body>
</html>
Doba běhu: 8.1 ms