Merge branch 'master' into python3
[wrw.git] / wrw / cookie.py
CommitLineData
920b69c3
FT
1import http.cookies, time
2from . import proto
b409a338
FT
3
4__all__ = ["cookies", "get", "add"]
5
6def addcookies(req):
7 ck = cookies(req)
8 for nm in ck.codec:
9 req.ohead.add("Set-Cookie", ck.codec[nm].OutputString())
10
11class cookiedict(object):
12 def __init__(self, req):
8204ad1d 13 try:
c33f2d6c
FT
14 self.bk = http.cookies.SimpleCookie(req.ihead.get("Cookie"))
15 except http.cookies.CookieError:
16 self.bk = http.cookies.SimpleCookie()
17 self.codec = http.cookies.SimpleCookie()
b409a338
FT
18 req.oncommit(addcookies)
19
20 def __getitem__(self, name):
21 return self.bk[name].value
22
23 def __contains__(self, name):
24 return name in self.bk
25
9bc70dab 26 def get(self, name, default=None):
b409a338
FT
27 if name not in self.bk:
28 return default
29 return self.bk[name].value
30
d99a17a6 31 def add(self, name, value, **kw):
b409a338 32 self.codec[name] = value
5218a0fd 33 for key, value in kw.items():
d99a17a6 34 self.codec[name][key] = value
b409a338
FT
35
36 def __setitem__(self, name, value):
37 self.add(name, value)
38
39def cookies(req):
40 return req.item(cookiedict)
41
9bc70dab 42def get(req, name, default=None):
b409a338
FT
43 return cookies(req).get(name, default)
44
d99a17a6
FT
45def add(req, name, value, **kw):
46 cookies(req).add(name, value, **kw)
badc2530
FT
47
48cdate = proto.httpdate