Commit | Line | Data |
---|---|---|
b409a338 FT |
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): | |
8204ad1d FT |
12 | try: |
13 | self.bk = Cookie.SimpleCookie(req.ihead.get("Cookie")) | |
14 | except Cookie.CookieError: | |
15 | self.bk = Cookie.SimpleCookie() | |
b409a338 FT |
16 | self.codec = Cookie.SimpleCookie() |
17 | req.oncommit(addcookies) | |
18 | ||
19 | def __getitem__(self, name): | |
20 | return self.bk[name].value | |
21 | ||
22 | def __contains__(self, name): | |
23 | return name in self.bk | |
24 | ||
25 | def get(self, name, default = None): | |
26 | if name not in self.bk: | |
27 | return default | |
28 | return self.bk[name].value | |
29 | ||
30 | def add(self, name, value, path = None): | |
31 | self.codec[name] = value | |
32 | if path is not None: self.codec[name]["path"] = path | |
33 | ||
34 | def __setitem__(self, name, value): | |
35 | self.add(name, value) | |
36 | ||
37 | def cookies(req): | |
38 | return req.item(cookiedict) | |
39 | ||
40 | def get(req, name, default = None): | |
41 | return cookies(req).get(name, default) | |
42 | ||
43 | def add(req, name, value, path = None): | |
44 | cookies(req).add(name, value, path) |