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 54 # Use Unicode for correct character encoding behaviour. 55 56 out.write(u""" 57 <html> 58 <head> 59 <title>Form Test</title> 60 </head> 61 <body> 62 <h1>Form Test</h1> 63 <h2>Normal</h2> 64 <form method="post" action=""> 65 <input name="x" type="text" value="1"/><br/> 66 <input name="x" type="text" value="2"/><br/> 67 <input name="y" type="text" value="3"/><br/> 68 <input name="f" type="file"/><br/> 69 <input name="send" type="submit" value="Send!"/> 70 </form> 71 <h2>Multipart</h2> 72 <form method="post" action="" enctype="multipart/form-data"> 73 <input name="x" type="text" value="1"/><br/> 74 <input name="x" type="text" value="2"/><br/> 75 <input name="y" type="text" value="3"/><br/> 76 <input name="f" type="file"/><br/> 77 <input name="send" type="submit" value="Send!"/> 78 </form> 79 <h2>Content Type</h2> 80 <p>%s</p> 81 <h2>Charset</h2> 82 <h3>From Content Type</h3> 83 <p>%s</p> 84 <h3>In Use</h3> 85 <p>%s</p> 86 <h2>Fields from Body</h2> 87 <ul>%s</ul> 88 </body> 89 </html> 90 """ % ( 91 content_type_str, 92 content_type_charset, 93 charset, 94 self._format_fields(fields) 95 )) 96 97 def _format_fields(self, d): 98 return "".join([ 99 "<li>%s<ul>%s</ul></li>" % (key, self._format_list(value)) 100 for key, value in d.items() 101 ]) 102 103 def _format_list(self, l): 104 return "".join([ 105 "<li>%s</li>" % value 106 for value in l 107 ]) 108 109 # vim: tabstop=4 expandtab shiftwidth=4