pyramid-mako 1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,300 @@
1
+ import os
2
+ import posixpath
3
+ import sys
4
+
5
+ from mako.exceptions import (
6
+ TemplateLookupException,
7
+ TopLevelLookupException,
8
+ text_error_template,
9
+ )
10
+ from mako.lookup import TemplateLookup
11
+ from pyramid.asset import abspath_from_asset_spec
12
+ from pyramid.path import AssetResolver
13
+ from pyramid.settings import asbool, aslist
14
+
15
+ from .compat import is_nonstr_iter, reraise
16
+
17
+
18
+ class PkgResourceTemplateLookup(TemplateLookup):
19
+ """TemplateLookup subclass that handles asset specification URIs"""
20
+
21
+ def adjust_uri(self, uri, relativeto):
22
+ """Called from within a Mako template, avoids adjusting the
23
+ uri if it looks like an asset specification"""
24
+ # Don't adjust asset spec names
25
+ isabs = os.path.isabs(uri)
26
+ if (not isabs) and (":" in uri):
27
+ return uri
28
+ if not (isabs) and ("$" in uri):
29
+ return uri.replace("$", ":")
30
+ if relativeto is not None:
31
+ relativeto = relativeto.replace("$", ":")
32
+ if not (":" in uri) and (":" in relativeto):
33
+ if uri.startswith("/"):
34
+ return uri
35
+ pkg, relto = relativeto.split(":")
36
+ _uri = posixpath.join(posixpath.dirname(relto), uri)
37
+ return "{0}:{1}".format(pkg, _uri)
38
+ if not (":" in uri) and not (":" in relativeto):
39
+ return posixpath.join(posixpath.dirname(relativeto), uri)
40
+ return TemplateLookup.adjust_uri(self, uri, relativeto)
41
+
42
+ def get_template(self, uri):
43
+ """Fetch a template from the cache, or check the filesystem
44
+ for it
45
+
46
+ In addition to the basic filesystem lookup, this subclass will
47
+ use pkg_resource to load a file using the asset
48
+ specification syntax.
49
+
50
+ """
51
+ isabs = os.path.isabs(uri)
52
+ if (not isabs) and (":" in uri):
53
+ # Windows can't cope with colons in filenames, so we replace the
54
+ # colon with a dollar sign in the filename mako uses to actually
55
+ # store the generated python code in the mako module_directory or
56
+ # in the temporary location of mako's modules
57
+ adjusted = uri.replace(":", "$")
58
+ try:
59
+ if self.filesystem_checks:
60
+ return self._check(adjusted, self._collection[adjusted])
61
+ else:
62
+ return self._collection[adjusted]
63
+ except KeyError:
64
+ asset = AssetResolver().resolve(uri)
65
+ if asset.exists():
66
+ srcfile = asset.abspath()
67
+ return self._load(srcfile, adjusted)
68
+ raise TopLevelLookupException(
69
+ "Can not locate template for uri %r" % uri
70
+ )
71
+ try:
72
+ return TemplateLookup.get_template(self, uri)
73
+ except TemplateLookupException:
74
+ if isabs:
75
+ return self._load(uri, uri)
76
+ else:
77
+ raise
78
+
79
+
80
+ class MakoRenderingException(Exception):
81
+ def __init__(self, text):
82
+ self.text = text
83
+
84
+ def __repr__(self):
85
+ return self.text
86
+
87
+ __str__ = __repr__
88
+
89
+
90
+ class MakoLookupTemplateRenderer(object):
91
+ """Render a :term:`Mako` template using the ``template``.
92
+ If a ``defname`` is defined, in the form of
93
+ ``package:path/to/template#defname.mako``, a function named ``defname``
94
+ inside the ``template`` will then be rendered.
95
+ """
96
+
97
+ @property
98
+ def template(self):
99
+ spec = self.spec
100
+ isabspath = os.path.isabs(spec)
101
+ colon_in_name = ":" in spec
102
+ isabsspec = colon_in_name and (not isabspath)
103
+ isrelspec = (not isabsspec) and (not isabspath)
104
+
105
+ try:
106
+ # try to find the template using default search paths
107
+ template = self.lookup.get_template(spec)
108
+ except TemplateLookupException:
109
+ if isrelspec:
110
+ # convert relative asset spec to absolute asset spec
111
+ resolver = AssetResolver(self.package)
112
+ asset = resolver.resolve(spec)
113
+ spec = asset.absspec()
114
+ template = self.lookup.get_template(spec)
115
+ else:
116
+ raise
117
+
118
+ return template
119
+
120
+ def __init__(self, lookup, spec, defname, package):
121
+ self.lookup = lookup
122
+ self.spec = spec
123
+ self.defname = defname
124
+ self.package = package
125
+
126
+ def __call__(self, value, system):
127
+ # Update the system dictionary with the values from the user
128
+ try:
129
+ system.update(value)
130
+ except (TypeError, ValueError):
131
+ raise ValueError("renderer was passed non-dictionary as value")
132
+
133
+ # Check if 'context' in the dictionary
134
+ context = system.pop("context", None)
135
+
136
+ # Rename 'context' to '_context' because Mako internally already has a
137
+ # variable named 'context'
138
+ if context is not None:
139
+ system["_context"] = context
140
+
141
+ template = self.template
142
+ if self.defname is not None:
143
+ template = template.get_def(self.defname)
144
+ try:
145
+ result = template.render_unicode(**system)
146
+ except:
147
+ try:
148
+ exc_info = sys.exc_info()
149
+ errtext = text_error_template().render(
150
+ error=exc_info[1], traceback=exc_info[2]
151
+ )
152
+ reraise(MakoRenderingException(errtext), None, exc_info[2])
153
+ finally:
154
+ del exc_info
155
+
156
+ return result
157
+
158
+
159
+ class MakoRendererFactory(object):
160
+ lookup = None
161
+ renderer_factory = staticmethod(MakoLookupTemplateRenderer) # testing
162
+
163
+ def __call__(self, info):
164
+ defname = None
165
+ asset, ext = info.name.rsplit(".", 1)
166
+ if "#" in asset:
167
+ asset, defname = asset.rsplit("#", 1)
168
+
169
+ spec = "%s.%s" % (asset, ext)
170
+
171
+ return self.renderer_factory(self.lookup, spec, defname, info.package)
172
+
173
+
174
+ def parse_options_from_settings(settings, settings_prefix, maybe_dotted):
175
+ """Parse options for use with Mako's TemplateLookup from settings."""
176
+
177
+ def sget(name, default=None):
178
+ return settings.get(settings_prefix + name, default)
179
+
180
+ reload_templates = sget("reload_templates", None)
181
+ if reload_templates is None:
182
+ reload_templates = settings.get("pyramid.reload_templates", None)
183
+ reload_templates = asbool(reload_templates)
184
+ directories = sget("directories", [])
185
+ module_directory = sget("module_directory", None)
186
+ input_encoding = sget("input_encoding", "utf-8")
187
+ error_handler = sget("error_handler", None)
188
+ default_filters = sget("default_filters", "h")
189
+ imports = sget("imports", None)
190
+ future_imports = sget("future_imports", None)
191
+ strict_undefined = asbool(sget("strict_undefined", False))
192
+ preprocessor = sget("preprocessor", None)
193
+ preprocessor_wants_settings = asbool(sget("preprocessor_wants_settings", None))
194
+ cache_impl = sget("cache_impl", "beaker")
195
+ cache_type = sget("cache.type", None)
196
+ cache_dir = sget("cache.dir", module_directory)
197
+ cache_timeout = sget("cache.timeout", None)
198
+ cache_url = sget("cache.url", None)
199
+
200
+ if not is_nonstr_iter(directories):
201
+ # Since we parse a value that comes from an .ini config,
202
+ # we treat whitespaces and newline characters equally as list item separators.
203
+ directories = aslist(directories, flatten=True)
204
+ directories = [abspath_from_asset_spec(d) for d in directories]
205
+
206
+ if module_directory is not None:
207
+ module_directory = abspath_from_asset_spec(module_directory)
208
+
209
+ if error_handler is not None:
210
+ error_handler = maybe_dotted(error_handler)
211
+
212
+ if default_filters is not None:
213
+ if not is_nonstr_iter(default_filters):
214
+ default_filters = aslist(default_filters)
215
+
216
+ if imports is not None:
217
+ if not is_nonstr_iter(imports):
218
+ imports = aslist(imports, flatten=False)
219
+
220
+ if future_imports is not None:
221
+ if not is_nonstr_iter(future_imports):
222
+ future_imports = aslist(future_imports)
223
+
224
+ if preprocessor is not None:
225
+ preprocessor_function = maybe_dotted(preprocessor)
226
+ if preprocessor_wants_settings:
227
+
228
+ def preprocessor_injector(template):
229
+ return preprocessor_function(template, settings)
230
+
231
+ preprocessor = preprocessor_injector
232
+ else:
233
+ preprocessor = preprocessor_function
234
+
235
+ return dict(
236
+ directories=directories,
237
+ module_directory=module_directory,
238
+ input_encoding=input_encoding,
239
+ error_handler=error_handler,
240
+ default_filters=default_filters,
241
+ imports=imports,
242
+ future_imports=future_imports,
243
+ filesystem_checks=reload_templates,
244
+ strict_undefined=strict_undefined,
245
+ preprocessor=preprocessor,
246
+ cache_impl=cache_impl,
247
+ cache_args=dict(
248
+ timeout=cache_timeout,
249
+ url=cache_url,
250
+ type=cache_type,
251
+ dir=cache_dir,
252
+ ),
253
+ )
254
+
255
+
256
+ def add_mako_renderer(config, extension, settings_prefix="mako."):
257
+ """Register a Mako renderer for a template extension.
258
+
259
+ This function is available on the Pyramid configurator after
260
+ including the package:
261
+
262
+ .. code-block:: python
263
+
264
+ config.add_mako_renderer('.html', settings_prefix='mako.')
265
+
266
+ The renderer will load its configuration from a prefix in the Pyramid
267
+ settings dictionary. The default prefix is 'mako.'.
268
+ """
269
+ renderer_factory = MakoRendererFactory()
270
+ config.add_renderer(extension, renderer_factory)
271
+
272
+ def register():
273
+ registry = config.registry
274
+ opts = parse_options_from_settings(
275
+ registry.settings, settings_prefix, config.maybe_dotted
276
+ )
277
+ lookup = PkgResourceTemplateLookup(**opts)
278
+
279
+ renderer_factory.lookup = lookup
280
+
281
+ config.action(("mako-renderer", extension), register)
282
+
283
+
284
+ def includeme(config):
285
+ """Set up standard configurator registrations. Use via:
286
+
287
+ .. code-block:: python
288
+
289
+ config = Configurator()
290
+ config.include('pyramid_mako')
291
+
292
+ Once this function has been invoked, the ``.mako`` and ``.mak`` renderers
293
+ are available for use in Pyramid. This can be overridden and more may be
294
+ added via the ``config.add_mako_renderer`` directive. See
295
+ :func:`~pyramid_mako.add_mako_renderer` documentation for more information.
296
+ """
297
+ config.add_directive("add_mako_renderer", add_mako_renderer)
298
+
299
+ config.add_mako_renderer(".mako")
300
+ config.add_mako_renderer(".mak")
pyramid_mako/compat.py ADDED
@@ -0,0 +1,74 @@
1
+ import sys
2
+ import types
3
+
4
+ PY2 = sys.version_info[0] == 2
5
+
6
+ if PY2:
7
+ string_types = (basestring,)
8
+ integer_types = (int, long)
9
+ class_types = (type, types.ClassType)
10
+ text_type = unicode
11
+ binary_type = str
12
+ long = long
13
+
14
+ else:
15
+ string_types = (str,)
16
+ integer_types = (int,)
17
+ class_types = (type,)
18
+ text_type = str
19
+ binary_type = bytes
20
+ long = int
21
+
22
+
23
+ def text_(s, encoding="latin-1", errors="strict"):
24
+ """If ``s`` is an instance of ``binary_type``, return
25
+ ``s.decode(encoding, errors)``, otherwise return ``s``"""
26
+ if isinstance(s, binary_type):
27
+ return s.decode(encoding, errors)
28
+ return s
29
+
30
+
31
+ if PY2:
32
+
33
+ def is_nonstr_iter(v):
34
+ return hasattr(v, "__iter__")
35
+
36
+ else:
37
+
38
+ def is_nonstr_iter(v):
39
+ if isinstance(v, str):
40
+ return False
41
+ return hasattr(v, "__iter__")
42
+
43
+
44
+ if PY2: # pragma: no cover
45
+
46
+ def exec_(code, globs=None, locs=None):
47
+ """Execute code in a namespace."""
48
+ if globs is None:
49
+ frame = sys._getframe(1)
50
+ globs = frame.f_globals
51
+ if locs is None:
52
+ locs = frame.f_locals
53
+ del frame
54
+ elif locs is None:
55
+ locs = globs
56
+ exec("""exec code in globs, locs""")
57
+
58
+ exec_("""def reraise(tp, value, tb=None):
59
+ raise tp, value, tb
60
+ """)
61
+
62
+ else: # pragma: no cover
63
+ import builtins
64
+
65
+ exec_ = getattr(builtins, "exec")
66
+
67
+ def reraise(tp, value, tb=None):
68
+ if value is None:
69
+ value = tp
70
+ if value.__traceback__ is not tb:
71
+ raise value.with_traceback(tb)
72
+ raise value
73
+
74
+ del builtins
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyramid_mako
3
+ Version: 1.2
4
+ Summary: Mako template bindings for the Pyramid web framework
5
+ Author-email: Delta Regeer <pylons-discuss@googlegroups.com>
6
+ Maintainer-email: Pylons Project <pylons-discuss@googlegroups.com>
7
+ License-Expression: LicenseRef-Repoze-BSD-derived
8
+ Project-URL: Changelog, https://docs.pylonsproject.org/projects/pyramid_mako/en/latest/changes.html
9
+ Project-URL: Documentation, https://docs.pylonsproject.org/projects/pyramid_mako/en/latest/
10
+ Project-URL: Homepage, https://github.com/Pylons/pyramid_mako
11
+ Project-URL: Issue Tracker, https://github.com/Pylons/pyramid_mako/issues
12
+ Keywords: mako,pylons,pyramid,web,wsgi
13
+ Classifier: Development Status :: 6 - Mature
14
+ Classifier: Framework :: Pyramid
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/x-rst
27
+ License-File: LICENSE.txt
28
+ Requires-Dist: Mako>=1.1.0
29
+ Requires-Dist: pyramid>=1.3
30
+ Dynamic: license-file
31
+
32
+ `Mako <http://www.makotemplates.org/>`_ bindings for Pyramid
33
+ ============================================================
34
+
35
+ These are bindings for the `Mako templating system <https://www.makotemplates.org/>`_ for the `Pyramid <https://trypyramid.com/>`_ web framework.
36
+
37
+ Documentation for `pyramid_mako <https://docs.pylonsproject.org/projects/pyramid_mako/en/latest/>`_.
38
+
39
+ 1.2 (2026-11-23)
40
+ ================
41
+
42
+ - Drop support for Python 2.7 and 3.4 through 3.10.
43
+
44
+ - Add support for Python 3.11, 3.12, 3.13, 3.14, and 3.15.
45
+
46
+ - Require ``pyramid >= 1.3``, the first release with
47
+ ``pyramid.path.AssetResolver``.
48
+
49
+ - Add support for setting cache arguments as well as the cache implementation
50
+ to use in the configuration passed to `pyramid_mako`
51
+
52
+ - Stop using the deprecated ``pkg_resources`` api in the docs.
53
+
54
+ - Switch packaging metadata from ``setup.cfg`` to ``pyproject.toml`` and use
55
+ an SPDX license expression. The ``testing`` and ``docs`` extras are replaced
56
+ by dependency groups.
57
+
58
+ 1.1.0 (2019-08-18)
59
+ ==================
60
+
61
+ - Add support for Python 3.5, 3.6, 3.7.
62
+
63
+ - Require ``mako >= 1.1.0``.
64
+
65
+ - Add a config option for ``preprocessor_wants_settings``. If set to ``true``,
66
+ the ``preprocessor`` will be wrapped in a function that invokes the
67
+ preprocessor with pyramid's config settings as the second argument.
68
+
69
+ 1.0.2 (2014-04-22)
70
+ ==================
71
+
72
+ - Fix mako.imports so that aslist() does not flatten. See issue #23
73
+ (https://github.com/Pylons/pyramid_mako/issues/23)
74
+
75
+ 1.0.1 (2014-04-16)
76
+ ==================
77
+
78
+ - Bump the required version of Mako to 0.8 or newer for issue #22 (add
79
+ future_imports). If you would like to use an older version of Mako, please
80
+ pin your dependency to version 0.3.1 of pyramid_mako.
81
+
82
+ 1.0 (2014-04-15)
83
+ ================
84
+
85
+ - Add new configuration variable for future_imports. See issue #22
86
+ (https://github.com/Pylons/pyramid_mako/issues/22)
87
+ - Fix issue #19, whereby pyramid.reload_templates stopped functioning due to
88
+ changes in pyramid_mako. The lookup is now completed at template render,
89
+ instead of when the factory returns the renderer. See:
90
+ (https://github.com/Pylons/pyramid_mako/issues/19)
91
+ - Tuple return values in the form of ('defname', {}) are no longer supported,
92
+ and will result in a ValueError being raised.
93
+ - Fix an packaging issue whereby \*.foo files were not included in the MANIFEST.
94
+ - Caller-relative template lookup is now supported. Any template that fails
95
+ to be found in the default search paths will be searched relative to the
96
+ caller package.
97
+ - Allow overriding the ``pyramid.reload_templates`` using
98
+ ``mako.reload_templates``.
99
+ - Change the way that custom user values passed to the renderer are merged with
100
+ the system provided variables. This allows the user to pass in a variable
101
+ named 'context' and have it correctly override the system provided context,
102
+ and THEN get correctly renamed so that Mako doesn't complain about a variable
103
+ being passed in that isn't allowed due to it being reserved.
104
+ - Drop testing dependency on ``nose-selecttests``.
105
+
106
+ 0.3.1 (2013-10-22)
107
+ ==================
108
+
109
+ - Re-enable lazy loading of the mako renderer, allowing the settings
110
+ to be configured after pyramid_mako has been included, as long as everything
111
+ happens in the same commit.
112
+
113
+ 0.3 (2013-10-20)
114
+ ================
115
+
116
+ - Add a new Configurator directive, ``config.add_mako_renderer`` which
117
+ can be used to add a new mako renderer for a given extension. This
118
+ directive accepts an optional ``settings_prefix`` to load settings and
119
+ configuration differently per-renderer as well.
120
+
121
+ - Removed the private APIs, ``IMakoLookup``, ``MakoRendererFactoryHelper``,
122
+ and ``renderer_factory``. See the new ``config.add_mako_renderer`` API
123
+ for updating offending code.
124
+
125
+ - Remove dependency on ``pyramid.interfaces.ITemplateRenderer`` from
126
+ Pyramid 1.5.
127
+
128
+ 0.2 (2013-09-07)
129
+ ================
130
+
131
+ - Docs up-to-date
132
+ - Latest changes pulled from Pyramid
133
+ - Latest tests pulled from Pyramid
134
+ - All tests updated to refer to fixtures in pyramid_mako
135
+
136
+ 0.1 (2012-03-12)
137
+ ================
138
+
139
+ - First release. Extracted from Pyramid core.
140
+
@@ -0,0 +1,7 @@
1
+ pyramid_mako/__init__.py,sha256=jpjLfCJ6h3zdfq_2Gy8H7cl336NUiME_OYVhwjW2B5c,10472
2
+ pyramid_mako/compat.py,sha256=p4sgjmYsHWSv5IKTeig2p4ihJd7-7Ew1Br8sxZagT8A,1622
3
+ pyramid_mako-1.2.dist-info/licenses/LICENSE.txt,sha256=QU48zYp1hpbDpHCKMeNlB_HEd1f901odVpvkMIUUgzg,1791
4
+ pyramid_mako-1.2.dist-info/METADATA,sha256=VN5OPzJkSNjJLdZLodonjc9HhTF15eHkdiSyd37LFHI,5517
5
+ pyramid_mako-1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ pyramid_mako-1.2.dist-info/top_level.txt,sha256=DBkQciMV7OyWv6vtzfGPHYPSorQBzdXSUn8fRtUTqQ4,13
7
+ pyramid_mako-1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,41 @@
1
+ License
2
+
3
+ A copyright notice accompanies this license document that identifies
4
+ the copyright holders.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are
8
+ met:
9
+
10
+ 1. Redistributions in source code must retain the accompanying
11
+ copyright notice, this list of conditions, and the following
12
+ disclaimer.
13
+
14
+ 2. Redistributions in binary form must reproduce the accompanying
15
+ copyright notice, this list of conditions, and the following
16
+ disclaimer in the documentation and/or other materials provided
17
+ with the distribution.
18
+
19
+ 3. Names of the copyright holders must not be used to endorse or
20
+ promote products derived from this software without prior
21
+ written permission from the copyright holders.
22
+
23
+ 4. If any files are modified, you must cause the modified files to
24
+ carry prominent notices stating that you changed the files and
25
+ the date of any change.
26
+
27
+ Disclaimer
28
+
29
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND
30
+ ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31
+ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
32
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33
+ HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
34
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
35
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
37
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
39
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40
+ SUCH DAMAGE.
41
+
@@ -0,0 +1 @@
1
+ pyramid_mako