Initial commit.
[wrw.git] / wrw / cookie.py
CommitLineData
b409a338
FT
1import Cookie
2
3__all__ = ["cookies", "get", "add"]
4
5def addcookies(req):
6 ck = cookies(req)
7 for nm in ck.codec:
8 req.ohead.add("Set-Cookie", ck.codec[nm].OutputString())
9
10class 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
34def cookies(req):
35 return req.item(cookiedict)
36
37def get(req, name, default = None):
38 return cookies(req).get(name, default)
39
40def add(req, name, value, path = None):
41 cookies(req).add(name, value, path)