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