Added a simple filesystem handler.
[wrw.git] / wrw / req.py
CommitLineData
b409a338
FT
1__all__ = ["request"]
2
3class headdict(object):
4 def __init__(self):
5 self.dict = {}
6
7 def __getitem__(self, key):
8 return self.dict[key.lower()][1]
9
10 def __setitem__(self, key, val):
11 self.dict[key.lower()] = [key, val]
12
13 def __contains__(self, key):
14 return key.lower() in self.dict
15
16 def __delitem__(self, key):
17 del self.dict[key.lower()]
18
19 def __iter__(self):
20 return iter((list[0] for list in self.dict.itervalues()))
21
22 def get(self, key, default = ""):
23 if key.lower() in self.dict:
24 return self.dict[key.lower()][1]
25 return default
26
27 def getlist(self, key):
28 return self.dict.setdefault(key.lower(), [key])[1:]
29
30 def add(self, key, val):
31 self.dict.setdefault(key.lower(), [key]).append(val)
32
33 def __repr__(self):
34 return repr(self.dict)
35
36 def __str__(self):
37 return str(self.dict)
38
39def fixcase(str):
40 str = str.lower()
41 i = 0
42 b = True
43 while i < len(str):
44 if b:
45 str = str[:i] + str[i].upper() + str[i + 1:]
46 b = False
47 if str[i] == '-':
48 b = True
49 i += 1
50 return str
51
52class request(object):
53 def __init__(self, env):
54 self.env = env
55 self.uriname = env["SCRIPT_NAME"]
56 self.filename = env.get("SCRIPT_FILENAME")
57 self.uri = env["REQUEST_URI"]
58 self.pathinfo = env["PATH_INFO"]
59 self.query = env["QUERY_STRING"]
60 self.remoteaddr = env["REMOTE_ADDR"]
61 self.serverport = env["SERVER_PORT"]
62 self.https = "HTTPS" in env
63 self.ihead = headdict()
64 self.ohead = headdict()
65 for k, v in env.items():
66 if k[:5] == "HTTP_":
67 self.ihead.add(fixcase(k[5:].replace("_", "-")), v)
68 self.items = {}
69 self.statuscode = (200, "OK")
70 self.ohead["Content-Type"] = "text/html"
71 self.resources = set()
72 self.clean = set()
73 self.commitfuns = []
74
75 def status(self, code, msg):
76 self.statuscode = code, msg
77
78 def item(self, id):
79 if id in self.items:
80 return self.items[id]
81 self.items[id] = new = id(self)
82 if hasattr(new, "__enter__") and hasattr(new, "__exit__"):
83 self.withres(new)
84 return new
85
86 def withres(self, res):
87 if res not in self.resources:
88 done = False
89 res.__enter__()
90 try:
91 self.resources.add(res)
92 self.clean.add(res.__exit__)
93 done = True
94 finally:
95 if not done:
96 res.__exit__(None, None, None)
97 self.resources.discard(res)
98
99 def cleanup(self):
100 def clean1(list):
101 if len(list) > 0:
102 try:
103 list[0]()
104 finally:
105 clean1(list[1:])
106 clean1(list(self.clean))
107
108 def oncommit(self, fn):
109 if fn not in self.commitfuns:
110 self.commitfuns.append(fn)
111
112 def commit(self, startreq):
113 for fun in reversed(self.commitfuns):
114 fun(self)
115 hdrs = []
116 for nm in self.ohead:
117 for val in self.ohead.getlist(nm):
118 hdrs.append((nm, val))
119 startreq("%s %s" % self.statuscode, hdrs)