Fixed copyrequest missing input.
[wrw.git] / wrw / cookie.py
1 import http.cookies, time
2 from . import proto
3
4 __all__ = ["cookies", "get", "add"]
5
6 def addcookies(req):
7     ck = cookies(req)
8     for nm in ck.codec:
9         req.ohead.add("Set-Cookie", ck.codec[nm].OutputString())
10
11 class cookiedict(object):
12     def __init__(self, req):
13         try:
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()
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
26     def get(self, name, default=None):
27         if name not in self.bk:
28             return default
29         return self.bk[name].value
30
31     def add(self, name, value, **kw):
32         self.codec[name] = value
33         for key, value in kw.items():
34             self.codec[name][key] = value
35
36     def __setitem__(self, name, value):
37         self.add(name, value)
38
39 def cookies(req):
40     return req.item(cookiedict)
41
42 def get(req, name, default=None):
43     return cookies(req).get(name, default)
44
45 def add(req, name, value, **kw):
46     cookies(req).add(name, value, **kw)
47
48 cdate = proto.httpdate