-
Notifications
You must be signed in to change notification settings - Fork 30
/
flask_mako.py
282 lines (220 loc) · 9.48 KB
/
flask_mako.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# -*- coding: utf-8 -*-
"""
flask.ext.mako
~~~~~~~~~~~~~~~~~~~~~~~
Extension implementing Mako Templates support in Flask with support for
flask-babel
:copyright: (c) 2012 by Béranger Enselme <benselme@gmail.com>
:license: BSD, see LICENSE for more details.
"""
import os, sys
from flask.helpers import locked_cached_property
from flask.signals import template_rendered
# Find the context stack so we can resolve which application is calling this
# extension. Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
from werkzeug.debug.tbtools import Traceback, Frame, Line
from mako.lookup import TemplateLookup
from mako.template import Template
from mako import exceptions
from mako.exceptions import RichTraceback, text_error_template
itervalues = getattr(dict, 'itervalues', dict.values)
_BABEL_IMPORTS = 'from flask.ext.babel import gettext as _, ngettext, ' \
'pgettext, npgettext'
_FLASK_IMPORTS = 'from flask.helpers import url_for, get_flashed_messages'
class MakoFrame(Frame):
""" A special `~werkzeug.debug.tbtools.Frame` object for Mako sources. """
def __init__(self, exc_type, exc_value, tb, name, line):
super(MakoFrame, self).__init__(exc_type, exc_value, tb)
self.info = "(translated Mako exception)"
self.filename = name
self.lineno = line
old_locals = self.locals
self.locals = dict(tb.tb_frame.f_locals['context'].kwargs)
self.locals['__mako_module_locals__'] = old_locals
def get_annotated_lines(self):
"""
Remove frame-finding code from `~werkzeug.debug.tbtools.Frame`. This
code is actively dangerous when run on Mako templates because
Werkzeug's parsing doesn't understand their syntax. Instead, just mark
the current line.
"""
lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)]
try:
lines[self.lineno - 1].current = True
except IndexError:
pass
return lines
class TemplateError(RichTraceback, RuntimeError):
""" A template has thrown an error during rendering. """
def werkzeug_debug_traceback(self, exc_type, exc_value, tb):
""" Munge the default Werkzeug traceback to include Mako info. """
orig_type, orig_value, orig_tb = self.einfo
translated = Traceback(orig_type, orig_value, tb)
# Drop the "raise" frame from the traceback.
translated.frames.pop()
def orig_frames():
cur = orig_tb
while cur:
yield cur
cur = cur.tb_next
# Append our original frames, overwriting previous source information
# with the translated Mako line locators.
for tb, record in zip(orig_frames(), self.records):
name, line = record[4:6]
if name:
new_frame = MakoFrame(orig_type, orig_value, tb, name, line)
else:
new_frame = Frame(orig_type, orig_value, tb)
translated.frames.append(new_frame)
return translated
def __init__(self, template):
super(TemplateError, self).__init__()
self.einfo = sys.exc_info()
self.text = text_error_template().render()
msg = "Error occurred while rendering template '{0}'"
msg = msg.format(template.uri)
super(TemplateError, self).__init__(msg)
class MakoTemplates(object):
"""
Main class for bridging mako and flask. We try to stay as close as possible
to how Jinja2 is used in Flask, while at the same time surfacing the useful
stuff from Mako.
"""
def __init__(self, app=None):
self.app = None
if app is not None:
self.init_app(app)
self.app = app
def init_app(self, app):
"""
Initialize a :class:`~flask.Flask` application
for use with this extension. This method is useful for the factory
pattern of extension initialization. Example::
mako = MakoTemplates()
app = Flask(__name__)
mako.init_app(app)
.. note::
This call will fail if you called the :class:`MakoTemplates`
constructor with an ``app`` argument.
"""
if self.app:
raise RuntimeError("Cannot call init_app when app argument was "
"provided to MakoTemplates constructor.")
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['mako'] = self
app._mako_lookup = None
app.config.setdefault('MAKO_INPUT_ENCODING', 'utf-8')
app.config.setdefault('MAKO_OUTPUT_ENCODING', 'utf-8')
app.config.setdefault('MAKO_MODULE_DIRECTORY', None)
app.config.setdefault('MAKO_COLLECTION_SIZE', -1)
app.config.setdefault('MAKO_IMPORTS', None)
app.config.setdefault('MAKO_FILESYSTEM_CHECKS', True)
app.config.setdefault('MAKO_TRANSLATE_EXCEPTIONS', True)
app.config.setdefault('MAKO_DEFAULT_FILTERS', None)
app.config.setdefault('MAKO_PREPROCESSOR', None)
app.config.setdefault('MAKO_STRICT_UNDEFINED', False)
def _create_lookup(app):
"""Returns a :class:`TemplateLookup <mako.lookup.TemplateLookup>`
instance that looks for templates from the same places as Flask, ie.
subfolders named 'templates' in both the app folder and its blueprints'
folders.
If flask-babel is installed it will add support for it in the templates
by adding the appropriate imports clause.
"""
imports = app.config['MAKO_IMPORTS'] or []
imports.append(_FLASK_IMPORTS)
if 'babel' in app.extensions:
imports.append(_BABEL_IMPORTS)
# for beaker
cache_impl = app.config.get('MAKO_CACHE_IMPL')
cache_args = app.config.get('MAKO_CACHE_ARGS')
kw = {
'input_encoding': app.config['MAKO_INPUT_ENCODING'],
'output_encoding': app.config['MAKO_OUTPUT_ENCODING'],
'module_directory': app.config['MAKO_MODULE_DIRECTORY'],
'collection_size': app.config['MAKO_COLLECTION_SIZE'],
'imports': imports,
'filesystem_checks': app.config['MAKO_FILESYSTEM_CHECKS'],
'default_filters': app.config['MAKO_DEFAULT_FILTERS'],
'preprocessor': app.config['MAKO_PREPROCESSOR'],
'strict_undefined': app.config['MAKO_STRICT_UNDEFINED'],
}
if cache_impl:
kw['cache_impl'] = cache_impl
if cache_args:
kw['cache_args'] = cache_args
if isinstance(app.template_folder, (list, tuple)):
paths = [os.path.join(app.root_path, tf) for tf in app.template_folder]
else:
paths = [os.path.join(app.root_path, app.template_folder)]
blueprints = getattr(app, 'blueprints', {})
for blueprint in itervalues(blueprints):
bp_tf = blueprint.template_folder
if bp_tf:
if isinstance(bp_tf, (list, tuple)):
paths.extend([os.path.join(blueprint.root_path, tf)
for tf in bp_tf])
else:
paths.append(os.path.join(blueprint.root_path, bp_tf))
paths = [path for path in paths if os.path.isdir(path)]
return TemplateLookup(directories=paths, **kw)
def _lookup(app):
if not app._mako_lookup:
app._mako_lookup = _create_lookup(app)
return app._mako_lookup
def _render(template, context, app):
"""Renders the template and fires the signal"""
context.update(app.jinja_env.globals)
app.update_template_context(context)
try:
rv = template.render(**context)
template_rendered.send(app, template=template, context=context)
return rv
except:
translate = app.config.get("MAKO_TRANSLATE_EXCEPTIONS")
if translate:
translated = TemplateError(template)
raise translated
else:
raise
def render_template(template_name, **context):
"""Renders a template from the template folder with the given
context.
:param template_name: the name of the template to be rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = stack.top
return _render(_lookup(ctx.app).get_template(template_name),
context, ctx.app)
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = stack.top
template = Template(source, lookup=_lookup(ctx.app))
return _render(template, context, ctx.app)
def render_template_def(template_name, def_name, **context):
"""Renders a specific def from a given
template from the template folder with the given
context. Useful for implementing this AJAX pattern:
http://techspot.zzzeek.org/2008/09/01/ajax-the-mako-way
:param template_name: the name of the template file containing the def
to be rendered
:param def_name: the name of the def to be rendered
:param context: the variables that should be available in the
context of the template.
"""
ctx = stack.top
template = _lookup(ctx.app).get_template(template_name)
return _render(template.get_def(def_name), context, ctx.app)