paulb@99 | 1 | #!/usr/bin/env python |
paulb@99 | 2 | |
paulb@99 | 3 | "A test of cookies." |
paulb@99 | 4 | |
paulb@99 | 5 | import WebStack.Generic |
paulb@99 | 6 | import time |
paulb@99 | 7 | |
paulb@99 | 8 | class CookiesResource: |
paulb@99 | 9 | |
paulb@99 | 10 | "A resource adding and removing cookies." |
paulb@99 | 11 | |
paulb@99 | 12 | def respond(self, trans): |
paulb@99 | 13 | trans.set_content_type(WebStack.Generic.ContentType("text/html")) |
paulb@99 | 14 | |
paulb@99 | 15 | # Get the fields and choose an action. |
paulb@99 | 16 | |
paulb@99 | 17 | fields = trans.get_fields_from_path() |
paulb@99 | 18 | |
paulb@99 | 19 | cookie_name_list = fields.get("name") or ["test"] |
paulb@99 | 20 | cookie_value_list = fields.get("value") or ["test"] |
paulb@99 | 21 | cookie_path_list = fields.get("path") or ["/"] |
paulb@99 | 22 | cookie_expires_list = fields.get("expires") or ["60"] |
paulb@99 | 23 | |
paulb@99 | 24 | cookie_name = cookie_name_list[0] |
paulb@99 | 25 | cookie_value = cookie_value_list[0] |
paulb@99 | 26 | cookie_path = cookie_path_list[0] |
paulb@99 | 27 | cookie_expires = int(cookie_expires_list[0]) |
paulb@99 | 28 | |
paulb@99 | 29 | message = "No action taken - use add or delete to change the cookies." |
paulb@99 | 30 | |
paulb@99 | 31 | if fields.has_key("add"): |
paulb@99 | 32 | trans.set_cookie_value( |
paulb@99 | 33 | cookie_name, |
paulb@99 | 34 | cookie_value, |
paulb@99 | 35 | cookie_path, |
paulb@99 | 36 | time.time() + cookie_expires |
paulb@99 | 37 | ) |
paulb@99 | 38 | message = "Cookie %s added!" % cookie_name |
paulb@99 | 39 | |
paulb@99 | 40 | elif fields.has_key("delete"): |
paulb@99 | 41 | trans.delete_cookie(cookie_name) |
paulb@99 | 42 | message = "Cookie %s deleted!" % cookie_name |
paulb@99 | 43 | |
paulb@99 | 44 | # Get some information. |
paulb@99 | 45 | |
paulb@99 | 46 | out = trans.get_response_stream() |
paulb@99 | 47 | out.write(""" |
paulb@99 | 48 | <html> |
paulb@99 | 49 | <head> |
paulb@99 | 50 | <title>Cookies Example</title> |
paulb@99 | 51 | </head> |
paulb@99 | 52 | <body> |
paulb@99 | 53 | <h1>Cookies</h1> |
paulb@99 | 54 | <p>%s</p> |
paulb@99 | 55 | <ul> |
paulb@99 | 56 | %s |
paulb@99 | 57 | </ul> |
paulb@99 | 58 | </body> |
paulb@99 | 59 | </html> |
paulb@99 | 60 | """ % ( |
paulb@99 | 61 | message, |
paulb@99 | 62 | self._format_dict(trans.get_cookies()), |
paulb@99 | 63 | )) |
paulb@99 | 64 | |
paulb@99 | 65 | def _format_dict(self, d): |
paulb@99 | 66 | return "".join([ |
paulb@99 | 67 | "<dt>%s</dt><dd>%s</dd>" % (key, value) |
paulb@99 | 68 | for key, value in d.items() |
paulb@99 | 69 | ]) |
paulb@99 | 70 | |
paulb@99 | 71 | def _format_list(self, l): |
paulb@99 | 72 | return "".join([ |
paulb@99 | 73 | "<li>%s</li>" % value |
paulb@99 | 74 | for value in l |
paulb@99 | 75 | ]) |
paulb@99 | 76 | |
paulb@99 | 77 | # vim: tabstop=4 expandtab shiftwidth=4 |