Merge branch 'master' into python3
[wrw.git] / wrw / wmako.py
CommitLineData
3d866605
FT
1import os, threading
2from mako import template, lookup, filters
5d0ae101 3from . import util, form, session, env, resp
3d866605
FT
4
5# It seems Mako isn't thread-safe.
6makolock = threading.Lock()
7
8class liblookup(lookup.TemplateLookup):
9 def __init__(self, *args, **kwargs):
10 lookup.TemplateLookup.__init__(self, *args, **kwargs)
11
12 def adjust_uri(self, uri, relativeto):
13 return uri
14
15libdirs = []
16homedir = os.getenv("HOME")
17if homedir is not None:
18 usrdir = os.path.join(homedir, "wmako")
19 if os.path.exists(usrdir):
20 libdirs.append(usrdir)
21libdirs.append(os.path.join(os.path.dirname(__file__), "makolib"))
22cachedir = os.path.join("/tmp/", "mako-" + str(os.getuid()))
23defargs = {"output_encoding": "utf-8",
24 "input_encoding": "utf-8",
25 "default_filters": ["decode.utf8"],
26 "module_directory": cachedir,
27 }
4eca1118
FT
28
29def makelib(init=liblookup, directories=[], **kwargs):
30 ad = dict(defargs)
31 ad.update(kwargs)
32 return init(directories = libdirs + directories, **ad)
33
34lib = env.var(makelib())
3d866605
FT
35
36if not os.path.exists(cachedir):
37 os.mkdir(cachedir)
38def handle(req, filename, **kw):
39 with makolock:
4eca1118 40 tt = template.Template(filename = filename, lookup = lib.val, **defargs)
3d866605
FT
41 req.ohead["Content-Type"] = "text/html; charset=utf-8"
42 return [tt.render(request = req, **kw)]
43
44@util.wsgiwrap
45def application(req):
54e74e80
FT
46 if req.method not in ["GET", "HEAD"]:
47 raise resp.httperror(405)
3d866605
FT
48 return handle(req, req.filename,
49 form = form.formdata(req),
50 session = session.get(req))