Initial commit.
[wrw.git] / wrw / cookie.py
1 import Cookie
2
3 __all__ = ["cookies", "get", "add"]
4
5 def addcookies(req):
6     ck = cookies(req)
7     for nm in ck.codec:
8         req.ohead.add("Set-Cookie", ck.codec[nm].OutputString())
9
10 class cookiedict(object):
11     def __init__(self, req):
12         self.bk = Cookie.SimpleCookie(req.ihead.get("Cookie"))
13         self.codec = Cookie.SimpleCookie()
14         req.oncommit(addcookies)
15
16     def __getitem__(self, name):
17         return self.bk[name].value
18
19     def __contains__(self, name):
20         return name in self.bk
21
22     def get(self, name, default = None):
23         if name not in self.bk:
24             return default
25         return self.bk[name].value
26
27     def add(self, name, value, path = None):
28         self.codec[name] = value
29         if path is not None: self.codec[name]["path"] = path
30
31     def __setitem__(self, name, value):
32         self.add(name, value)
33
34 def cookies(req):
35     return req.item(cookiedict)
36
37 def get(req, name, default = None):
38     return cookies(req).get(name, default)
39
40 def add(req, name, value, path = None):
41     cookies(req).add(name, value, path)