Removed some leftovers from media.xsl.
[enkel.git] / enkel / cookie.py
blob94a95e729f9c4691bb3cddf2e11e61de376d744b
1 # This file is part of the Enkel web programming library.
3 # Copyright (C) 2007 Espen Angell Kristiansen (espeak@users.sourceforge.net)
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 """ Cookie helpers.
21 @warning: Unlike the standard Cookie module, this interface does
22 not encode the cookie value, so if you wish to store special
23 characters, you have to encode the value.
24 """
26 from datetime import datetime
28 from enkel.wansgli.utils import rfc1123_date
29 from enkel.wansgli.env import parse_value
32 def get_cookies(env):
33 """ Lookup cookies in the WSGI environ dict.
35 Example
36 =======
37 >>> env = dict(HTTP_COOKIE="sid=ax33d; name=John Peters")
38 >>> get_cookies(env)
39 {'name': 'John Peters', 'sid': 'ax33d'}
41 @param env: WSGI environ dict.
42 @return: dict with cookie-name as key and cookie-value as value.
43 Returns None when no cookie is found.
44 """
45 c = env.get("HTTP_COOKIE")
46 if c:
47 return parse_value(c)
48 else:
49 return None
52 class Cookie(object):
53 """ A http cookie interface.
55 Unlike the standard Cookie module, this class only works
56 with a single cookie, and provides a simple interface
57 for defining cookies.
59 Usage
60 =====
61 >>> from datetime import timedelta, datetime
62 >>> c = Cookie("name", "John Peters")
63 >>> print c
64 set-cookie: name=John Peters
67 Persistant cookies
68 ------------------
69 You can specify a timeout or a expiration date.
71 >>> c.expires = datetime(2010, 12, 24)
72 >>> print c
73 set-cookie: name=John Peters; expires=Fri, 24 Dec 2010 00:00:00 GMT
75 Timeouts are specified like this:
77 >>> c.set_timeout(timedelta(days=10))
80 Getting headers for WSGI
81 ------------------------
82 >>> c = Cookie("id", "axTTT")
83 >>> c.get_httpheader()
84 ('set-cookie', 'id=axTTT')
87 @ivar name: The name of the cookie.
88 @ivar value: The value of the cookie.
89 @ivar domain: The cookie domain. Browsers will only send the cookie
90 when revisiting this domain. Defaults to None, which most
91 browsers translates to "use current domain".
92 @ivar path: Cookie path. Browsers will only send the cookie when
93 when revisiting this path. Defaults to None, which most
94 browsers translates to "use current path".
95 @ivar expires: The expiration date of the cookie as a datetime.datetime
96 object. Defaults to None (no timeout). Note that if you want
97 to set this to the current time you should use datetime.utcnow(),
98 since cookies work in GMT/UTC time.
100 @cvar HTTP_HEADER: The http header name used to set cookies.
101 @cvar VERSION: The cookie version used.
103 HTTP_HEADER = "set-cookie"
104 VERSION = "1"
105 def __init__(self, name, value, timeout=None):
107 @param name: The name of the cookie.
108 @param value: The value of the cookie.
109 @param timeout: sent to L{set_timeout} if not None.
111 self.name = name
112 self.value = value
113 self.domain = None
114 self.expires = None
115 self.path = None
116 if timeout:
117 self.set_timeout(timeout)
119 def set_timeout(self, timeout):
120 """ Set the expiration relative to the current time.
121 @param timeout: A datetime.timedelta object.
123 self.expires = datetime.utcnow() + timeout
125 def get_httpheader(self):
126 """ Get the http header like WSGI likes it.
127 @return: (header-name, header-value) pair.
129 v = ["%s=%s" % (self.name, self.value)]
130 if self.expires:
131 v.append("expires=%s" % rfc1123_date(self.expires))
132 if self.path:
133 v.append("path=%s" % self.path)
134 if self.domain:
135 v.append("domain=%s" % self.domain)
136 return self.HTTP_HEADER, "; ".join(v)
138 def __str__(self):
139 return "%s: %s" % self.get_httpheader()
142 def suite():
143 import doctest
144 return doctest.DocTestSuite()
146 if __name__ == "__main__":
147 from enkel.wansgli.testhelpers import run_suite
148 run_suite(suite())