Fixed form handler bug when no POST data is present.
[wrw.git] / wrw / form.py
1 import cgi
2
3 __all__ = ["formdata"]
4
5 class formwrap(object):
6     def __init__(self, req):
7         if req.ihead.get("Content-Type") == "application/x-www-form-urlencoded":
8             self.cf = cgi.parse(environ = req.env, fp = req.env["wsgi.input"])
9         else:
10             self.cf = cgi.parse(environ = req.env)
11
12     def __getitem__(self, key):
13         return self.cf[key][0]
14
15     def get(self, key, default = ""):
16         if key in self:
17             return self.cf[key][0]
18         return default
19
20     def __contains__(self, key):
21         return key in self.cf and len(self.cf[key]) > 0
22
23     def __iter__(self):
24         return iter(self.cf)
25
26     def items(self):
27         def iter():
28             for key, list in self.cf.items():
29                 for val in list:
30                     yield key, val
31         return list(iter())
32
33     def keys(self):
34         return self.cf.keys()
35
36     def values(self):
37         return [val for key, val in self.items()]
38
39 def formdata(req):
40     return req.item(formwrap)