tinybird 0.0.1.dev0__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.
Potentially problematic release.
This version of tinybird might be problematic. Click here for more details.
- tinybird/__cli__.py +8 -0
- tinybird/ch_utils/constants.py +244 -0
- tinybird/ch_utils/engine.py +855 -0
- tinybird/check_pypi.py +25 -0
- tinybird/client.py +1281 -0
- tinybird/config.py +117 -0
- tinybird/connectors.py +428 -0
- tinybird/context.py +23 -0
- tinybird/datafile.py +5589 -0
- tinybird/datatypes.py +434 -0
- tinybird/feedback_manager.py +1022 -0
- tinybird/git_settings.py +145 -0
- tinybird/sql.py +865 -0
- tinybird/sql_template.py +2343 -0
- tinybird/sql_template_fmt.py +281 -0
- tinybird/sql_toolset.py +350 -0
- tinybird/syncasync.py +682 -0
- tinybird/tb_cli.py +25 -0
- tinybird/tb_cli_modules/auth.py +252 -0
- tinybird/tb_cli_modules/branch.py +1043 -0
- tinybird/tb_cli_modules/cicd.py +434 -0
- tinybird/tb_cli_modules/cli.py +1571 -0
- tinybird/tb_cli_modules/common.py +2082 -0
- tinybird/tb_cli_modules/config.py +344 -0
- tinybird/tb_cli_modules/connection.py +803 -0
- tinybird/tb_cli_modules/datasource.py +900 -0
- tinybird/tb_cli_modules/exceptions.py +91 -0
- tinybird/tb_cli_modules/fmt.py +91 -0
- tinybird/tb_cli_modules/job.py +85 -0
- tinybird/tb_cli_modules/pipe.py +858 -0
- tinybird/tb_cli_modules/regions.py +9 -0
- tinybird/tb_cli_modules/tag.py +100 -0
- tinybird/tb_cli_modules/telemetry.py +310 -0
- tinybird/tb_cli_modules/test.py +107 -0
- tinybird/tb_cli_modules/tinyunit/tinyunit.py +340 -0
- tinybird/tb_cli_modules/tinyunit/tinyunit_lib.py +71 -0
- tinybird/tb_cli_modules/token.py +349 -0
- tinybird/tb_cli_modules/workspace.py +269 -0
- tinybird/tb_cli_modules/workspace_members.py +212 -0
- tinybird/tornado_template.py +1194 -0
- tinybird-0.0.1.dev0.dist-info/METADATA +2815 -0
- tinybird-0.0.1.dev0.dist-info/RECORD +45 -0
- tinybird-0.0.1.dev0.dist-info/WHEEL +5 -0
- tinybird-0.0.1.dev0.dist-info/entry_points.txt +2 -0
- tinybird-0.0.1.dev0.dist-info/top_level.txt +4 -0
|
@@ -0,0 +1,1194 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright 2009 Facebook
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
|
5
|
+
# not use this file except in compliance with the License. You may obtain
|
|
6
|
+
# a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
12
|
+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
13
|
+
# License for the specific language governing permissions and limitations
|
|
14
|
+
# under the License.
|
|
15
|
+
|
|
16
|
+
"""A simple template system that compiles templates to Python code.
|
|
17
|
+
|
|
18
|
+
Basic usage looks like::
|
|
19
|
+
|
|
20
|
+
t = template.Template("<html>{{ myvalue }}</html>")
|
|
21
|
+
print(t.generate(myvalue="XXX"))
|
|
22
|
+
|
|
23
|
+
`Loader` is a class that loads templates from a root directory and caches
|
|
24
|
+
the compiled templates::
|
|
25
|
+
|
|
26
|
+
loader = template.Loader("/home/btaylor")
|
|
27
|
+
print(loader.load("test.html").generate(myvalue="XXX"))
|
|
28
|
+
|
|
29
|
+
We compile all templates to raw Python. Error-reporting is currently... uh,
|
|
30
|
+
interesting. Syntax for the templates::
|
|
31
|
+
|
|
32
|
+
### base.html
|
|
33
|
+
<html>
|
|
34
|
+
<head>
|
|
35
|
+
<title>{% block title %}Default title{% end %}</title>
|
|
36
|
+
</head>
|
|
37
|
+
<body>
|
|
38
|
+
<ul>
|
|
39
|
+
{% for student in students %}
|
|
40
|
+
{% block student %}
|
|
41
|
+
<li>{{ escape(student.name) }}</li>
|
|
42
|
+
{% end %}
|
|
43
|
+
{% end %}
|
|
44
|
+
</ul>
|
|
45
|
+
</body>
|
|
46
|
+
</html>
|
|
47
|
+
|
|
48
|
+
### bold.html
|
|
49
|
+
{% extends "base.html" %}
|
|
50
|
+
|
|
51
|
+
{% block title %}A bolder title{% end %}
|
|
52
|
+
|
|
53
|
+
{% block student %}
|
|
54
|
+
<li><span style="bold">{{ escape(student.name) }}</span></li>
|
|
55
|
+
{% end %}
|
|
56
|
+
|
|
57
|
+
Unlike most other template systems, we do not put any restrictions on the
|
|
58
|
+
expressions you can include in your statements. ``if`` and ``for`` blocks get
|
|
59
|
+
translated exactly into Python, so you can do complex expressions like::
|
|
60
|
+
|
|
61
|
+
{% for student in [p for p in people if p.student and p.age > 23] %}
|
|
62
|
+
<li>{{ escape(student.name) }}</li>
|
|
63
|
+
{% end %}
|
|
64
|
+
|
|
65
|
+
Translating directly to Python means you can apply functions to expressions
|
|
66
|
+
easily, like the ``escape()`` function in the examples above. You can pass
|
|
67
|
+
functions in to your template just like any other variable
|
|
68
|
+
(In a `.RequestHandler`, override `.RequestHandler.get_template_namespace`)::
|
|
69
|
+
|
|
70
|
+
### Python code
|
|
71
|
+
def add(x, y):
|
|
72
|
+
return x + y
|
|
73
|
+
template.execute(add=add)
|
|
74
|
+
|
|
75
|
+
### The template
|
|
76
|
+
{{ add(1, 2) }}
|
|
77
|
+
|
|
78
|
+
We provide the functions `escape() <.xhtml_escape>`, `.url_escape()`,
|
|
79
|
+
`.json_encode()`, and `.squeeze()` to all templates by default.
|
|
80
|
+
|
|
81
|
+
Typical applications do not create `Template` or `Loader` instances by
|
|
82
|
+
hand, but instead use the `~.RequestHandler.render` and
|
|
83
|
+
`~.RequestHandler.render_string` methods of
|
|
84
|
+
`tornado.web.RequestHandler`, which load templates automatically based
|
|
85
|
+
on the ``template_path`` `.Application` setting.
|
|
86
|
+
|
|
87
|
+
Variable names beginning with ``_tt_`` are reserved by the template
|
|
88
|
+
system and should not be used by application code.
|
|
89
|
+
|
|
90
|
+
Syntax Reference
|
|
91
|
+
----------------
|
|
92
|
+
|
|
93
|
+
Template expressions are surrounded by double curly braces: ``{{ ... }}``.
|
|
94
|
+
The contents may be any python expression, which will be escaped according
|
|
95
|
+
to the current autoescape setting and inserted into the output. Other
|
|
96
|
+
template directives use ``{% %}``.
|
|
97
|
+
|
|
98
|
+
To comment out a section so that it is omitted from the output, surround it
|
|
99
|
+
with ``{# ... #}``.
|
|
100
|
+
|
|
101
|
+
These tags may be escaped as ``{{!``, ``{%!``, and ``{#!``
|
|
102
|
+
if you need to include a literal ``{{``, ``{%``, or ``{#`` in the output.
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
``{% apply *function* %}...{% end %}``
|
|
106
|
+
Applies a function to the output of all template code between ``apply``
|
|
107
|
+
and ``end``::
|
|
108
|
+
|
|
109
|
+
{% apply linkify %}{{name}} said: {{message}}{% end %}
|
|
110
|
+
|
|
111
|
+
Note that as an implementation detail apply blocks are implemented
|
|
112
|
+
as nested functions and thus may interact strangely with variables
|
|
113
|
+
set via ``{% set %}``, or the use of ``{% break %}`` or ``{% continue %}``
|
|
114
|
+
within loops.
|
|
115
|
+
|
|
116
|
+
``{% autoescape *function* %}``
|
|
117
|
+
Sets the autoescape mode for the current file. This does not affect
|
|
118
|
+
other files, even those referenced by ``{% include %}``. Note that
|
|
119
|
+
autoescaping can also be configured globally, at the `.Application`
|
|
120
|
+
or `Loader`.::
|
|
121
|
+
|
|
122
|
+
{% autoescape xhtml_escape %}
|
|
123
|
+
{% autoescape None %}
|
|
124
|
+
|
|
125
|
+
``{% block *name* %}...{% end %}``
|
|
126
|
+
Indicates a named, replaceable block for use with ``{% extends %}``.
|
|
127
|
+
Blocks in the parent template will be replaced with the contents of
|
|
128
|
+
the same-named block in a child template.::
|
|
129
|
+
|
|
130
|
+
<!-- base.html -->
|
|
131
|
+
<title>{% block title %}Default title{% end %}</title>
|
|
132
|
+
|
|
133
|
+
<!-- mypage.html -->
|
|
134
|
+
{% extends "base.html" %}
|
|
135
|
+
{% block title %}My page title{% end %}
|
|
136
|
+
|
|
137
|
+
``{% comment ... %}``
|
|
138
|
+
A comment which will be removed from the template output. Note that
|
|
139
|
+
there is no ``{% end %}`` tag; the comment goes from the word ``comment``
|
|
140
|
+
to the closing ``%}`` tag.
|
|
141
|
+
|
|
142
|
+
``{% extends *filename* %}``
|
|
143
|
+
Inherit from another template. Templates that use ``extends`` should
|
|
144
|
+
contain one or more ``block`` tags to replace content from the parent
|
|
145
|
+
template. Anything in the child template not contained in a ``block``
|
|
146
|
+
tag will be ignored. For an example, see the ``{% block %}`` tag.
|
|
147
|
+
|
|
148
|
+
``{% for *var* in *expr* %}...{% end %}``
|
|
149
|
+
Same as the python ``for`` statement. ``{% break %}`` and
|
|
150
|
+
``{% continue %}`` may be used inside the loop.
|
|
151
|
+
|
|
152
|
+
``{% from *x* import *y* %}``
|
|
153
|
+
Same as the python ``import`` statement.
|
|
154
|
+
|
|
155
|
+
``{% if *condition* %}...{% elif *condition* %}...{% else %}...{% end %}``
|
|
156
|
+
Conditional statement - outputs the first section whose condition is
|
|
157
|
+
true. (The ``elif`` and ``else`` sections are optional)
|
|
158
|
+
|
|
159
|
+
``{% import *module* %}``
|
|
160
|
+
Same as the python ``import`` statement.
|
|
161
|
+
|
|
162
|
+
``{% include *filename* %}``
|
|
163
|
+
Includes another template file. The included file can see all the local
|
|
164
|
+
variables as if it were copied directly to the point of the ``include``
|
|
165
|
+
directive (the ``{% autoescape %}`` directive is an exception).
|
|
166
|
+
Alternately, ``{% module Template(filename, **kwargs) %}`` may be used
|
|
167
|
+
to include another template with an isolated namespace.
|
|
168
|
+
|
|
169
|
+
``{% module *expr* %}``
|
|
170
|
+
Renders a `~tornado.web.UIModule`. The output of the ``UIModule`` is
|
|
171
|
+
not escaped::
|
|
172
|
+
|
|
173
|
+
{% module Template("foo.html", arg=42) %}
|
|
174
|
+
|
|
175
|
+
``UIModules`` are a feature of the `tornado.web.RequestHandler`
|
|
176
|
+
class (and specifically its ``render`` method) and will not work
|
|
177
|
+
when the template system is used on its own in other contexts.
|
|
178
|
+
|
|
179
|
+
``{% raw *expr* %}``
|
|
180
|
+
Outputs the result of the given expression without autoescaping.
|
|
181
|
+
|
|
182
|
+
``{% set *x* = *y* %}``
|
|
183
|
+
Sets a local variable.
|
|
184
|
+
|
|
185
|
+
``{% try %}...{% except %}...{% else %}...{% finally %}...{% end %}``
|
|
186
|
+
Same as the python ``try`` statement.
|
|
187
|
+
|
|
188
|
+
``{% while *condition* %}... {% end %}``
|
|
189
|
+
Same as the python ``while`` statement. ``{% break %}`` and
|
|
190
|
+
``{% continue %}`` may be used inside the loop.
|
|
191
|
+
|
|
192
|
+
``{% whitespace *mode* %}``
|
|
193
|
+
Sets the whitespace mode for the remainder of the current file
|
|
194
|
+
(or until the next ``{% whitespace %}`` directive). See
|
|
195
|
+
`filter_whitespace` for available options. New in Tornado 4.3.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
from __future__ import absolute_import, division, print_function
|
|
199
|
+
|
|
200
|
+
import ast
|
|
201
|
+
import datetime
|
|
202
|
+
import linecache
|
|
203
|
+
import os.path
|
|
204
|
+
import posixpath
|
|
205
|
+
import re
|
|
206
|
+
import threading
|
|
207
|
+
from io import StringIO
|
|
208
|
+
from typing import Dict, Union
|
|
209
|
+
|
|
210
|
+
from tornado import escape
|
|
211
|
+
from tornado.log import app_log
|
|
212
|
+
from tornado.util import ObjectDict, exec_in, unicode_type
|
|
213
|
+
|
|
214
|
+
from .context import disable_template_security_validation
|
|
215
|
+
|
|
216
|
+
_DEFAULT_AUTOESCAPE = "xhtml_escape"
|
|
217
|
+
_UNSET = object()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def filter_whitespace(mode, text):
|
|
221
|
+
"""Transform whitespace in ``text`` according to ``mode``.
|
|
222
|
+
|
|
223
|
+
Available modes are:
|
|
224
|
+
|
|
225
|
+
* ``all``: Return all whitespace unmodified.
|
|
226
|
+
* ``single``: Collapse consecutive whitespace with a single whitespace
|
|
227
|
+
character, preserving newlines.
|
|
228
|
+
* ``oneline``: Collapse all runs of whitespace into a single space
|
|
229
|
+
character, removing all newlines in the process.
|
|
230
|
+
|
|
231
|
+
.. versionadded:: 4.3
|
|
232
|
+
"""
|
|
233
|
+
if mode == "all":
|
|
234
|
+
return text
|
|
235
|
+
elif mode == "single":
|
|
236
|
+
text = re.sub(r"([\t ]+)", " ", text)
|
|
237
|
+
text = re.sub(r"(\s*\n\s*)", "\n", text)
|
|
238
|
+
return text
|
|
239
|
+
elif mode == "oneline":
|
|
240
|
+
return re.sub(r"(\s+)", " ", text)
|
|
241
|
+
else:
|
|
242
|
+
raise Exception("invalid whitespace mode %s" % mode)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class Template:
|
|
246
|
+
"""A compiled template.
|
|
247
|
+
|
|
248
|
+
We compile into Python from the given template_string. You can generate
|
|
249
|
+
the template from variables with generate().
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
# note that the constructor's signature is not extracted with
|
|
253
|
+
# autodoc because _UNSET looks like garbage. When changing
|
|
254
|
+
# this signature update website/sphinx/template.rst too.
|
|
255
|
+
|
|
256
|
+
def __init__(
|
|
257
|
+
self,
|
|
258
|
+
template_string,
|
|
259
|
+
name="<string>",
|
|
260
|
+
loader=None,
|
|
261
|
+
compress_whitespace=_UNSET,
|
|
262
|
+
autoescape=_UNSET,
|
|
263
|
+
whitespace=None,
|
|
264
|
+
):
|
|
265
|
+
"""Construct a Template.
|
|
266
|
+
|
|
267
|
+
:arg str template_string: the contents of the template file.
|
|
268
|
+
:arg str name: the filename from which the template was loaded
|
|
269
|
+
(used for error message).
|
|
270
|
+
:arg tornado.template.BaseLoader loader: the `~tornado.template.BaseLoader` responsible
|
|
271
|
+
for this template, used to resolve ``{% include %}`` and ``{% extend %}`` directives.
|
|
272
|
+
:arg bool compress_whitespace: Deprecated since Tornado 4.3.
|
|
273
|
+
Equivalent to ``whitespace="single"`` if true and
|
|
274
|
+
``whitespace="all"`` if false.
|
|
275
|
+
:arg str autoescape: The name of a function in the template
|
|
276
|
+
namespace, or ``None`` to disable escaping by default.
|
|
277
|
+
:arg str whitespace: A string specifying treatment of whitespace;
|
|
278
|
+
see `filter_whitespace` for options.
|
|
279
|
+
|
|
280
|
+
.. versionchanged:: 4.3
|
|
281
|
+
Added ``whitespace`` parameter; deprecated ``compress_whitespace``.
|
|
282
|
+
"""
|
|
283
|
+
name = name if name else "<string>"
|
|
284
|
+
self.name = escape.native_str(name)
|
|
285
|
+
|
|
286
|
+
if compress_whitespace is not _UNSET:
|
|
287
|
+
# Convert deprecated compress_whitespace (bool) to whitespace (str).
|
|
288
|
+
if whitespace is not None:
|
|
289
|
+
raise Exception("cannot set both whitespace and compress_whitespace")
|
|
290
|
+
whitespace = "single" if compress_whitespace else "all"
|
|
291
|
+
if whitespace is None:
|
|
292
|
+
if loader and loader.whitespace:
|
|
293
|
+
whitespace = loader.whitespace
|
|
294
|
+
else:
|
|
295
|
+
# Whitespace defaults by filename.
|
|
296
|
+
if name.endswith(".html") or name.endswith(".js"):
|
|
297
|
+
whitespace = "single"
|
|
298
|
+
else:
|
|
299
|
+
whitespace = "all"
|
|
300
|
+
# Validate the whitespace setting.
|
|
301
|
+
filter_whitespace(whitespace, "")
|
|
302
|
+
|
|
303
|
+
if autoescape is not _UNSET:
|
|
304
|
+
self.autoescape = autoescape
|
|
305
|
+
elif loader:
|
|
306
|
+
self.autoescape = loader.autoescape
|
|
307
|
+
else:
|
|
308
|
+
self.autoescape = _DEFAULT_AUTOESCAPE
|
|
309
|
+
|
|
310
|
+
self.namespace = loader.namespace if loader else {}
|
|
311
|
+
reader = _TemplateReader(name, escape.native_str(template_string), whitespace)
|
|
312
|
+
self.file = _File(self, _parse(reader, self))
|
|
313
|
+
self.code = self._generate_python(loader)
|
|
314
|
+
self.loader = loader
|
|
315
|
+
try:
|
|
316
|
+
# Under python2.5, the fake filename used here must match
|
|
317
|
+
# the module name used in __name__ below.
|
|
318
|
+
# The dont_inherit flag prevents template.py's future imports
|
|
319
|
+
# from being applied to the generated code.
|
|
320
|
+
self.compiled = compile(
|
|
321
|
+
escape.to_unicode(self.code), "%s.generated.py" % self.name.replace(".", "_"), "exec", dont_inherit=True
|
|
322
|
+
)
|
|
323
|
+
except Exception:
|
|
324
|
+
formatted_code = _format_code(self.code).rstrip()
|
|
325
|
+
app_log.warning("%s code:\n%s", self.name, formatted_code)
|
|
326
|
+
raise
|
|
327
|
+
|
|
328
|
+
def generate(self, **kwargs):
|
|
329
|
+
"""Generate this template with the given arguments."""
|
|
330
|
+
namespace = {
|
|
331
|
+
"escape": escape.xhtml_escape,
|
|
332
|
+
"xhtml_escape": escape.xhtml_escape,
|
|
333
|
+
"url_escape": escape.url_escape,
|
|
334
|
+
"json_encode": escape.json_encode,
|
|
335
|
+
"squeeze": escape.squeeze,
|
|
336
|
+
"linkify": escape.linkify,
|
|
337
|
+
"datetime": datetime,
|
|
338
|
+
"_tt_utf8": escape.utf8, # for internal use
|
|
339
|
+
"_tt_string_types": (unicode_type, bytes),
|
|
340
|
+
# __name__ and __loader__ allow the traceback mechanism to find
|
|
341
|
+
# the generated source code.
|
|
342
|
+
"__name__": self.name.replace(".", "_"),
|
|
343
|
+
"__loader__": ObjectDict(get_source=lambda name: self.code),
|
|
344
|
+
}
|
|
345
|
+
namespace.update(self.namespace)
|
|
346
|
+
namespace.update(kwargs)
|
|
347
|
+
exec_in(self.compiled, namespace)
|
|
348
|
+
execute = namespace["_tt_execute"]
|
|
349
|
+
# Clear the traceback module's cache of source data now that
|
|
350
|
+
# we've generated a new template (mainly for this module's
|
|
351
|
+
# unittests, where different tests reuse the same name).
|
|
352
|
+
linecache.clearcache()
|
|
353
|
+
return execute()
|
|
354
|
+
|
|
355
|
+
def _generate_python(self, loader):
|
|
356
|
+
buffer = StringIO()
|
|
357
|
+
try:
|
|
358
|
+
# named_blocks maps from names to _NamedBlock objects
|
|
359
|
+
named_blocks: Dict[str, _NamedBlock] = {}
|
|
360
|
+
ancestors = self._get_ancestors(loader)
|
|
361
|
+
ancestors.reverse()
|
|
362
|
+
for ancestor in ancestors:
|
|
363
|
+
ancestor.find_named_blocks(loader, named_blocks)
|
|
364
|
+
writer = _CodeWriter(buffer, named_blocks, loader, ancestors[0].template)
|
|
365
|
+
ancestors[0].generate(writer)
|
|
366
|
+
return buffer.getvalue()
|
|
367
|
+
finally:
|
|
368
|
+
buffer.close()
|
|
369
|
+
|
|
370
|
+
def _get_ancestors(self, loader):
|
|
371
|
+
ancestors = [self.file]
|
|
372
|
+
for chunk in self.file.body.chunks:
|
|
373
|
+
if isinstance(chunk, _ExtendsBlock):
|
|
374
|
+
if not loader:
|
|
375
|
+
raise ParseError("{% extends %} block found, but no " "template loader")
|
|
376
|
+
template = loader.load(chunk.name, self.name)
|
|
377
|
+
ancestors.extend(template._get_ancestors(loader))
|
|
378
|
+
return ancestors
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
class BaseLoader:
|
|
382
|
+
"""Base class for template loaders.
|
|
383
|
+
|
|
384
|
+
You must use a template loader to use template constructs like
|
|
385
|
+
``{% extends %}`` and ``{% include %}``. The loader caches all
|
|
386
|
+
templates after they are loaded the first time.
|
|
387
|
+
"""
|
|
388
|
+
|
|
389
|
+
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None, whitespace=None):
|
|
390
|
+
"""Construct a template loader.
|
|
391
|
+
|
|
392
|
+
:arg str autoescape: The name of a function in the template
|
|
393
|
+
namespace, such as "xhtml_escape", or ``None`` to disable
|
|
394
|
+
autoescaping by default.
|
|
395
|
+
:arg dict namespace: A dictionary to be added to the default template
|
|
396
|
+
namespace, or ``None``.
|
|
397
|
+
:arg str whitespace: A string specifying default behavior for
|
|
398
|
+
whitespace in templates; see `filter_whitespace` for options.
|
|
399
|
+
Default is "single" for files ending in ".html" and ".js" and
|
|
400
|
+
"all" for other files.
|
|
401
|
+
|
|
402
|
+
.. versionchanged:: 4.3
|
|
403
|
+
Added ``whitespace`` parameter.
|
|
404
|
+
"""
|
|
405
|
+
self.autoescape = autoescape
|
|
406
|
+
self.namespace = namespace or {}
|
|
407
|
+
self.whitespace = whitespace
|
|
408
|
+
self.templates = {}
|
|
409
|
+
# self.lock protects self.templates. It's a reentrant lock
|
|
410
|
+
# because templates may load other templates via `include` or
|
|
411
|
+
# `extends`. Note that thanks to the GIL this code would be safe
|
|
412
|
+
# even without the lock, but could lead to wasted work as multiple
|
|
413
|
+
# threads tried to compile the same template simultaneously.
|
|
414
|
+
self.lock = threading.RLock()
|
|
415
|
+
|
|
416
|
+
def reset(self):
|
|
417
|
+
"""Resets the cache of compiled templates."""
|
|
418
|
+
with self.lock:
|
|
419
|
+
self.templates = {}
|
|
420
|
+
|
|
421
|
+
def resolve_path(self, name, parent_path=None):
|
|
422
|
+
"""Converts a possibly-relative path to absolute (used internally)."""
|
|
423
|
+
raise NotImplementedError()
|
|
424
|
+
|
|
425
|
+
def load(self, name, parent_path=None):
|
|
426
|
+
"""Loads a template."""
|
|
427
|
+
name = self.resolve_path(name, parent_path=parent_path)
|
|
428
|
+
with self.lock:
|
|
429
|
+
if name not in self.templates:
|
|
430
|
+
self.templates[name] = self._create_template(name)
|
|
431
|
+
return self.templates[name]
|
|
432
|
+
|
|
433
|
+
def _create_template(self, name):
|
|
434
|
+
raise NotImplementedError()
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
class Loader(BaseLoader):
|
|
438
|
+
"""A template loader that loads from a single root directory."""
|
|
439
|
+
|
|
440
|
+
def __init__(self, root_directory, **kwargs):
|
|
441
|
+
super().__init__(**kwargs)
|
|
442
|
+
self.root = os.path.abspath(root_directory)
|
|
443
|
+
|
|
444
|
+
def resolve_path(self, name, parent_path=None):
|
|
445
|
+
if (
|
|
446
|
+
parent_path
|
|
447
|
+
and not parent_path.startswith("<")
|
|
448
|
+
and not parent_path.startswith("/")
|
|
449
|
+
and not name.startswith("/")
|
|
450
|
+
):
|
|
451
|
+
current_path = os.path.join(self.root, parent_path)
|
|
452
|
+
file_dir = os.path.dirname(os.path.abspath(current_path))
|
|
453
|
+
relative_path = os.path.abspath(os.path.join(file_dir, name))
|
|
454
|
+
if relative_path.startswith(self.root):
|
|
455
|
+
name = relative_path[len(self.root) + 1 :]
|
|
456
|
+
return name
|
|
457
|
+
|
|
458
|
+
def _create_template(self, name):
|
|
459
|
+
path = os.path.join(self.root, name)
|
|
460
|
+
with open(path, "rb") as f:
|
|
461
|
+
template = Template(f.read(), name=name, loader=self)
|
|
462
|
+
return template
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class DictLoader(BaseLoader):
|
|
466
|
+
"""A template loader that loads from a dictionary."""
|
|
467
|
+
|
|
468
|
+
def __init__(self, dict, **kwargs):
|
|
469
|
+
super().__init__(**kwargs)
|
|
470
|
+
self.dict = dict
|
|
471
|
+
|
|
472
|
+
def resolve_path(self, name, parent_path=None):
|
|
473
|
+
if (
|
|
474
|
+
parent_path
|
|
475
|
+
and not parent_path.startswith("<")
|
|
476
|
+
and not parent_path.startswith("/")
|
|
477
|
+
and not name.startswith("/")
|
|
478
|
+
):
|
|
479
|
+
file_dir = posixpath.dirname(parent_path)
|
|
480
|
+
name = posixpath.normpath(posixpath.join(file_dir, name))
|
|
481
|
+
return name
|
|
482
|
+
|
|
483
|
+
def _create_template(self, name):
|
|
484
|
+
return Template(self.dict[name], name=name, loader=self)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
class _Node:
|
|
488
|
+
def each_child(self):
|
|
489
|
+
return ()
|
|
490
|
+
|
|
491
|
+
def generate(self, writer):
|
|
492
|
+
raise NotImplementedError()
|
|
493
|
+
|
|
494
|
+
def find_named_blocks(self, loader, named_blocks):
|
|
495
|
+
for child in self.each_child():
|
|
496
|
+
child.find_named_blocks(loader, named_blocks)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
class _File(_Node):
|
|
500
|
+
def __init__(self, template, body):
|
|
501
|
+
self.template = template
|
|
502
|
+
self.body = body
|
|
503
|
+
self.line = 0
|
|
504
|
+
|
|
505
|
+
def generate(self, writer):
|
|
506
|
+
writer.write_line("def _tt_execute():", self.line)
|
|
507
|
+
with writer.indent():
|
|
508
|
+
writer.write_line("_tt_buffer = []", self.line)
|
|
509
|
+
writer.write_line("_tt_append = _tt_buffer.append", self.line)
|
|
510
|
+
self.body.generate(writer)
|
|
511
|
+
writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
|
|
512
|
+
|
|
513
|
+
def each_child(self):
|
|
514
|
+
return (self.body,)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
class _ChunkList(_Node):
|
|
518
|
+
def __init__(self, chunks):
|
|
519
|
+
self.chunks = chunks
|
|
520
|
+
|
|
521
|
+
def generate(self, writer):
|
|
522
|
+
for chunk in self.chunks:
|
|
523
|
+
chunk.generate(writer)
|
|
524
|
+
|
|
525
|
+
def each_child(self):
|
|
526
|
+
return self.chunks
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
class _NamedBlock(_Node):
|
|
530
|
+
def __init__(self, name, body, template, line):
|
|
531
|
+
self.name = name
|
|
532
|
+
self.body = body
|
|
533
|
+
self.template = template
|
|
534
|
+
self.line = line
|
|
535
|
+
|
|
536
|
+
def each_child(self):
|
|
537
|
+
return (self.body,)
|
|
538
|
+
|
|
539
|
+
def generate(self, writer):
|
|
540
|
+
block = writer.named_blocks[self.name]
|
|
541
|
+
with writer.include(block.template, self.line):
|
|
542
|
+
block.body.generate(writer)
|
|
543
|
+
|
|
544
|
+
def find_named_blocks(self, loader, named_blocks):
|
|
545
|
+
named_blocks[self.name] = self
|
|
546
|
+
_Node.find_named_blocks(self, loader, named_blocks)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
class _ExtendsBlock(_Node):
|
|
550
|
+
def __init__(self, name):
|
|
551
|
+
self.name = name
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
class _IncludeBlock(_Node):
|
|
555
|
+
def __init__(self, name, reader, line):
|
|
556
|
+
self.name = name
|
|
557
|
+
self.template_name = reader.name
|
|
558
|
+
self.line = line
|
|
559
|
+
|
|
560
|
+
def find_named_blocks(self, loader, named_blocks):
|
|
561
|
+
included = loader.load(self.name, self.template_name)
|
|
562
|
+
included.file.find_named_blocks(loader, named_blocks)
|
|
563
|
+
|
|
564
|
+
def generate(self, writer):
|
|
565
|
+
included = writer.loader.load(self.name, self.template_name)
|
|
566
|
+
with writer.include(included, self.line):
|
|
567
|
+
included.file.body.generate(writer)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
class _ApplyBlock(_Node):
|
|
571
|
+
def __init__(self, method, line, body=None):
|
|
572
|
+
self.method = method
|
|
573
|
+
self.line = line
|
|
574
|
+
self.body = body
|
|
575
|
+
|
|
576
|
+
def each_child(self):
|
|
577
|
+
return (self.body,)
|
|
578
|
+
|
|
579
|
+
def generate(self, writer):
|
|
580
|
+
method_name = "_tt_apply%d" % writer.apply_counter
|
|
581
|
+
writer.apply_counter += 1
|
|
582
|
+
writer.write_line("def %s():" % method_name, self.line)
|
|
583
|
+
with writer.indent():
|
|
584
|
+
writer.write_line("_tt_buffer = []", self.line)
|
|
585
|
+
writer.write_line("_tt_append = _tt_buffer.append", self.line)
|
|
586
|
+
self.body.generate(writer)
|
|
587
|
+
writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
|
|
588
|
+
writer.write_line("_tt_append(_tt_utf8(%s(%s())))" % (self.method, method_name), self.line)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
class _ControlBlock(_Node):
|
|
592
|
+
def __init__(self, statement, line, body=None):
|
|
593
|
+
self.statement = statement
|
|
594
|
+
self.line = line
|
|
595
|
+
self.body = body
|
|
596
|
+
|
|
597
|
+
def each_child(self):
|
|
598
|
+
return (self.body,)
|
|
599
|
+
|
|
600
|
+
def generate(self, writer):
|
|
601
|
+
writer.write_line("%s:" % self.statement, self.line)
|
|
602
|
+
with writer.indent():
|
|
603
|
+
self.body.generate(writer)
|
|
604
|
+
# Just in case the body was empty
|
|
605
|
+
writer.write_line("pass", self.line)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
class _IntermediateControlBlock(_Node):
|
|
609
|
+
def __init__(self, statement, line):
|
|
610
|
+
self.statement = statement
|
|
611
|
+
self.line = line
|
|
612
|
+
|
|
613
|
+
def generate(self, writer):
|
|
614
|
+
# In case the previous block was empty
|
|
615
|
+
writer.write_line("pass", self.line)
|
|
616
|
+
writer.write_line("%s:" % self.statement, self.line, writer.indent_size() - 1)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
class _Statement(_Node):
|
|
620
|
+
def __init__(self, statement, line):
|
|
621
|
+
self.statement = statement
|
|
622
|
+
self.line = line
|
|
623
|
+
|
|
624
|
+
def generate(self, writer):
|
|
625
|
+
writer.write_line(self.statement, self.line)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
class _Expression(_Node):
|
|
629
|
+
def __init__(self, expression, line, raw=False):
|
|
630
|
+
if not disable_template_security_validation.get(False):
|
|
631
|
+
check_valid_code(expression)
|
|
632
|
+
self.expression = expression
|
|
633
|
+
self.line = line
|
|
634
|
+
self.raw = raw
|
|
635
|
+
|
|
636
|
+
def generate(self, writer):
|
|
637
|
+
writer.write_line("_tt_tmp = %s" % self.expression, self.line)
|
|
638
|
+
writer.write_line("if isinstance(_tt_tmp, _tt_string_types):" " _tt_tmp = _tt_utf8(_tt_tmp)", self.line)
|
|
639
|
+
writer.write_line("else: _tt_tmp = _tt_utf8(str(_tt_tmp))", self.line)
|
|
640
|
+
if not self.raw and writer.current_template.autoescape is not None:
|
|
641
|
+
# In python3 functions like xhtml_escape return unicode,
|
|
642
|
+
# so we have to convert to utf8 again.
|
|
643
|
+
writer.write_line("_tt_tmp = _tt_utf8(%s(_tt_tmp))" % writer.current_template.autoescape, self.line)
|
|
644
|
+
writer.write_line("_tt_append(_tt_tmp)", self.line)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
class _Module(_Expression):
|
|
648
|
+
def __init__(self, expression, line):
|
|
649
|
+
super().__init__("_tt_modules." + expression, line, raw=True)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
class _Text(_Node):
|
|
653
|
+
def __init__(self, value, line, whitespace):
|
|
654
|
+
self.value = value
|
|
655
|
+
self.line = line
|
|
656
|
+
self.whitespace = whitespace
|
|
657
|
+
|
|
658
|
+
def generate(self, writer):
|
|
659
|
+
value = self.value
|
|
660
|
+
|
|
661
|
+
# Compress whitespace if requested, with a crude heuristic to avoid
|
|
662
|
+
# altering preformatted whitespace.
|
|
663
|
+
if "<pre>" not in value:
|
|
664
|
+
value = filter_whitespace(self.whitespace, value)
|
|
665
|
+
|
|
666
|
+
if value:
|
|
667
|
+
writer.write_line("_tt_append(%r)" % escape.utf8(value), self.line)
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
class UnClosedIfError(Exception):
|
|
671
|
+
"""
|
|
672
|
+
Raised when a template contains {% if %} that are not being closed
|
|
673
|
+
"""
|
|
674
|
+
|
|
675
|
+
def __init__(self, node: str, lineno: int, sql: str):
|
|
676
|
+
self.node = node
|
|
677
|
+
self.lineno = lineno
|
|
678
|
+
self.sql = sql
|
|
679
|
+
self._text = sql
|
|
680
|
+
|
|
681
|
+
def __str__(self):
|
|
682
|
+
# TODO: Maybe we should pass if it's we are being called from the UI or CLI
|
|
683
|
+
# When we have the node name is because we are using this from the CLI and we want to identify better the node responsable
|
|
684
|
+
if self.node != "<string>":
|
|
685
|
+
return "Missing {%% end %%} block for if in the node %s at line %d of the SQL: %s" % (
|
|
686
|
+
self.node,
|
|
687
|
+
self.lineno,
|
|
688
|
+
self.sql,
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
return "Missing {%% end %%} block for if at line %d" % (self.lineno)
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
class ParseError(Exception):
|
|
695
|
+
"""Raised for template syntax errors.
|
|
696
|
+
|
|
697
|
+
``ParseError`` instances have ``filename`` and ``lineno`` attributes
|
|
698
|
+
indicating the position of the error.
|
|
699
|
+
|
|
700
|
+
.. versionchanged:: 4.3
|
|
701
|
+
Added ``filename`` and ``lineno`` attributes.
|
|
702
|
+
"""
|
|
703
|
+
|
|
704
|
+
def __init__(self, message, filename=None, lineno=0, text=None):
|
|
705
|
+
self.message = message
|
|
706
|
+
# The names "filename" and "lineno" are chosen for consistency
|
|
707
|
+
# with python SyntaxError.
|
|
708
|
+
self.filename = filename
|
|
709
|
+
self.lineno = lineno
|
|
710
|
+
self._text = text
|
|
711
|
+
|
|
712
|
+
def __str__(self):
|
|
713
|
+
return "%s at %s:%d" % (self.message, self.filename, self.lineno)
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
class _CodeWriter:
|
|
717
|
+
def __init__(self, file, named_blocks, loader, current_template):
|
|
718
|
+
self.file = file
|
|
719
|
+
self.named_blocks = named_blocks
|
|
720
|
+
self.loader = loader
|
|
721
|
+
self.current_template = current_template
|
|
722
|
+
self.apply_counter = 0
|
|
723
|
+
self.include_stack = []
|
|
724
|
+
self._indent = 0
|
|
725
|
+
|
|
726
|
+
def indent_size(self):
|
|
727
|
+
return self._indent
|
|
728
|
+
|
|
729
|
+
def indent(self):
|
|
730
|
+
class Indenter:
|
|
731
|
+
def __enter__(_):
|
|
732
|
+
self._indent += 1
|
|
733
|
+
return self
|
|
734
|
+
|
|
735
|
+
def __exit__(_, *args):
|
|
736
|
+
assert self._indent > 0
|
|
737
|
+
self._indent -= 1
|
|
738
|
+
|
|
739
|
+
return Indenter()
|
|
740
|
+
|
|
741
|
+
def include(self, template, line):
|
|
742
|
+
self.include_stack.append((self.current_template, line))
|
|
743
|
+
self.current_template = template
|
|
744
|
+
|
|
745
|
+
class IncludeTemplate:
|
|
746
|
+
def __enter__(_):
|
|
747
|
+
return self
|
|
748
|
+
|
|
749
|
+
def __exit__(_, *args):
|
|
750
|
+
self.current_template = self.include_stack.pop()[0]
|
|
751
|
+
|
|
752
|
+
return IncludeTemplate()
|
|
753
|
+
|
|
754
|
+
def write_line(self, line, line_number, indent=None):
|
|
755
|
+
if indent is None:
|
|
756
|
+
indent = self._indent
|
|
757
|
+
line_comment = " # %s:%d" % (self.current_template.name, line_number)
|
|
758
|
+
if self.include_stack:
|
|
759
|
+
ancestors = ["%s:%d" % (tmpl.name, lineno) for (tmpl, lineno) in self.include_stack]
|
|
760
|
+
line_comment += " (via %s)" % ", ".join(reversed(ancestors))
|
|
761
|
+
print(" " * indent + line + line_comment, file=self.file)
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
class _TemplateReader:
|
|
765
|
+
def __init__(self, name, text, whitespace):
|
|
766
|
+
self.name = name
|
|
767
|
+
self.text = text
|
|
768
|
+
self.whitespace = whitespace
|
|
769
|
+
self.line = 1
|
|
770
|
+
self.pos = 0
|
|
771
|
+
|
|
772
|
+
def find(self, needle, start=0, end=None):
|
|
773
|
+
assert start >= 0, start
|
|
774
|
+
pos = self.pos
|
|
775
|
+
start += pos
|
|
776
|
+
if end is None:
|
|
777
|
+
index = self.text.find(needle, start)
|
|
778
|
+
else:
|
|
779
|
+
end += pos
|
|
780
|
+
assert end >= start
|
|
781
|
+
index = self.text.find(needle, start, end)
|
|
782
|
+
if index != -1:
|
|
783
|
+
index -= pos
|
|
784
|
+
return index
|
|
785
|
+
|
|
786
|
+
def consume(self, count=None):
|
|
787
|
+
if count is None:
|
|
788
|
+
count = len(self.text) - self.pos
|
|
789
|
+
newpos = self.pos + count
|
|
790
|
+
self.line += self.text.count("\n", self.pos, newpos)
|
|
791
|
+
s = self.text[self.pos : newpos]
|
|
792
|
+
self.pos = newpos
|
|
793
|
+
return s
|
|
794
|
+
|
|
795
|
+
def remaining(self):
|
|
796
|
+
return len(self.text) - self.pos
|
|
797
|
+
|
|
798
|
+
def __len__(self):
|
|
799
|
+
return self.remaining()
|
|
800
|
+
|
|
801
|
+
def __getitem__(self, key):
|
|
802
|
+
if type(key) is slice:
|
|
803
|
+
size = len(self)
|
|
804
|
+
start, stop, step = key.indices(size)
|
|
805
|
+
if start is None:
|
|
806
|
+
start = self.pos
|
|
807
|
+
else:
|
|
808
|
+
start += self.pos
|
|
809
|
+
if stop is not None:
|
|
810
|
+
stop += self.pos
|
|
811
|
+
return self.text[slice(start, stop, step)]
|
|
812
|
+
elif key < 0:
|
|
813
|
+
return self.text[key]
|
|
814
|
+
else:
|
|
815
|
+
return self.text[self.pos + key]
|
|
816
|
+
|
|
817
|
+
def __str__(self):
|
|
818
|
+
return self.text[self.pos :]
|
|
819
|
+
|
|
820
|
+
def raise_parse_error(self, msg):
|
|
821
|
+
raise ParseError(msg, self.name, self.line, self.text)
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def _format_code(code):
|
|
825
|
+
lines = code.splitlines()
|
|
826
|
+
format = "%%%dd %%s\n" % len(repr(len(lines) + 1))
|
|
827
|
+
return "".join([format % (i + 1, line) for (i, line) in enumerate(lines)])
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def _parse(reader: _TemplateReader, template, in_block=None, in_loop=None):
|
|
831
|
+
body = _ChunkList([])
|
|
832
|
+
while True:
|
|
833
|
+
# Find next template directive
|
|
834
|
+
curly = 0
|
|
835
|
+
while True:
|
|
836
|
+
curly = reader.find("{", curly)
|
|
837
|
+
if curly == -1 or curly + 1 == reader.remaining():
|
|
838
|
+
# EOF
|
|
839
|
+
if in_block:
|
|
840
|
+
raise UnClosedIfError(node=reader.name, lineno=reader.line, sql=reader.text)
|
|
841
|
+
body.chunks.append(_Text(reader.consume(), reader.line, reader.whitespace))
|
|
842
|
+
return body
|
|
843
|
+
# If the first curly brace is not the start of a special token,
|
|
844
|
+
# start searching from the character after it
|
|
845
|
+
if reader[curly + 1] not in ("{", "%", "#"):
|
|
846
|
+
curly += 1
|
|
847
|
+
continue
|
|
848
|
+
# When there are more than 2 curlies in a row, use the
|
|
849
|
+
# innermost ones. This is useful when generating languages
|
|
850
|
+
# like latex where curlies are also meaningful
|
|
851
|
+
if curly + 2 < reader.remaining() and reader[curly + 1] == "{" and reader[curly + 2] == "{":
|
|
852
|
+
curly += 1
|
|
853
|
+
continue
|
|
854
|
+
break
|
|
855
|
+
|
|
856
|
+
# Append any text before the special token
|
|
857
|
+
if curly > 0:
|
|
858
|
+
cons = reader.consume(curly)
|
|
859
|
+
body.chunks.append(_Text(cons, reader.line, reader.whitespace))
|
|
860
|
+
|
|
861
|
+
start_brace = reader.consume(2)
|
|
862
|
+
line = reader.line
|
|
863
|
+
|
|
864
|
+
# Template directives may be escaped as "{{!" or "{%!".
|
|
865
|
+
# In this case output the braces and consume the "!".
|
|
866
|
+
# This is especially useful in conjunction with jquery templates,
|
|
867
|
+
# which also use double braces.
|
|
868
|
+
if reader.remaining() and reader[0] == "!":
|
|
869
|
+
reader.consume(1)
|
|
870
|
+
body.chunks.append(_Text(start_brace, line, reader.whitespace))
|
|
871
|
+
continue
|
|
872
|
+
|
|
873
|
+
# Comment
|
|
874
|
+
if start_brace == "{#":
|
|
875
|
+
end = reader.find("#}")
|
|
876
|
+
if end == -1:
|
|
877
|
+
reader.raise_parse_error("Missing end comment #}")
|
|
878
|
+
contents = reader.consume(end).strip()
|
|
879
|
+
reader.consume(2)
|
|
880
|
+
continue
|
|
881
|
+
|
|
882
|
+
# Expression
|
|
883
|
+
if start_brace == "{{":
|
|
884
|
+
end = reader.find("}}")
|
|
885
|
+
if end == -1:
|
|
886
|
+
reader.raise_parse_error("Missing end expression }}")
|
|
887
|
+
contents = reader.consume(end).strip()
|
|
888
|
+
reader.consume(2)
|
|
889
|
+
if not contents:
|
|
890
|
+
reader.raise_parse_error("Empty expression")
|
|
891
|
+
|
|
892
|
+
try:
|
|
893
|
+
body.chunks.append(_Expression(contents, line))
|
|
894
|
+
except SyntaxError:
|
|
895
|
+
operator, _, _ = contents.partition(" ")
|
|
896
|
+
|
|
897
|
+
if "from" in operator:
|
|
898
|
+
reader.raise_parse_error('"from" is a forbidden word')
|
|
899
|
+
raise
|
|
900
|
+
continue
|
|
901
|
+
|
|
902
|
+
# Block
|
|
903
|
+
assert start_brace == "{%", start_brace
|
|
904
|
+
end = reader.find("%}")
|
|
905
|
+
if end == -1:
|
|
906
|
+
reader.raise_parse_error("Missing end block %}")
|
|
907
|
+
contents = reader.consume(end).strip()
|
|
908
|
+
reader.consume(2)
|
|
909
|
+
if not contents:
|
|
910
|
+
reader.raise_parse_error("Empty block tag ({% %})")
|
|
911
|
+
|
|
912
|
+
operator, space, suffix = contents.partition(" ")
|
|
913
|
+
suffix = suffix.strip()
|
|
914
|
+
|
|
915
|
+
# Intermediate ("else", "elif", etc) blocks
|
|
916
|
+
intermediate_blocks = {
|
|
917
|
+
"else": set(["if", "for", "while", "try"]),
|
|
918
|
+
"elif": set(["if"]),
|
|
919
|
+
"except": set(["try"]),
|
|
920
|
+
"finally": set(["try"]),
|
|
921
|
+
}
|
|
922
|
+
allowed_parents = intermediate_blocks.get(operator)
|
|
923
|
+
|
|
924
|
+
block: Union[_Statement, _ControlBlock]
|
|
925
|
+
if allowed_parents is not None:
|
|
926
|
+
if not in_block:
|
|
927
|
+
reader.raise_parse_error("%s outside %s block" % (operator, allowed_parents))
|
|
928
|
+
if in_block not in allowed_parents:
|
|
929
|
+
reader.raise_parse_error("%s block cannot be attached to %s block" % (operator, in_block))
|
|
930
|
+
body.chunks.append(_IntermediateControlBlock(contents, line))
|
|
931
|
+
continue
|
|
932
|
+
|
|
933
|
+
# End tag
|
|
934
|
+
elif operator == "end":
|
|
935
|
+
if not in_block:
|
|
936
|
+
reader.raise_parse_error("Extra {% end %} block")
|
|
937
|
+
return body
|
|
938
|
+
|
|
939
|
+
elif operator in (
|
|
940
|
+
"extends",
|
|
941
|
+
"include",
|
|
942
|
+
"set",
|
|
943
|
+
"import",
|
|
944
|
+
"from",
|
|
945
|
+
"comment",
|
|
946
|
+
"autoescape",
|
|
947
|
+
"whitespace",
|
|
948
|
+
"raw",
|
|
949
|
+
"module",
|
|
950
|
+
):
|
|
951
|
+
if operator == "comment":
|
|
952
|
+
continue
|
|
953
|
+
if operator == "extends":
|
|
954
|
+
reader.raise_parse_error("extends is forbidden")
|
|
955
|
+
elif operator in ("import", "from"):
|
|
956
|
+
reader.raise_parse_error("import is forbidden")
|
|
957
|
+
elif operator == "include":
|
|
958
|
+
reader.raise_parse_error("include is forbidden")
|
|
959
|
+
elif operator == "set":
|
|
960
|
+
if not suffix:
|
|
961
|
+
reader.raise_parse_error("set missing statement")
|
|
962
|
+
block = _Statement(suffix, line)
|
|
963
|
+
elif operator == "autoescape":
|
|
964
|
+
reader.raise_parse_error("autoescape is forbidden")
|
|
965
|
+
elif operator == "whitespace":
|
|
966
|
+
mode = suffix.strip()
|
|
967
|
+
# Validate the selected mode
|
|
968
|
+
filter_whitespace(mode, "")
|
|
969
|
+
reader.whitespace = mode
|
|
970
|
+
continue
|
|
971
|
+
elif operator == "raw":
|
|
972
|
+
reader.raise_parse_error("raw is forbidden")
|
|
973
|
+
elif operator == "module":
|
|
974
|
+
reader.raise_parse_error("module is forbidden")
|
|
975
|
+
body.chunks.append(block)
|
|
976
|
+
continue
|
|
977
|
+
|
|
978
|
+
elif operator in ("apply", "block", "try", "if", "for", "while"):
|
|
979
|
+
# parse inner body recursively
|
|
980
|
+
if operator in ("for", "while"):
|
|
981
|
+
block_body = _parse(reader, template, operator, operator)
|
|
982
|
+
elif operator == "apply":
|
|
983
|
+
reader.raise_parse_error("apply is forbidden")
|
|
984
|
+
else:
|
|
985
|
+
block_body = _parse(reader, template, operator, in_loop)
|
|
986
|
+
|
|
987
|
+
if operator == "apply":
|
|
988
|
+
reader.raise_parse_error("apply is forbidden")
|
|
989
|
+
elif operator == "block":
|
|
990
|
+
reader.raise_parse_error("block is forbidden")
|
|
991
|
+
else:
|
|
992
|
+
block = _ControlBlock(contents, line, block_body)
|
|
993
|
+
body.chunks.append(block)
|
|
994
|
+
continue
|
|
995
|
+
|
|
996
|
+
elif operator in ("break", "continue"):
|
|
997
|
+
if not in_loop:
|
|
998
|
+
reader.raise_parse_error("%s outside %s block" % (operator, set(["for", "while"])))
|
|
999
|
+
body.chunks.append(_Statement(contents, line))
|
|
1000
|
+
continue
|
|
1001
|
+
|
|
1002
|
+
else:
|
|
1003
|
+
reader.raise_parse_error("unknown operator: %r" % operator)
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
VALID_CUSTOM_FUNCTION_NAMES = {
|
|
1007
|
+
"defined",
|
|
1008
|
+
"column",
|
|
1009
|
+
"columns",
|
|
1010
|
+
"day_diff",
|
|
1011
|
+
"date_diff_in_seconds",
|
|
1012
|
+
"date_diff_in_minutes",
|
|
1013
|
+
"date_diff_in_hours",
|
|
1014
|
+
"date_diff_in_days",
|
|
1015
|
+
"split_to_array",
|
|
1016
|
+
"enumerate_with_last",
|
|
1017
|
+
"sql_and",
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
VALID_FUNCTION_NAMES = {
|
|
1021
|
+
"Boolean",
|
|
1022
|
+
"DateTime",
|
|
1023
|
+
"DateTime64",
|
|
1024
|
+
"Date",
|
|
1025
|
+
"Float32",
|
|
1026
|
+
"Float64",
|
|
1027
|
+
"Int8",
|
|
1028
|
+
"Int16",
|
|
1029
|
+
"Int32",
|
|
1030
|
+
"Int64",
|
|
1031
|
+
"Int128",
|
|
1032
|
+
"Int256",
|
|
1033
|
+
"UInt8",
|
|
1034
|
+
"UInt16",
|
|
1035
|
+
"UInt32",
|
|
1036
|
+
"UInt64",
|
|
1037
|
+
"UInt128",
|
|
1038
|
+
"UInt256",
|
|
1039
|
+
"String",
|
|
1040
|
+
"Array",
|
|
1041
|
+
"symbol",
|
|
1042
|
+
"cache_ttl",
|
|
1043
|
+
"error",
|
|
1044
|
+
"custom_error",
|
|
1045
|
+
"backend_hint",
|
|
1046
|
+
"activate",
|
|
1047
|
+
"sql_unescape",
|
|
1048
|
+
"max_threads",
|
|
1049
|
+
"tb_secret",
|
|
1050
|
+
"tb_var",
|
|
1051
|
+
"Int",
|
|
1052
|
+
"table",
|
|
1053
|
+
"TABLE",
|
|
1054
|
+
"len",
|
|
1055
|
+
"list",
|
|
1056
|
+
"min",
|
|
1057
|
+
"max",
|
|
1058
|
+
"Integer",
|
|
1059
|
+
"int",
|
|
1060
|
+
"float",
|
|
1061
|
+
"JSON",
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
VALID_FUNCTION_NAMES.update(VALID_CUSTOM_FUNCTION_NAMES)
|
|
1065
|
+
|
|
1066
|
+
VALID_METHOD_NAMES = {"split", "get", "join", "replace"}
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
class SecurityException(Exception):
|
|
1070
|
+
pass
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def check_valid_code(code):
|
|
1074
|
+
"""
|
|
1075
|
+
>>> check_valid_code('''888**99 / 888**999998''')
|
|
1076
|
+
Traceback (most recent call last):
|
|
1077
|
+
...
|
|
1078
|
+
tinybird.tornado_template.SecurityException: Invalid BinOp: Div()
|
|
1079
|
+
>>> check_valid_code('''len([1] * 10**7)''')
|
|
1080
|
+
Traceback (most recent call last):
|
|
1081
|
+
...
|
|
1082
|
+
tinybird.tornado_template.SecurityException: Invalid BinOp: Pow()
|
|
1083
|
+
>>> check_valid_code('''len([1] * 10**7)''')
|
|
1084
|
+
Traceback (most recent call last):
|
|
1085
|
+
...
|
|
1086
|
+
tinybird.tornado_template.SecurityException: Invalid BinOp: Pow()
|
|
1087
|
+
>>> check_valid_code('''eval("1+1")''')
|
|
1088
|
+
Traceback (most recent call last):
|
|
1089
|
+
...
|
|
1090
|
+
tinybird.tornado_template.SecurityException: Invalid function name: eval
|
|
1091
|
+
>>> check_valid_code('''globals()''')
|
|
1092
|
+
Traceback (most recent call last):
|
|
1093
|
+
...
|
|
1094
|
+
tinybird.tornado_template.SecurityException: Invalid function name: globals
|
|
1095
|
+
>>> check_valid_code('''dir(globals()["__builtins__"])''')
|
|
1096
|
+
Traceback (most recent call last):
|
|
1097
|
+
...
|
|
1098
|
+
tinybird.tornado_template.SecurityException: Invalid function name: dir
|
|
1099
|
+
>>> check_valid_code('''globals()["__builtins__"]["open"]("/etc/passwd").read()''')
|
|
1100
|
+
Traceback (most recent call last):
|
|
1101
|
+
...
|
|
1102
|
+
tinybird.tornado_template.SecurityException: Invalid method name: read
|
|
1103
|
+
>>> check_valid_code('''globals()["__builtins__"]["__import__"]('os').popen("ls /").read()''')
|
|
1104
|
+
Traceback (most recent call last):
|
|
1105
|
+
...
|
|
1106
|
+
tinybird.tornado_template.SecurityException: Invalid method name: read
|
|
1107
|
+
>>> check_valid_code('''globals.__self__''')
|
|
1108
|
+
Traceback (most recent call last):
|
|
1109
|
+
...
|
|
1110
|
+
tinybird.tornado_template.SecurityException: Invalid expression type: Attribute(value=Name(id='globals', ctx=Load()), attr='__self__', ctx=Load())
|
|
1111
|
+
>>> check_valid_code('''dir.__self__''')
|
|
1112
|
+
Traceback (most recent call last):
|
|
1113
|
+
...
|
|
1114
|
+
tinybird.tornado_template.SecurityException: Invalid expression type: Attribute(value=Name(id='dir', ctx=Load()), attr='__self__', ctx=Load())
|
|
1115
|
+
>>> check_valid_code('''len.__self__''')
|
|
1116
|
+
Traceback (most recent call last):
|
|
1117
|
+
...
|
|
1118
|
+
tinybird.tornado_template.SecurityException: Invalid expression type: Attribute(value=Name(id='len', ctx=Load()), attr='__self__', ctx=Load())
|
|
1119
|
+
"""
|
|
1120
|
+
body = ast.parse(code).body
|
|
1121
|
+
for expr in body:
|
|
1122
|
+
check_valid_expr(expr)
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
def check_valid_expr(expr):
|
|
1126
|
+
while isinstance(expr, ast.Expr):
|
|
1127
|
+
expr = expr.value
|
|
1128
|
+
if isinstance(expr, ast.Call):
|
|
1129
|
+
if isinstance(expr.func, ast.Name):
|
|
1130
|
+
if expr.func.id not in VALID_FUNCTION_NAMES:
|
|
1131
|
+
raise SecurityException(f"Invalid function name: {expr.func.id}")
|
|
1132
|
+
elif isinstance(expr.func, ast.Call):
|
|
1133
|
+
check_valid_expr(expr.func)
|
|
1134
|
+
elif isinstance(expr.func, ast.Attribute):
|
|
1135
|
+
if expr.func.attr not in VALID_METHOD_NAMES:
|
|
1136
|
+
raise SecurityException(f"Invalid method name: {expr.func.attr}")
|
|
1137
|
+
check_valid_expr(expr.func.value)
|
|
1138
|
+
else:
|
|
1139
|
+
raise SecurityException(f"Invalid function: {ast.dump(expr)}")
|
|
1140
|
+
for subexpr in expr.args:
|
|
1141
|
+
check_valid_expr(subexpr)
|
|
1142
|
+
elif isinstance(expr, ast.Constant):
|
|
1143
|
+
if isinstance(expr.value, int):
|
|
1144
|
+
return
|
|
1145
|
+
if isinstance(expr.value, float):
|
|
1146
|
+
return
|
|
1147
|
+
if isinstance(expr.value, str):
|
|
1148
|
+
return
|
|
1149
|
+
if isinstance(expr.value, type(None)):
|
|
1150
|
+
return
|
|
1151
|
+
raise SecurityException(f"Invalid Constant: {ast.dump(expr)}")
|
|
1152
|
+
elif isinstance(expr, ast.Name):
|
|
1153
|
+
return
|
|
1154
|
+
elif isinstance(expr, ast.UnaryOp):
|
|
1155
|
+
if not isinstance(expr.op, ast.USub) and not isinstance(expr.op, ast.Not):
|
|
1156
|
+
raise SecurityException(f"Invalid UnaryOp: {ast.dump(expr.op)}")
|
|
1157
|
+
check_valid_expr(expr.operand)
|
|
1158
|
+
elif isinstance(expr, ast.BinOp):
|
|
1159
|
+
if not isinstance(expr.op, ast.Add) and not isinstance(expr.op, ast.Mult) and not isinstance(expr.op, ast.Sub):
|
|
1160
|
+
raise SecurityException(f"Invalid BinOp: {ast.dump(expr.op)}")
|
|
1161
|
+
check_valid_expr(expr.left)
|
|
1162
|
+
check_valid_expr(expr.right)
|
|
1163
|
+
elif isinstance(expr, ast.Subscript):
|
|
1164
|
+
check_valid_expr(expr.value)
|
|
1165
|
+
if isinstance(expr.slice, ast.Index):
|
|
1166
|
+
check_valid_expr(expr.slice.value) # type: ignore[attr-defined]
|
|
1167
|
+
elif isinstance(expr.slice, ast.Slice):
|
|
1168
|
+
if expr.slice.lower is not None:
|
|
1169
|
+
check_valid_expr(expr.slice.lower)
|
|
1170
|
+
if expr.slice.upper is not None:
|
|
1171
|
+
check_valid_expr(expr.slice.upper)
|
|
1172
|
+
elif isinstance(expr.slice, ast.Constant) or isinstance(expr.slice, ast.Subscript):
|
|
1173
|
+
check_valid_expr(expr.slice)
|
|
1174
|
+
else:
|
|
1175
|
+
raise SecurityException(f"Invalid Slice expression: {ast.dump(expr.slice)}")
|
|
1176
|
+
elif isinstance(expr, ast.Dict):
|
|
1177
|
+
for key in expr.keys:
|
|
1178
|
+
check_valid_expr(key)
|
|
1179
|
+
for value in expr.values:
|
|
1180
|
+
check_valid_expr(value)
|
|
1181
|
+
elif isinstance(expr, ast.Tuple) or isinstance(expr, ast.List) or isinstance(expr, ast.Set):
|
|
1182
|
+
for x in expr.elts:
|
|
1183
|
+
check_valid_expr(x)
|
|
1184
|
+
elif isinstance(expr, ast.JoinedStr):
|
|
1185
|
+
for x in expr.values:
|
|
1186
|
+
check_valid_expr(x)
|
|
1187
|
+
elif isinstance(expr, ast.FormattedValue):
|
|
1188
|
+
check_valid_expr(expr.value)
|
|
1189
|
+
elif isinstance(expr, ast.IfExp):
|
|
1190
|
+
check_valid_expr(expr.test)
|
|
1191
|
+
check_valid_expr(expr.body)
|
|
1192
|
+
check_valid_expr(expr.orelse)
|
|
1193
|
+
else:
|
|
1194
|
+
raise SecurityException(f"Invalid expression type: {ast.dump(expr)}")
|