Include a selfpath in requests derived from a funplex.
[wrw.git] / wrw / filesys.py
CommitLineData
79a8b95a 1import os
d854802a 2from . import resp
79a8b95a
FT
3pj = os.path.join
4
5__all__ = ["filehandler"]
6
7class filehandler(object):
8 def __init__(self, basedir):
9 self.basedir = basedir
10
11 def handledir(self, req, path):
12 raise resp.notfound()
13
14 def handlefile(self, req, path):
15 ctype = "application/octet-stream"
16 bn = os.path.basename(path)
17 if '.' in bn:
18 ext = bn[bn.rindex('.') + 1:].lower()
19 if ext == "jpg" or ext == "jpeg":
20 ctype = "image/jpeg"
21 elif ext == "png":
22 ctype = "image/png"
23 elif ext == "gif":
24 ctype = "image/gif"
25 elif ext == "txt":
26 ctype = "text/plain"
27 elif ext == "css":
28 ctype = "text/css"
29 elif ext == "html":
30 ctype = "text/html"
31 req.ohead["Content-Type"] = ctype
c33f2d6c 32 return open(path, "rb")
79a8b95a
FT
33
34 def resolvefile(self, req, curpath, el):
35 if os.path.isfile(pj(curpath, el)):
36 return pj(curpath, el)
37 if '.' not in el:
38 for f in os.listdir(curpath):
39 p = f.find('.')
40 if p > 0:
41 if f[:p] == el:
42 return pj(curpath, f)
43 raise resp.notfound()
44
45 def handlefinal(self, req, curpath, el):
46 if el == "":
47 return self.handledir(req, curpath)
48 return self.handlefile(req, self.resolvefile(req, curpath, el))
49
50 def handlenonfinal(self, req, curpath, el, rest):
51 raise resp.notfound()
52
53 def handleentry(self, req, curpath, el, rest):
54 if el == "":
55 raise resp.notfound()
56 if '/' in el or el[0] == '.':
57 raise resp.notfound()
58 if os.path.isdir(pj(curpath, el)):
59 return self.handlepath(req, pj(curpath, el), rest)
60 return self.handlenonfinal(req, curpath, el, rest)
61
62 def handlepath(self, req, curpath, rest):
63 p = rest.find('/')
64 if p < 0:
65 return self.handlefinal(req, curpath, rest)
66 else:
67 return self.handleentry(req, curpath, rest[:p], rest[p + 1:])
68
69 def handle(self, req):
70 pi = req.pathinfo
71 if len(pi) > 0 and pi[0] == '/':
72 pi = pi[1:]
73 return self.handlepath(req, self.basedir, pi)