1 #!/usr/bin/env python 2 3 "A form submission test." 4 5 import WebStack.Generic 6 7 class FormResource: 8 9 """ 10 A resource which handles incoming form submissions. 11 """ 12 13 def respond(self, trans): 14 15 """ 16 Examine the incoming request, decoding the form information. 17 """ 18 19 # NOTE: Some frameworks do not pass in the content type. 20 21 content_type = trans.get_content_type() 22 if content_type: 23 content_type_str = content_type.media_type 24 content_type_charset = content_type.charset 25 else: 26 content_type_str = None 27 content_type_charset = None 28 29 # Optional encodings can be employed. 30 31 fields_from_path = trans.get_fields_from_path() 32 33 # Send the appropriate kind of response. 34 35 if fields_from_path.has_key("charset"): 36 charset = fields_from_path["charset"][0] 37 trans.set_content_type(WebStack.Generic.ContentType("text/html", charset)) 38 elif content_type_charset: 39 charset = content_type_charset 40 trans.set_content_type(WebStack.Generic.ContentType("text/html", charset)) 41 else: 42 charset = None 43 trans.set_content_type(WebStack.Generic.ContentType("text/html")) 44 45 # Handle charset issues. 46 47 if charset: 48 fields = trans.get_fields_from_body(charset) 49 else: 50 fields = trans.get_fields_from_body() 51 52 out = trans.get_response_stream() 53 out.write(u""" 54 <html> 55 <head> 56 <title>Form Test</title> 57 </head> 58 <body> 59 <h1>Form Test</h1> 60 <h2>Normal</h2> 61 <form method="post" action=""> 62 <input name="x" type="text" value="1"/><br/> 63 <input name="x" type="text" value="2"/><br/> 64 <input name="y" type="text" value="3"/><br/> 65 <input name="f" type="file"/><br/> 66 <input name="send" type="submit" value="Send!"/> 67 </form> 68 <h2>Multipart</h2> 69 <form method="post" action="" enctype="multipart/form-data"> 70 <input name="x" type="text" value="1"/><br/> 71 <input name="x" type="text" value="2"/><br/> 72 <input name="y" type="text" value="3"/><br/> 73 <input name="f" type="file"/><br/> 74 <input name="send" type="submit" value="Send!"/> 75 </form> 76 <h2>Content Type</h2> 77 <p>%s</p> 78 <h2>Charset</h2> 79 <h3>From Content Type</h3> 80 <p>%s</p> 81 <h3>In Use</h3> 82 <p>%s</p> 83 <h2>Fields from Body</h2> 84 <ul>%s</ul> 85 </body> 86 </html> 87 """ % ( 88 content_type_str, 89 content_type_charset, 90 charset, 91 self._format_fields(fields) 92 )) 93 94 def _format_fields(self, d): 95 return "".join([ 96 "<li>%s<ul>%s</ul></li>" % (key, self._format_list(value)) 97 for key, value in d.items() 98 ]) 99 100 def _format_list(self, l): 101 return "".join([ 102 "<li>%s</li>" % value 103 for value in l 104 ]) 105 106 # vim: tabstop=4 expandtab shiftwidth=4