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