Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- wemm/lib/python3.10/asyncio/base_tasks.py +85 -0
- wemm/lib/python3.10/asyncio/exceptions.py +58 -0
- wemm/lib/python3.10/asyncio/locks.py +438 -0
- wemm/lib/python3.10/asyncio/mixins.py +31 -0
- wemm/lib/python3.10/asyncio/protocols.py +216 -0
- wemm/lib/python3.10/asyncio/tasks.py +946 -0
- wemm/lib/python3.10/asyncio/threads.py +25 -0
- wemm/lib/python3.10/asyncio/windows_utils.py +173 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/__init__.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/_identifier.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/async_utils.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/bccache.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/defaults.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/exceptions.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/filters.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/loaders.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/optimizer.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/parser.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/runtime.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/__pycache__/visitor.cpython-310.pyc +0 -0
- wemm/lib/python3.10/site-packages/jinja2/_identifier.py +6 -0
- wemm/lib/python3.10/site-packages/jinja2/debug.py +191 -0
- wemm/lib/python3.10/site-packages/jinja2/environment.py +1672 -0
- wemm/lib/python3.10/site-packages/jinja2/filters.py +1878 -0
- wemm/lib/python3.10/site-packages/jinja2/idtracking.py +318 -0
- wemm/lib/python3.10/site-packages/jinja2/loaders.py +693 -0
- wemm/lib/python3.10/site-packages/jinja2/nodes.py +1206 -0
- wemm/lib/python3.10/site-packages/jinja2/parser.py +1049 -0
- wemm/lib/python3.10/site-packages/jinja2/runtime.py +1062 -0
- wemm/lib/python3.10/site-packages/jinja2/sandbox.py +436 -0
- wemm/lib/python3.10/site-packages/jinja2/tests.py +256 -0
- wemm/lib/python3.10/site-packages/jinja2/utils.py +766 -0
- wemm/lib/python3.10/site-packages/lightning_utilities-0.11.9.dist-info/METADATA +177 -0
- wemm/lib/python3.10/site-packages/multidict-6.1.0.dist-info/RECORD +20 -0
- wemm/lib/python3.10/site-packages/networkx-3.4.2.dist-info/INSTALLER +1 -0
- wemm/lib/python3.10/site-packages/networkx-3.4.2.dist-info/METADATA +165 -0
.gitattributes
CHANGED
|
@@ -233,3 +233,5 @@ wemm/lib/python3.10/site-packages/setuptools/_vendor/__pycache__/typing_extensio
|
|
| 233 |
wemm/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 234 |
wemm/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 235 |
wemm/lib/python3.10/site-packages/numpy/core/tests/__pycache__/test_umath.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 233 |
wemm/lib/python3.10/site-packages/numpy/ma/__pycache__/core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 234 |
wemm/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 235 |
wemm/lib/python3.10/site-packages/numpy/core/tests/__pycache__/test_umath.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 236 |
+
wemm/lib/python3.10/site-packages/numpy/core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 237 |
+
wemm/lib/python3.10/site-packages/numpy/core/__pycache__/fromnumeric.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
wemm/lib/python3.10/asyncio/base_tasks.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import linecache
|
| 2 |
+
import traceback
|
| 3 |
+
|
| 4 |
+
from . import base_futures
|
| 5 |
+
from . import coroutines
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _task_repr_info(task):
|
| 9 |
+
info = base_futures._future_repr_info(task)
|
| 10 |
+
|
| 11 |
+
if task._must_cancel:
|
| 12 |
+
# replace status
|
| 13 |
+
info[0] = 'cancelling'
|
| 14 |
+
|
| 15 |
+
info.insert(1, 'name=%r' % task.get_name())
|
| 16 |
+
|
| 17 |
+
coro = coroutines._format_coroutine(task._coro)
|
| 18 |
+
info.insert(2, f'coro=<{coro}>')
|
| 19 |
+
|
| 20 |
+
if task._fut_waiter is not None:
|
| 21 |
+
info.insert(3, f'wait_for={task._fut_waiter!r}')
|
| 22 |
+
return info
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _task_get_stack(task, limit):
|
| 26 |
+
frames = []
|
| 27 |
+
if hasattr(task._coro, 'cr_frame'):
|
| 28 |
+
# case 1: 'async def' coroutines
|
| 29 |
+
f = task._coro.cr_frame
|
| 30 |
+
elif hasattr(task._coro, 'gi_frame'):
|
| 31 |
+
# case 2: legacy coroutines
|
| 32 |
+
f = task._coro.gi_frame
|
| 33 |
+
elif hasattr(task._coro, 'ag_frame'):
|
| 34 |
+
# case 3: async generators
|
| 35 |
+
f = task._coro.ag_frame
|
| 36 |
+
else:
|
| 37 |
+
# case 4: unknown objects
|
| 38 |
+
f = None
|
| 39 |
+
if f is not None:
|
| 40 |
+
while f is not None:
|
| 41 |
+
if limit is not None:
|
| 42 |
+
if limit <= 0:
|
| 43 |
+
break
|
| 44 |
+
limit -= 1
|
| 45 |
+
frames.append(f)
|
| 46 |
+
f = f.f_back
|
| 47 |
+
frames.reverse()
|
| 48 |
+
elif task._exception is not None:
|
| 49 |
+
tb = task._exception.__traceback__
|
| 50 |
+
while tb is not None:
|
| 51 |
+
if limit is not None:
|
| 52 |
+
if limit <= 0:
|
| 53 |
+
break
|
| 54 |
+
limit -= 1
|
| 55 |
+
frames.append(tb.tb_frame)
|
| 56 |
+
tb = tb.tb_next
|
| 57 |
+
return frames
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _task_print_stack(task, limit, file):
|
| 61 |
+
extracted_list = []
|
| 62 |
+
checked = set()
|
| 63 |
+
for f in task.get_stack(limit=limit):
|
| 64 |
+
lineno = f.f_lineno
|
| 65 |
+
co = f.f_code
|
| 66 |
+
filename = co.co_filename
|
| 67 |
+
name = co.co_name
|
| 68 |
+
if filename not in checked:
|
| 69 |
+
checked.add(filename)
|
| 70 |
+
linecache.checkcache(filename)
|
| 71 |
+
line = linecache.getline(filename, lineno, f.f_globals)
|
| 72 |
+
extracted_list.append((filename, lineno, name, line))
|
| 73 |
+
|
| 74 |
+
exc = task._exception
|
| 75 |
+
if not extracted_list:
|
| 76 |
+
print(f'No stack for {task!r}', file=file)
|
| 77 |
+
elif exc is not None:
|
| 78 |
+
print(f'Traceback for {task!r} (most recent call last):', file=file)
|
| 79 |
+
else:
|
| 80 |
+
print(f'Stack for {task!r} (most recent call last):', file=file)
|
| 81 |
+
|
| 82 |
+
traceback.print_list(extracted_list, file=file)
|
| 83 |
+
if exc is not None:
|
| 84 |
+
for line in traceback.format_exception_only(exc.__class__, exc):
|
| 85 |
+
print(line, file=file, end='')
|
wemm/lib/python3.10/asyncio/exceptions.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""asyncio exceptions."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
|
| 5 |
+
'IncompleteReadError', 'LimitOverrunError',
|
| 6 |
+
'SendfileNotAvailableError')
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CancelledError(BaseException):
|
| 10 |
+
"""The Future or Task was cancelled."""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TimeoutError(Exception):
|
| 14 |
+
"""The operation exceeded the given deadline."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class InvalidStateError(Exception):
|
| 18 |
+
"""The operation is not allowed in this state."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SendfileNotAvailableError(RuntimeError):
|
| 22 |
+
"""Sendfile syscall is not available.
|
| 23 |
+
|
| 24 |
+
Raised if OS does not support sendfile syscall for given socket or
|
| 25 |
+
file type.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class IncompleteReadError(EOFError):
|
| 30 |
+
"""
|
| 31 |
+
Incomplete read error. Attributes:
|
| 32 |
+
|
| 33 |
+
- partial: read bytes string before the end of stream was reached
|
| 34 |
+
- expected: total number of expected bytes (or None if unknown)
|
| 35 |
+
"""
|
| 36 |
+
def __init__(self, partial, expected):
|
| 37 |
+
r_expected = 'undefined' if expected is None else repr(expected)
|
| 38 |
+
super().__init__(f'{len(partial)} bytes read on a total of '
|
| 39 |
+
f'{r_expected} expected bytes')
|
| 40 |
+
self.partial = partial
|
| 41 |
+
self.expected = expected
|
| 42 |
+
|
| 43 |
+
def __reduce__(self):
|
| 44 |
+
return type(self), (self.partial, self.expected)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LimitOverrunError(Exception):
|
| 48 |
+
"""Reached the buffer limit while looking for a separator.
|
| 49 |
+
|
| 50 |
+
Attributes:
|
| 51 |
+
- consumed: total number of to be consumed bytes.
|
| 52 |
+
"""
|
| 53 |
+
def __init__(self, message, consumed):
|
| 54 |
+
super().__init__(message)
|
| 55 |
+
self.consumed = consumed
|
| 56 |
+
|
| 57 |
+
def __reduce__(self):
|
| 58 |
+
return type(self), (self.args[0], self.consumed)
|
wemm/lib/python3.10/asyncio/locks.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synchronization primitives."""
|
| 2 |
+
|
| 3 |
+
__all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')
|
| 4 |
+
|
| 5 |
+
import collections
|
| 6 |
+
|
| 7 |
+
from . import exceptions
|
| 8 |
+
from . import mixins
|
| 9 |
+
from . import tasks
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _ContextManagerMixin:
|
| 13 |
+
async def __aenter__(self):
|
| 14 |
+
await self.acquire()
|
| 15 |
+
# We have no use for the "as ..." clause in the with
|
| 16 |
+
# statement for locks.
|
| 17 |
+
return None
|
| 18 |
+
|
| 19 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 20 |
+
self.release()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 24 |
+
"""Primitive lock objects.
|
| 25 |
+
|
| 26 |
+
A primitive lock is a synchronization primitive that is not owned
|
| 27 |
+
by a particular coroutine when locked. A primitive lock is in one
|
| 28 |
+
of two states, 'locked' or 'unlocked'.
|
| 29 |
+
|
| 30 |
+
It is created in the unlocked state. It has two basic methods,
|
| 31 |
+
acquire() and release(). When the state is unlocked, acquire()
|
| 32 |
+
changes the state to locked and returns immediately. When the
|
| 33 |
+
state is locked, acquire() blocks until a call to release() in
|
| 34 |
+
another coroutine changes it to unlocked, then the acquire() call
|
| 35 |
+
resets it to locked and returns. The release() method should only
|
| 36 |
+
be called in the locked state; it changes the state to unlocked
|
| 37 |
+
and returns immediately. If an attempt is made to release an
|
| 38 |
+
unlocked lock, a RuntimeError will be raised.
|
| 39 |
+
|
| 40 |
+
When more than one coroutine is blocked in acquire() waiting for
|
| 41 |
+
the state to turn to unlocked, only one coroutine proceeds when a
|
| 42 |
+
release() call resets the state to unlocked; first coroutine which
|
| 43 |
+
is blocked in acquire() is being processed.
|
| 44 |
+
|
| 45 |
+
acquire() is a coroutine and should be called with 'await'.
|
| 46 |
+
|
| 47 |
+
Locks also support the asynchronous context management protocol.
|
| 48 |
+
'async with lock' statement should be used.
|
| 49 |
+
|
| 50 |
+
Usage:
|
| 51 |
+
|
| 52 |
+
lock = Lock()
|
| 53 |
+
...
|
| 54 |
+
await lock.acquire()
|
| 55 |
+
try:
|
| 56 |
+
...
|
| 57 |
+
finally:
|
| 58 |
+
lock.release()
|
| 59 |
+
|
| 60 |
+
Context manager usage:
|
| 61 |
+
|
| 62 |
+
lock = Lock()
|
| 63 |
+
...
|
| 64 |
+
async with lock:
|
| 65 |
+
...
|
| 66 |
+
|
| 67 |
+
Lock objects can be tested for locking state:
|
| 68 |
+
|
| 69 |
+
if not lock.locked():
|
| 70 |
+
await lock.acquire()
|
| 71 |
+
else:
|
| 72 |
+
# lock is acquired
|
| 73 |
+
...
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(self, *, loop=mixins._marker):
|
| 78 |
+
super().__init__(loop=loop)
|
| 79 |
+
self._waiters = None
|
| 80 |
+
self._locked = False
|
| 81 |
+
|
| 82 |
+
def __repr__(self):
|
| 83 |
+
res = super().__repr__()
|
| 84 |
+
extra = 'locked' if self._locked else 'unlocked'
|
| 85 |
+
if self._waiters:
|
| 86 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 87 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 88 |
+
|
| 89 |
+
def locked(self):
|
| 90 |
+
"""Return True if lock is acquired."""
|
| 91 |
+
return self._locked
|
| 92 |
+
|
| 93 |
+
async def acquire(self):
|
| 94 |
+
"""Acquire a lock.
|
| 95 |
+
|
| 96 |
+
This method blocks until the lock is unlocked, then sets it to
|
| 97 |
+
locked and returns True.
|
| 98 |
+
"""
|
| 99 |
+
if (not self._locked and (self._waiters is None or
|
| 100 |
+
all(w.cancelled() for w in self._waiters))):
|
| 101 |
+
self._locked = True
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
if self._waiters is None:
|
| 105 |
+
self._waiters = collections.deque()
|
| 106 |
+
fut = self._get_loop().create_future()
|
| 107 |
+
self._waiters.append(fut)
|
| 108 |
+
|
| 109 |
+
# Finally block should be called before the CancelledError
|
| 110 |
+
# handling as we don't want CancelledError to call
|
| 111 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 112 |
+
try:
|
| 113 |
+
try:
|
| 114 |
+
await fut
|
| 115 |
+
finally:
|
| 116 |
+
self._waiters.remove(fut)
|
| 117 |
+
except exceptions.CancelledError:
|
| 118 |
+
if not self._locked:
|
| 119 |
+
self._wake_up_first()
|
| 120 |
+
raise
|
| 121 |
+
|
| 122 |
+
self._locked = True
|
| 123 |
+
return True
|
| 124 |
+
|
| 125 |
+
def release(self):
|
| 126 |
+
"""Release a lock.
|
| 127 |
+
|
| 128 |
+
When the lock is locked, reset it to unlocked, and return.
|
| 129 |
+
If any other coroutines are blocked waiting for the lock to become
|
| 130 |
+
unlocked, allow exactly one of them to proceed.
|
| 131 |
+
|
| 132 |
+
When invoked on an unlocked lock, a RuntimeError is raised.
|
| 133 |
+
|
| 134 |
+
There is no return value.
|
| 135 |
+
"""
|
| 136 |
+
if self._locked:
|
| 137 |
+
self._locked = False
|
| 138 |
+
self._wake_up_first()
|
| 139 |
+
else:
|
| 140 |
+
raise RuntimeError('Lock is not acquired.')
|
| 141 |
+
|
| 142 |
+
def _wake_up_first(self):
|
| 143 |
+
"""Wake up the first waiter if it isn't done."""
|
| 144 |
+
if not self._waiters:
|
| 145 |
+
return
|
| 146 |
+
try:
|
| 147 |
+
fut = next(iter(self._waiters))
|
| 148 |
+
except StopIteration:
|
| 149 |
+
return
|
| 150 |
+
|
| 151 |
+
# .done() necessarily means that a waiter will wake up later on and
|
| 152 |
+
# either take the lock, or, if it was cancelled and lock wasn't
|
| 153 |
+
# taken already, will hit this again and wake up a new waiter.
|
| 154 |
+
if not fut.done():
|
| 155 |
+
fut.set_result(True)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class Event(mixins._LoopBoundMixin):
|
| 159 |
+
"""Asynchronous equivalent to threading.Event.
|
| 160 |
+
|
| 161 |
+
Class implementing event objects. An event manages a flag that can be set
|
| 162 |
+
to true with the set() method and reset to false with the clear() method.
|
| 163 |
+
The wait() method blocks until the flag is true. The flag is initially
|
| 164 |
+
false.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(self, *, loop=mixins._marker):
|
| 168 |
+
super().__init__(loop=loop)
|
| 169 |
+
self._waiters = collections.deque()
|
| 170 |
+
self._value = False
|
| 171 |
+
|
| 172 |
+
def __repr__(self):
|
| 173 |
+
res = super().__repr__()
|
| 174 |
+
extra = 'set' if self._value else 'unset'
|
| 175 |
+
if self._waiters:
|
| 176 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 177 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 178 |
+
|
| 179 |
+
def is_set(self):
|
| 180 |
+
"""Return True if and only if the internal flag is true."""
|
| 181 |
+
return self._value
|
| 182 |
+
|
| 183 |
+
def set(self):
|
| 184 |
+
"""Set the internal flag to true. All coroutines waiting for it to
|
| 185 |
+
become true are awakened. Coroutine that call wait() once the flag is
|
| 186 |
+
true will not block at all.
|
| 187 |
+
"""
|
| 188 |
+
if not self._value:
|
| 189 |
+
self._value = True
|
| 190 |
+
|
| 191 |
+
for fut in self._waiters:
|
| 192 |
+
if not fut.done():
|
| 193 |
+
fut.set_result(True)
|
| 194 |
+
|
| 195 |
+
def clear(self):
|
| 196 |
+
"""Reset the internal flag to false. Subsequently, coroutines calling
|
| 197 |
+
wait() will block until set() is called to set the internal flag
|
| 198 |
+
to true again."""
|
| 199 |
+
self._value = False
|
| 200 |
+
|
| 201 |
+
async def wait(self):
|
| 202 |
+
"""Block until the internal flag is true.
|
| 203 |
+
|
| 204 |
+
If the internal flag is true on entry, return True
|
| 205 |
+
immediately. Otherwise, block until another coroutine calls
|
| 206 |
+
set() to set the flag to true, then return True.
|
| 207 |
+
"""
|
| 208 |
+
if self._value:
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
fut = self._get_loop().create_future()
|
| 212 |
+
self._waiters.append(fut)
|
| 213 |
+
try:
|
| 214 |
+
await fut
|
| 215 |
+
return True
|
| 216 |
+
finally:
|
| 217 |
+
self._waiters.remove(fut)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 221 |
+
"""Asynchronous equivalent to threading.Condition.
|
| 222 |
+
|
| 223 |
+
This class implements condition variable objects. A condition variable
|
| 224 |
+
allows one or more coroutines to wait until they are notified by another
|
| 225 |
+
coroutine.
|
| 226 |
+
|
| 227 |
+
A new Lock object is created and used as the underlying lock.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def __init__(self, lock=None, *, loop=mixins._marker):
|
| 231 |
+
super().__init__(loop=loop)
|
| 232 |
+
if lock is None:
|
| 233 |
+
lock = Lock()
|
| 234 |
+
|
| 235 |
+
self._lock = lock
|
| 236 |
+
# Export the lock's locked(), acquire() and release() methods.
|
| 237 |
+
self.locked = lock.locked
|
| 238 |
+
self.acquire = lock.acquire
|
| 239 |
+
self.release = lock.release
|
| 240 |
+
|
| 241 |
+
self._waiters = collections.deque()
|
| 242 |
+
|
| 243 |
+
def __repr__(self):
|
| 244 |
+
res = super().__repr__()
|
| 245 |
+
extra = 'locked' if self.locked() else 'unlocked'
|
| 246 |
+
if self._waiters:
|
| 247 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 248 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 249 |
+
|
| 250 |
+
async def wait(self):
|
| 251 |
+
"""Wait until notified.
|
| 252 |
+
|
| 253 |
+
If the calling coroutine has not acquired the lock when this
|
| 254 |
+
method is called, a RuntimeError is raised.
|
| 255 |
+
|
| 256 |
+
This method releases the underlying lock, and then blocks
|
| 257 |
+
until it is awakened by a notify() or notify_all() call for
|
| 258 |
+
the same condition variable in another coroutine. Once
|
| 259 |
+
awakened, it re-acquires the lock and returns True.
|
| 260 |
+
"""
|
| 261 |
+
if not self.locked():
|
| 262 |
+
raise RuntimeError('cannot wait on un-acquired lock')
|
| 263 |
+
|
| 264 |
+
self.release()
|
| 265 |
+
try:
|
| 266 |
+
fut = self._get_loop().create_future()
|
| 267 |
+
self._waiters.append(fut)
|
| 268 |
+
try:
|
| 269 |
+
await fut
|
| 270 |
+
return True
|
| 271 |
+
finally:
|
| 272 |
+
self._waiters.remove(fut)
|
| 273 |
+
|
| 274 |
+
finally:
|
| 275 |
+
# Must reacquire lock even if wait is cancelled
|
| 276 |
+
cancelled = False
|
| 277 |
+
while True:
|
| 278 |
+
try:
|
| 279 |
+
await self.acquire()
|
| 280 |
+
break
|
| 281 |
+
except exceptions.CancelledError:
|
| 282 |
+
cancelled = True
|
| 283 |
+
|
| 284 |
+
if cancelled:
|
| 285 |
+
raise exceptions.CancelledError
|
| 286 |
+
|
| 287 |
+
async def wait_for(self, predicate):
|
| 288 |
+
"""Wait until a predicate becomes true.
|
| 289 |
+
|
| 290 |
+
The predicate should be a callable which result will be
|
| 291 |
+
interpreted as a boolean value. The final predicate value is
|
| 292 |
+
the return value.
|
| 293 |
+
"""
|
| 294 |
+
result = predicate()
|
| 295 |
+
while not result:
|
| 296 |
+
await self.wait()
|
| 297 |
+
result = predicate()
|
| 298 |
+
return result
|
| 299 |
+
|
| 300 |
+
def notify(self, n=1):
|
| 301 |
+
"""By default, wake up one coroutine waiting on this condition, if any.
|
| 302 |
+
If the calling coroutine has not acquired the lock when this method
|
| 303 |
+
is called, a RuntimeError is raised.
|
| 304 |
+
|
| 305 |
+
This method wakes up at most n of the coroutines waiting for the
|
| 306 |
+
condition variable; it is a no-op if no coroutines are waiting.
|
| 307 |
+
|
| 308 |
+
Note: an awakened coroutine does not actually return from its
|
| 309 |
+
wait() call until it can reacquire the lock. Since notify() does
|
| 310 |
+
not release the lock, its caller should.
|
| 311 |
+
"""
|
| 312 |
+
if not self.locked():
|
| 313 |
+
raise RuntimeError('cannot notify on un-acquired lock')
|
| 314 |
+
|
| 315 |
+
idx = 0
|
| 316 |
+
for fut in self._waiters:
|
| 317 |
+
if idx >= n:
|
| 318 |
+
break
|
| 319 |
+
|
| 320 |
+
if not fut.done():
|
| 321 |
+
idx += 1
|
| 322 |
+
fut.set_result(False)
|
| 323 |
+
|
| 324 |
+
def notify_all(self):
|
| 325 |
+
"""Wake up all threads waiting on this condition. This method acts
|
| 326 |
+
like notify(), but wakes up all waiting threads instead of one. If the
|
| 327 |
+
calling thread has not acquired the lock when this method is called,
|
| 328 |
+
a RuntimeError is raised.
|
| 329 |
+
"""
|
| 330 |
+
self.notify(len(self._waiters))
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 334 |
+
"""A Semaphore implementation.
|
| 335 |
+
|
| 336 |
+
A semaphore manages an internal counter which is decremented by each
|
| 337 |
+
acquire() call and incremented by each release() call. The counter
|
| 338 |
+
can never go below zero; when acquire() finds that it is zero, it blocks,
|
| 339 |
+
waiting until some other thread calls release().
|
| 340 |
+
|
| 341 |
+
Semaphores also support the context management protocol.
|
| 342 |
+
|
| 343 |
+
The optional argument gives the initial value for the internal
|
| 344 |
+
counter; it defaults to 1. If the value given is less than 0,
|
| 345 |
+
ValueError is raised.
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
def __init__(self, value=1, *, loop=mixins._marker):
|
| 349 |
+
super().__init__(loop=loop)
|
| 350 |
+
if value < 0:
|
| 351 |
+
raise ValueError("Semaphore initial value must be >= 0")
|
| 352 |
+
self._waiters = None
|
| 353 |
+
self._value = value
|
| 354 |
+
|
| 355 |
+
def __repr__(self):
|
| 356 |
+
res = super().__repr__()
|
| 357 |
+
extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
|
| 358 |
+
if self._waiters:
|
| 359 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 360 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 361 |
+
|
| 362 |
+
def locked(self):
|
| 363 |
+
"""Returns True if semaphore cannot be acquired immediately."""
|
| 364 |
+
return self._value == 0 or (
|
| 365 |
+
any(not w.cancelled() for w in (self._waiters or ())))
|
| 366 |
+
|
| 367 |
+
async def acquire(self):
|
| 368 |
+
"""Acquire a semaphore.
|
| 369 |
+
|
| 370 |
+
If the internal counter is larger than zero on entry,
|
| 371 |
+
decrement it by one and return True immediately. If it is
|
| 372 |
+
zero on entry, block, waiting until some other coroutine has
|
| 373 |
+
called release() to make it larger than 0, and then return
|
| 374 |
+
True.
|
| 375 |
+
"""
|
| 376 |
+
if not self.locked():
|
| 377 |
+
self._value -= 1
|
| 378 |
+
return True
|
| 379 |
+
|
| 380 |
+
if self._waiters is None:
|
| 381 |
+
self._waiters = collections.deque()
|
| 382 |
+
fut = self._get_loop().create_future()
|
| 383 |
+
self._waiters.append(fut)
|
| 384 |
+
|
| 385 |
+
# Finally block should be called before the CancelledError
|
| 386 |
+
# handling as we don't want CancelledError to call
|
| 387 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 388 |
+
try:
|
| 389 |
+
try:
|
| 390 |
+
await fut
|
| 391 |
+
finally:
|
| 392 |
+
self._waiters.remove(fut)
|
| 393 |
+
except exceptions.CancelledError:
|
| 394 |
+
if not fut.cancelled():
|
| 395 |
+
self._value += 1
|
| 396 |
+
self._wake_up_next()
|
| 397 |
+
raise
|
| 398 |
+
|
| 399 |
+
if self._value > 0:
|
| 400 |
+
self._wake_up_next()
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
def release(self):
|
| 404 |
+
"""Release a semaphore, incrementing the internal counter by one.
|
| 405 |
+
|
| 406 |
+
When it was zero on entry and another coroutine is waiting for it to
|
| 407 |
+
become larger than zero again, wake up that coroutine.
|
| 408 |
+
"""
|
| 409 |
+
self._value += 1
|
| 410 |
+
self._wake_up_next()
|
| 411 |
+
|
| 412 |
+
def _wake_up_next(self):
|
| 413 |
+
"""Wake up the first waiter that isn't done."""
|
| 414 |
+
if not self._waiters:
|
| 415 |
+
return
|
| 416 |
+
|
| 417 |
+
for fut in self._waiters:
|
| 418 |
+
if not fut.done():
|
| 419 |
+
self._value -= 1
|
| 420 |
+
fut.set_result(True)
|
| 421 |
+
return
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class BoundedSemaphore(Semaphore):
|
| 425 |
+
"""A bounded semaphore implementation.
|
| 426 |
+
|
| 427 |
+
This raises ValueError in release() if it would increase the value
|
| 428 |
+
above the initial value.
|
| 429 |
+
"""
|
| 430 |
+
|
| 431 |
+
def __init__(self, value=1, *, loop=mixins._marker):
|
| 432 |
+
self._bound_value = value
|
| 433 |
+
super().__init__(value, loop=loop)
|
| 434 |
+
|
| 435 |
+
def release(self):
|
| 436 |
+
if self._value >= self._bound_value:
|
| 437 |
+
raise ValueError('BoundedSemaphore released too many times')
|
| 438 |
+
super().release()
|
wemm/lib/python3.10/asyncio/mixins.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop mixins."""
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
from . import events
|
| 5 |
+
|
| 6 |
+
_global_lock = threading.Lock()
|
| 7 |
+
|
| 8 |
+
# Used as a sentinel for loop parameter
|
| 9 |
+
_marker = object()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _LoopBoundMixin:
|
| 13 |
+
_loop = None
|
| 14 |
+
|
| 15 |
+
def __init__(self, *, loop=_marker):
|
| 16 |
+
if loop is not _marker:
|
| 17 |
+
raise TypeError(
|
| 18 |
+
f'As of 3.10, the *loop* parameter was removed from '
|
| 19 |
+
f'{type(self).__name__}() since it is no longer necessary'
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def _get_loop(self):
|
| 23 |
+
loop = events._get_running_loop()
|
| 24 |
+
|
| 25 |
+
if self._loop is None:
|
| 26 |
+
with _global_lock:
|
| 27 |
+
if self._loop is None:
|
| 28 |
+
self._loop = loop
|
| 29 |
+
if loop is not self._loop:
|
| 30 |
+
raise RuntimeError(f'{self!r} is bound to a different event loop')
|
| 31 |
+
return loop
|
wemm/lib/python3.10/asyncio/protocols.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Abstract Protocol base classes."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'BaseProtocol', 'Protocol', 'DatagramProtocol',
|
| 5 |
+
'SubprocessProtocol', 'BufferedProtocol',
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class BaseProtocol:
|
| 10 |
+
"""Common base class for protocol interfaces.
|
| 11 |
+
|
| 12 |
+
Usually user implements protocols that derived from BaseProtocol
|
| 13 |
+
like Protocol or ProcessProtocol.
|
| 14 |
+
|
| 15 |
+
The only case when BaseProtocol should be implemented directly is
|
| 16 |
+
write-only transport like write pipe
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
__slots__ = ()
|
| 20 |
+
|
| 21 |
+
def connection_made(self, transport):
|
| 22 |
+
"""Called when a connection is made.
|
| 23 |
+
|
| 24 |
+
The argument is the transport representing the pipe connection.
|
| 25 |
+
To receive data, wait for data_received() calls.
|
| 26 |
+
When the connection is closed, connection_lost() is called.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def connection_lost(self, exc):
|
| 30 |
+
"""Called when the connection is lost or closed.
|
| 31 |
+
|
| 32 |
+
The argument is an exception object or None (the latter
|
| 33 |
+
meaning a regular EOF is received or the connection was
|
| 34 |
+
aborted or closed).
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def pause_writing(self):
|
| 38 |
+
"""Called when the transport's buffer goes over the high-water mark.
|
| 39 |
+
|
| 40 |
+
Pause and resume calls are paired -- pause_writing() is called
|
| 41 |
+
once when the buffer goes strictly over the high-water mark
|
| 42 |
+
(even if subsequent writes increases the buffer size even
|
| 43 |
+
more), and eventually resume_writing() is called once when the
|
| 44 |
+
buffer size reaches the low-water mark.
|
| 45 |
+
|
| 46 |
+
Note that if the buffer size equals the high-water mark,
|
| 47 |
+
pause_writing() is not called -- it must go strictly over.
|
| 48 |
+
Conversely, resume_writing() is called when the buffer size is
|
| 49 |
+
equal or lower than the low-water mark. These end conditions
|
| 50 |
+
are important to ensure that things go as expected when either
|
| 51 |
+
mark is zero.
|
| 52 |
+
|
| 53 |
+
NOTE: This is the only Protocol callback that is not called
|
| 54 |
+
through EventLoop.call_soon() -- if it were, it would have no
|
| 55 |
+
effect when it's most needed (when the app keeps writing
|
| 56 |
+
without yielding until pause_writing() is called).
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def resume_writing(self):
|
| 60 |
+
"""Called when the transport's buffer drains below the low-water mark.
|
| 61 |
+
|
| 62 |
+
See pause_writing() for details.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Protocol(BaseProtocol):
|
| 67 |
+
"""Interface for stream protocol.
|
| 68 |
+
|
| 69 |
+
The user should implement this interface. They can inherit from
|
| 70 |
+
this class but don't need to. The implementations here do
|
| 71 |
+
nothing (they don't raise exceptions).
|
| 72 |
+
|
| 73 |
+
When the user wants to requests a transport, they pass a protocol
|
| 74 |
+
factory to a utility function (e.g., EventLoop.create_connection()).
|
| 75 |
+
|
| 76 |
+
When the connection is made successfully, connection_made() is
|
| 77 |
+
called with a suitable transport object. Then data_received()
|
| 78 |
+
will be called 0 or more times with data (bytes) received from the
|
| 79 |
+
transport; finally, connection_lost() will be called exactly once
|
| 80 |
+
with either an exception object or None as an argument.
|
| 81 |
+
|
| 82 |
+
State machine of calls:
|
| 83 |
+
|
| 84 |
+
start -> CM [-> DR*] [-> ER?] -> CL -> end
|
| 85 |
+
|
| 86 |
+
* CM: connection_made()
|
| 87 |
+
* DR: data_received()
|
| 88 |
+
* ER: eof_received()
|
| 89 |
+
* CL: connection_lost()
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
__slots__ = ()
|
| 93 |
+
|
| 94 |
+
def data_received(self, data):
|
| 95 |
+
"""Called when some data is received.
|
| 96 |
+
|
| 97 |
+
The argument is a bytes object.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def eof_received(self):
|
| 101 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 102 |
+
|
| 103 |
+
If this returns a false value (including None), the transport
|
| 104 |
+
will close itself. If it returns a true value, closing the
|
| 105 |
+
transport is up to the protocol.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class BufferedProtocol(BaseProtocol):
|
| 110 |
+
"""Interface for stream protocol with manual buffer control.
|
| 111 |
+
|
| 112 |
+
Event methods, such as `create_server` and `create_connection`,
|
| 113 |
+
accept factories that return protocols that implement this interface.
|
| 114 |
+
|
| 115 |
+
The idea of BufferedProtocol is that it allows to manually allocate
|
| 116 |
+
and control the receive buffer. Event loops can then use the buffer
|
| 117 |
+
provided by the protocol to avoid unnecessary data copies. This
|
| 118 |
+
can result in noticeable performance improvement for protocols that
|
| 119 |
+
receive big amounts of data. Sophisticated protocols can allocate
|
| 120 |
+
the buffer only once at creation time.
|
| 121 |
+
|
| 122 |
+
State machine of calls:
|
| 123 |
+
|
| 124 |
+
start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end
|
| 125 |
+
|
| 126 |
+
* CM: connection_made()
|
| 127 |
+
* GB: get_buffer()
|
| 128 |
+
* BU: buffer_updated()
|
| 129 |
+
* ER: eof_received()
|
| 130 |
+
* CL: connection_lost()
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
__slots__ = ()
|
| 134 |
+
|
| 135 |
+
def get_buffer(self, sizehint):
|
| 136 |
+
"""Called to allocate a new receive buffer.
|
| 137 |
+
|
| 138 |
+
*sizehint* is a recommended minimal size for the returned
|
| 139 |
+
buffer. When set to -1, the buffer size can be arbitrary.
|
| 140 |
+
|
| 141 |
+
Must return an object that implements the
|
| 142 |
+
:ref:`buffer protocol <bufferobjects>`.
|
| 143 |
+
It is an error to return a zero-sized buffer.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def buffer_updated(self, nbytes):
|
| 147 |
+
"""Called when the buffer was updated with the received data.
|
| 148 |
+
|
| 149 |
+
*nbytes* is the total number of bytes that were written to
|
| 150 |
+
the buffer.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
def eof_received(self):
|
| 154 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 155 |
+
|
| 156 |
+
If this returns a false value (including None), the transport
|
| 157 |
+
will close itself. If it returns a true value, closing the
|
| 158 |
+
transport is up to the protocol.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class DatagramProtocol(BaseProtocol):
|
| 163 |
+
"""Interface for datagram protocol."""
|
| 164 |
+
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
def datagram_received(self, data, addr):
|
| 168 |
+
"""Called when some datagram is received."""
|
| 169 |
+
|
| 170 |
+
def error_received(self, exc):
|
| 171 |
+
"""Called when a send or receive operation raises an OSError.
|
| 172 |
+
|
| 173 |
+
(Other than BlockingIOError or InterruptedError.)
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SubprocessProtocol(BaseProtocol):
|
| 178 |
+
"""Interface for protocol for subprocess calls."""
|
| 179 |
+
|
| 180 |
+
__slots__ = ()
|
| 181 |
+
|
| 182 |
+
def pipe_data_received(self, fd, data):
|
| 183 |
+
"""Called when the subprocess writes data into stdout/stderr pipe.
|
| 184 |
+
|
| 185 |
+
fd is int file descriptor.
|
| 186 |
+
data is bytes object.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
def pipe_connection_lost(self, fd, exc):
|
| 190 |
+
"""Called when a file descriptor associated with the child process is
|
| 191 |
+
closed.
|
| 192 |
+
|
| 193 |
+
fd is the int file descriptor that was closed.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
def process_exited(self):
|
| 197 |
+
"""Called when subprocess has exited."""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _feed_data_to_buffered_proto(proto, data):
|
| 201 |
+
data_len = len(data)
|
| 202 |
+
while data_len:
|
| 203 |
+
buf = proto.get_buffer(data_len)
|
| 204 |
+
buf_len = len(buf)
|
| 205 |
+
if not buf_len:
|
| 206 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 207 |
+
|
| 208 |
+
if buf_len >= data_len:
|
| 209 |
+
buf[:data_len] = data
|
| 210 |
+
proto.buffer_updated(data_len)
|
| 211 |
+
return
|
| 212 |
+
else:
|
| 213 |
+
buf[:buf_len] = data[:buf_len]
|
| 214 |
+
proto.buffer_updated(buf_len)
|
| 215 |
+
data = data[buf_len:]
|
| 216 |
+
data_len = len(data)
|
wemm/lib/python3.10/asyncio/tasks.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for tasks, coroutines and the scheduler."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'Task', 'create_task',
|
| 5 |
+
'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
|
| 6 |
+
'wait', 'wait_for', 'as_completed', 'sleep',
|
| 7 |
+
'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
|
| 8 |
+
'current_task', 'all_tasks',
|
| 9 |
+
'_register_task', '_unregister_task', '_enter_task', '_leave_task',
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
import concurrent.futures
|
| 13 |
+
import contextvars
|
| 14 |
+
import functools
|
| 15 |
+
import inspect
|
| 16 |
+
import itertools
|
| 17 |
+
import types
|
| 18 |
+
import warnings
|
| 19 |
+
import weakref
|
| 20 |
+
from types import GenericAlias
|
| 21 |
+
|
| 22 |
+
from . import base_tasks
|
| 23 |
+
from . import coroutines
|
| 24 |
+
from . import events
|
| 25 |
+
from . import exceptions
|
| 26 |
+
from . import futures
|
| 27 |
+
from .coroutines import _is_coroutine
|
| 28 |
+
|
| 29 |
+
# Helper to generate new task names
|
| 30 |
+
# This uses itertools.count() instead of a "+= 1" operation because the latter
|
| 31 |
+
# is not thread safe. See bpo-11866 for a longer explanation.
|
| 32 |
+
_task_name_counter = itertools.count(1).__next__
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def current_task(loop=None):
|
| 36 |
+
"""Return a currently executed task."""
|
| 37 |
+
if loop is None:
|
| 38 |
+
loop = events.get_running_loop()
|
| 39 |
+
return _current_tasks.get(loop)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def all_tasks(loop=None):
|
| 43 |
+
"""Return a set of all tasks for the loop."""
|
| 44 |
+
if loop is None:
|
| 45 |
+
loop = events.get_running_loop()
|
| 46 |
+
# Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
|
| 47 |
+
# thread while we do so. Therefore we cast it to list prior to filtering. The list
|
| 48 |
+
# cast itself requires iteration, so we repeat it several times ignoring
|
| 49 |
+
# RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
|
| 50 |
+
# details.
|
| 51 |
+
i = 0
|
| 52 |
+
while True:
|
| 53 |
+
try:
|
| 54 |
+
tasks = list(_all_tasks)
|
| 55 |
+
except RuntimeError:
|
| 56 |
+
i += 1
|
| 57 |
+
if i >= 1000:
|
| 58 |
+
raise
|
| 59 |
+
else:
|
| 60 |
+
break
|
| 61 |
+
return {t for t in tasks
|
| 62 |
+
if futures._get_loop(t) is loop and not t.done()}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _set_task_name(task, name):
|
| 66 |
+
if name is not None:
|
| 67 |
+
try:
|
| 68 |
+
set_name = task.set_name
|
| 69 |
+
except AttributeError:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
set_name(name)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Task(futures._PyFuture): # Inherit Python Task implementation
|
| 76 |
+
# from a Python Future implementation.
|
| 77 |
+
|
| 78 |
+
"""A coroutine wrapped in a Future."""
|
| 79 |
+
|
| 80 |
+
# An important invariant maintained while a Task not done:
|
| 81 |
+
#
|
| 82 |
+
# - Either _fut_waiter is None, and _step() is scheduled;
|
| 83 |
+
# - or _fut_waiter is some Future, and _step() is *not* scheduled.
|
| 84 |
+
#
|
| 85 |
+
# The only transition from the latter to the former is through
|
| 86 |
+
# _wakeup(). When _fut_waiter is not None, one of its callbacks
|
| 87 |
+
# must be _wakeup().
|
| 88 |
+
|
| 89 |
+
# If False, don't log a message if the task is destroyed whereas its
|
| 90 |
+
# status is still pending
|
| 91 |
+
_log_destroy_pending = True
|
| 92 |
+
|
| 93 |
+
def __init__(self, coro, *, loop=None, name=None):
|
| 94 |
+
super().__init__(loop=loop)
|
| 95 |
+
if self._source_traceback:
|
| 96 |
+
del self._source_traceback[-1]
|
| 97 |
+
if not coroutines.iscoroutine(coro):
|
| 98 |
+
# raise after Future.__init__(), attrs are required for __del__
|
| 99 |
+
# prevent logging for pending task in __del__
|
| 100 |
+
self._log_destroy_pending = False
|
| 101 |
+
raise TypeError(f"a coroutine was expected, got {coro!r}")
|
| 102 |
+
|
| 103 |
+
if name is None:
|
| 104 |
+
self._name = f'Task-{_task_name_counter()}'
|
| 105 |
+
else:
|
| 106 |
+
self._name = str(name)
|
| 107 |
+
|
| 108 |
+
self._must_cancel = False
|
| 109 |
+
self._fut_waiter = None
|
| 110 |
+
self._coro = coro
|
| 111 |
+
self._context = contextvars.copy_context()
|
| 112 |
+
|
| 113 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 114 |
+
_register_task(self)
|
| 115 |
+
|
| 116 |
+
def __del__(self):
|
| 117 |
+
if self._state == futures._PENDING and self._log_destroy_pending:
|
| 118 |
+
context = {
|
| 119 |
+
'task': self,
|
| 120 |
+
'message': 'Task was destroyed but it is pending!',
|
| 121 |
+
}
|
| 122 |
+
if self._source_traceback:
|
| 123 |
+
context['source_traceback'] = self._source_traceback
|
| 124 |
+
self._loop.call_exception_handler(context)
|
| 125 |
+
super().__del__()
|
| 126 |
+
|
| 127 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 128 |
+
|
| 129 |
+
def _repr_info(self):
|
| 130 |
+
return base_tasks._task_repr_info(self)
|
| 131 |
+
|
| 132 |
+
def get_coro(self):
|
| 133 |
+
return self._coro
|
| 134 |
+
|
| 135 |
+
def get_name(self):
|
| 136 |
+
return self._name
|
| 137 |
+
|
| 138 |
+
def set_name(self, value):
|
| 139 |
+
self._name = str(value)
|
| 140 |
+
|
| 141 |
+
def set_result(self, result):
|
| 142 |
+
raise RuntimeError('Task does not support set_result operation')
|
| 143 |
+
|
| 144 |
+
def set_exception(self, exception):
|
| 145 |
+
raise RuntimeError('Task does not support set_exception operation')
|
| 146 |
+
|
| 147 |
+
def get_stack(self, *, limit=None):
|
| 148 |
+
"""Return the list of stack frames for this task's coroutine.
|
| 149 |
+
|
| 150 |
+
If the coroutine is not done, this returns the stack where it is
|
| 151 |
+
suspended. If the coroutine has completed successfully or was
|
| 152 |
+
cancelled, this returns an empty list. If the coroutine was
|
| 153 |
+
terminated by an exception, this returns the list of traceback
|
| 154 |
+
frames.
|
| 155 |
+
|
| 156 |
+
The frames are always ordered from oldest to newest.
|
| 157 |
+
|
| 158 |
+
The optional limit gives the maximum number of frames to
|
| 159 |
+
return; by default all available frames are returned. Its
|
| 160 |
+
meaning differs depending on whether a stack or a traceback is
|
| 161 |
+
returned: the newest frames of a stack are returned, but the
|
| 162 |
+
oldest frames of a traceback are returned. (This matches the
|
| 163 |
+
behavior of the traceback module.)
|
| 164 |
+
|
| 165 |
+
For reasons beyond our control, only one stack frame is
|
| 166 |
+
returned for a suspended coroutine.
|
| 167 |
+
"""
|
| 168 |
+
return base_tasks._task_get_stack(self, limit)
|
| 169 |
+
|
| 170 |
+
def print_stack(self, *, limit=None, file=None):
|
| 171 |
+
"""Print the stack or traceback for this task's coroutine.
|
| 172 |
+
|
| 173 |
+
This produces output similar to that of the traceback module,
|
| 174 |
+
for the frames retrieved by get_stack(). The limit argument
|
| 175 |
+
is passed to get_stack(). The file argument is an I/O stream
|
| 176 |
+
to which the output is written; by default output is written
|
| 177 |
+
to sys.stderr.
|
| 178 |
+
"""
|
| 179 |
+
return base_tasks._task_print_stack(self, limit, file)
|
| 180 |
+
|
| 181 |
+
def cancel(self, msg=None):
|
| 182 |
+
"""Request that this task cancel itself.
|
| 183 |
+
|
| 184 |
+
This arranges for a CancelledError to be thrown into the
|
| 185 |
+
wrapped coroutine on the next cycle through the event loop.
|
| 186 |
+
The coroutine then has a chance to clean up or even deny
|
| 187 |
+
the request using try/except/finally.
|
| 188 |
+
|
| 189 |
+
Unlike Future.cancel, this does not guarantee that the
|
| 190 |
+
task will be cancelled: the exception might be caught and
|
| 191 |
+
acted upon, delaying cancellation of the task or preventing
|
| 192 |
+
cancellation completely. The task may also return a value or
|
| 193 |
+
raise a different exception.
|
| 194 |
+
|
| 195 |
+
Immediately after this method is called, Task.cancelled() will
|
| 196 |
+
not return True (unless the task was already cancelled). A
|
| 197 |
+
task will be marked as cancelled when the wrapped coroutine
|
| 198 |
+
terminates with a CancelledError exception (even if cancel()
|
| 199 |
+
was not called).
|
| 200 |
+
"""
|
| 201 |
+
self._log_traceback = False
|
| 202 |
+
if self.done():
|
| 203 |
+
return False
|
| 204 |
+
if self._fut_waiter is not None:
|
| 205 |
+
if self._fut_waiter.cancel(msg=msg):
|
| 206 |
+
# Leave self._fut_waiter; it may be a Task that
|
| 207 |
+
# catches and ignores the cancellation so we may have
|
| 208 |
+
# to cancel it again later.
|
| 209 |
+
return True
|
| 210 |
+
# It must be the case that self.__step is already scheduled.
|
| 211 |
+
self._must_cancel = True
|
| 212 |
+
self._cancel_message = msg
|
| 213 |
+
return True
|
| 214 |
+
|
| 215 |
+
def __step(self, exc=None):
|
| 216 |
+
if self.done():
|
| 217 |
+
raise exceptions.InvalidStateError(
|
| 218 |
+
f'_step(): already done: {self!r}, {exc!r}')
|
| 219 |
+
if self._must_cancel:
|
| 220 |
+
if not isinstance(exc, exceptions.CancelledError):
|
| 221 |
+
exc = self._make_cancelled_error()
|
| 222 |
+
self._must_cancel = False
|
| 223 |
+
coro = self._coro
|
| 224 |
+
self._fut_waiter = None
|
| 225 |
+
|
| 226 |
+
_enter_task(self._loop, self)
|
| 227 |
+
# Call either coro.throw(exc) or coro.send(None).
|
| 228 |
+
try:
|
| 229 |
+
if exc is None:
|
| 230 |
+
# We use the `send` method directly, because coroutines
|
| 231 |
+
# don't have `__iter__` and `__next__` methods.
|
| 232 |
+
result = coro.send(None)
|
| 233 |
+
else:
|
| 234 |
+
result = coro.throw(exc)
|
| 235 |
+
except StopIteration as exc:
|
| 236 |
+
if self._must_cancel:
|
| 237 |
+
# Task is cancelled right before coro stops.
|
| 238 |
+
self._must_cancel = False
|
| 239 |
+
super().cancel(msg=self._cancel_message)
|
| 240 |
+
else:
|
| 241 |
+
super().set_result(exc.value)
|
| 242 |
+
except exceptions.CancelledError as exc:
|
| 243 |
+
# Save the original exception so we can chain it later.
|
| 244 |
+
self._cancelled_exc = exc
|
| 245 |
+
super().cancel() # I.e., Future.cancel(self).
|
| 246 |
+
except (KeyboardInterrupt, SystemExit) as exc:
|
| 247 |
+
super().set_exception(exc)
|
| 248 |
+
raise
|
| 249 |
+
except BaseException as exc:
|
| 250 |
+
super().set_exception(exc)
|
| 251 |
+
else:
|
| 252 |
+
blocking = getattr(result, '_asyncio_future_blocking', None)
|
| 253 |
+
if blocking is not None:
|
| 254 |
+
# Yielded Future must come from Future.__iter__().
|
| 255 |
+
if futures._get_loop(result) is not self._loop:
|
| 256 |
+
new_exc = RuntimeError(
|
| 257 |
+
f'Task {self!r} got Future '
|
| 258 |
+
f'{result!r} attached to a different loop')
|
| 259 |
+
self._loop.call_soon(
|
| 260 |
+
self.__step, new_exc, context=self._context)
|
| 261 |
+
elif blocking:
|
| 262 |
+
if result is self:
|
| 263 |
+
new_exc = RuntimeError(
|
| 264 |
+
f'Task cannot await on itself: {self!r}')
|
| 265 |
+
self._loop.call_soon(
|
| 266 |
+
self.__step, new_exc, context=self._context)
|
| 267 |
+
else:
|
| 268 |
+
result._asyncio_future_blocking = False
|
| 269 |
+
result.add_done_callback(
|
| 270 |
+
self.__wakeup, context=self._context)
|
| 271 |
+
self._fut_waiter = result
|
| 272 |
+
if self._must_cancel:
|
| 273 |
+
if self._fut_waiter.cancel(
|
| 274 |
+
msg=self._cancel_message):
|
| 275 |
+
self._must_cancel = False
|
| 276 |
+
else:
|
| 277 |
+
new_exc = RuntimeError(
|
| 278 |
+
f'yield was used instead of yield from '
|
| 279 |
+
f'in task {self!r} with {result!r}')
|
| 280 |
+
self._loop.call_soon(
|
| 281 |
+
self.__step, new_exc, context=self._context)
|
| 282 |
+
|
| 283 |
+
elif result is None:
|
| 284 |
+
# Bare yield relinquishes control for one event loop iteration.
|
| 285 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 286 |
+
elif inspect.isgenerator(result):
|
| 287 |
+
# Yielding a generator is just wrong.
|
| 288 |
+
new_exc = RuntimeError(
|
| 289 |
+
f'yield was used instead of yield from for '
|
| 290 |
+
f'generator in task {self!r} with {result!r}')
|
| 291 |
+
self._loop.call_soon(
|
| 292 |
+
self.__step, new_exc, context=self._context)
|
| 293 |
+
else:
|
| 294 |
+
# Yielding something else is an error.
|
| 295 |
+
new_exc = RuntimeError(f'Task got bad yield: {result!r}')
|
| 296 |
+
self._loop.call_soon(
|
| 297 |
+
self.__step, new_exc, context=self._context)
|
| 298 |
+
finally:
|
| 299 |
+
_leave_task(self._loop, self)
|
| 300 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 301 |
+
|
| 302 |
+
def __wakeup(self, future):
|
| 303 |
+
try:
|
| 304 |
+
future.result()
|
| 305 |
+
except BaseException as exc:
|
| 306 |
+
# This may also be a cancellation.
|
| 307 |
+
self.__step(exc)
|
| 308 |
+
else:
|
| 309 |
+
# Don't pass the value of `future.result()` explicitly,
|
| 310 |
+
# as `Future.__iter__` and `Future.__await__` don't need it.
|
| 311 |
+
# If we call `_step(value, None)` instead of `_step()`,
|
| 312 |
+
# Python eval loop would use `.send(value)` method call,
|
| 313 |
+
# instead of `__next__()`, which is slower for futures
|
| 314 |
+
# that return non-generator iterators from their `__iter__`.
|
| 315 |
+
self.__step()
|
| 316 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
_PyTask = Task
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
try:
|
| 323 |
+
import _asyncio
|
| 324 |
+
except ImportError:
|
| 325 |
+
pass
|
| 326 |
+
else:
|
| 327 |
+
# _CTask is needed for tests.
|
| 328 |
+
Task = _CTask = _asyncio.Task
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def create_task(coro, *, name=None):
|
| 332 |
+
"""Schedule the execution of a coroutine object in a spawn task.
|
| 333 |
+
|
| 334 |
+
Return a Task object.
|
| 335 |
+
"""
|
| 336 |
+
loop = events.get_running_loop()
|
| 337 |
+
task = loop.create_task(coro)
|
| 338 |
+
_set_task_name(task, name)
|
| 339 |
+
return task
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# wait() and as_completed() similar to those in PEP 3148.
|
| 343 |
+
|
| 344 |
+
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
|
| 345 |
+
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
|
| 346 |
+
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
async def wait(fs, *, timeout=None, return_when=ALL_COMPLETED):
|
| 350 |
+
"""Wait for the Futures and coroutines given by fs to complete.
|
| 351 |
+
|
| 352 |
+
The fs iterable must not be empty.
|
| 353 |
+
|
| 354 |
+
Coroutines will be wrapped in Tasks.
|
| 355 |
+
|
| 356 |
+
Returns two sets of Future: (done, pending).
|
| 357 |
+
|
| 358 |
+
Usage:
|
| 359 |
+
|
| 360 |
+
done, pending = await asyncio.wait(fs)
|
| 361 |
+
|
| 362 |
+
Note: This does not raise TimeoutError! Futures that aren't done
|
| 363 |
+
when the timeout occurs are returned in the second set.
|
| 364 |
+
"""
|
| 365 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 366 |
+
raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
|
| 367 |
+
if not fs:
|
| 368 |
+
raise ValueError('Set of coroutines/Futures is empty.')
|
| 369 |
+
if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
|
| 370 |
+
raise ValueError(f'Invalid return_when value: {return_when}')
|
| 371 |
+
|
| 372 |
+
loop = events.get_running_loop()
|
| 373 |
+
|
| 374 |
+
fs = set(fs)
|
| 375 |
+
|
| 376 |
+
if any(coroutines.iscoroutine(f) for f in fs):
|
| 377 |
+
warnings.warn("The explicit passing of coroutine objects to "
|
| 378 |
+
"asyncio.wait() is deprecated since Python 3.8, and "
|
| 379 |
+
"scheduled for removal in Python 3.11.",
|
| 380 |
+
DeprecationWarning, stacklevel=2)
|
| 381 |
+
|
| 382 |
+
fs = {ensure_future(f, loop=loop) for f in fs}
|
| 383 |
+
|
| 384 |
+
return await _wait(fs, timeout, return_when, loop)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _release_waiter(waiter, *args):
|
| 388 |
+
if not waiter.done():
|
| 389 |
+
waiter.set_result(None)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
async def wait_for(fut, timeout):
|
| 393 |
+
"""Wait for the single Future or coroutine to complete, with timeout.
|
| 394 |
+
|
| 395 |
+
Coroutine will be wrapped in Task.
|
| 396 |
+
|
| 397 |
+
Returns result of the Future or coroutine. When a timeout occurs,
|
| 398 |
+
it cancels the task and raises TimeoutError. To avoid the task
|
| 399 |
+
cancellation, wrap it in shield().
|
| 400 |
+
|
| 401 |
+
If the wait is cancelled, the task is also cancelled.
|
| 402 |
+
|
| 403 |
+
This function is a coroutine.
|
| 404 |
+
"""
|
| 405 |
+
loop = events.get_running_loop()
|
| 406 |
+
|
| 407 |
+
if timeout is None:
|
| 408 |
+
return await fut
|
| 409 |
+
|
| 410 |
+
if timeout <= 0:
|
| 411 |
+
fut = ensure_future(fut, loop=loop)
|
| 412 |
+
|
| 413 |
+
if fut.done():
|
| 414 |
+
return fut.result()
|
| 415 |
+
|
| 416 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 417 |
+
try:
|
| 418 |
+
return fut.result()
|
| 419 |
+
except exceptions.CancelledError as exc:
|
| 420 |
+
raise exceptions.TimeoutError() from exc
|
| 421 |
+
|
| 422 |
+
waiter = loop.create_future()
|
| 423 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 424 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 425 |
+
|
| 426 |
+
fut = ensure_future(fut, loop=loop)
|
| 427 |
+
fut.add_done_callback(cb)
|
| 428 |
+
|
| 429 |
+
try:
|
| 430 |
+
# wait until the future completes or the timeout
|
| 431 |
+
try:
|
| 432 |
+
await waiter
|
| 433 |
+
except exceptions.CancelledError:
|
| 434 |
+
if fut.done():
|
| 435 |
+
return fut.result()
|
| 436 |
+
else:
|
| 437 |
+
fut.remove_done_callback(cb)
|
| 438 |
+
# We must ensure that the task is not running
|
| 439 |
+
# after wait_for() returns.
|
| 440 |
+
# See https://bugs.python.org/issue32751
|
| 441 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 442 |
+
raise
|
| 443 |
+
|
| 444 |
+
if fut.done():
|
| 445 |
+
return fut.result()
|
| 446 |
+
else:
|
| 447 |
+
fut.remove_done_callback(cb)
|
| 448 |
+
# We must ensure that the task is not running
|
| 449 |
+
# after wait_for() returns.
|
| 450 |
+
# See https://bugs.python.org/issue32751
|
| 451 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 452 |
+
# In case task cancellation failed with some
|
| 453 |
+
# exception, we should re-raise it
|
| 454 |
+
# See https://bugs.python.org/issue40607
|
| 455 |
+
try:
|
| 456 |
+
return fut.result()
|
| 457 |
+
except exceptions.CancelledError as exc:
|
| 458 |
+
raise exceptions.TimeoutError() from exc
|
| 459 |
+
finally:
|
| 460 |
+
timeout_handle.cancel()
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
async def _wait(fs, timeout, return_when, loop):
|
| 464 |
+
"""Internal helper for wait().
|
| 465 |
+
|
| 466 |
+
The fs argument must be a collection of Futures.
|
| 467 |
+
"""
|
| 468 |
+
assert fs, 'Set of Futures is empty.'
|
| 469 |
+
waiter = loop.create_future()
|
| 470 |
+
timeout_handle = None
|
| 471 |
+
if timeout is not None:
|
| 472 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 473 |
+
counter = len(fs)
|
| 474 |
+
|
| 475 |
+
def _on_completion(f):
|
| 476 |
+
nonlocal counter
|
| 477 |
+
counter -= 1
|
| 478 |
+
if (counter <= 0 or
|
| 479 |
+
return_when == FIRST_COMPLETED or
|
| 480 |
+
return_when == FIRST_EXCEPTION and (not f.cancelled() and
|
| 481 |
+
f.exception() is not None)):
|
| 482 |
+
if timeout_handle is not None:
|
| 483 |
+
timeout_handle.cancel()
|
| 484 |
+
if not waiter.done():
|
| 485 |
+
waiter.set_result(None)
|
| 486 |
+
|
| 487 |
+
for f in fs:
|
| 488 |
+
f.add_done_callback(_on_completion)
|
| 489 |
+
|
| 490 |
+
try:
|
| 491 |
+
await waiter
|
| 492 |
+
finally:
|
| 493 |
+
if timeout_handle is not None:
|
| 494 |
+
timeout_handle.cancel()
|
| 495 |
+
for f in fs:
|
| 496 |
+
f.remove_done_callback(_on_completion)
|
| 497 |
+
|
| 498 |
+
done, pending = set(), set()
|
| 499 |
+
for f in fs:
|
| 500 |
+
if f.done():
|
| 501 |
+
done.add(f)
|
| 502 |
+
else:
|
| 503 |
+
pending.add(f)
|
| 504 |
+
return done, pending
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
async def _cancel_and_wait(fut, loop):
|
| 508 |
+
"""Cancel the *fut* future or task and wait until it completes."""
|
| 509 |
+
|
| 510 |
+
waiter = loop.create_future()
|
| 511 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 512 |
+
fut.add_done_callback(cb)
|
| 513 |
+
|
| 514 |
+
try:
|
| 515 |
+
fut.cancel()
|
| 516 |
+
# We cannot wait on *fut* directly to make
|
| 517 |
+
# sure _cancel_and_wait itself is reliably cancellable.
|
| 518 |
+
await waiter
|
| 519 |
+
finally:
|
| 520 |
+
fut.remove_done_callback(cb)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# This is *not* a @coroutine! It is just an iterator (yielding Futures).
|
| 524 |
+
def as_completed(fs, *, timeout=None):
|
| 525 |
+
"""Return an iterator whose values are coroutines.
|
| 526 |
+
|
| 527 |
+
When waiting for the yielded coroutines you'll get the results (or
|
| 528 |
+
exceptions!) of the original Futures (or coroutines), in the order
|
| 529 |
+
in which and as soon as they complete.
|
| 530 |
+
|
| 531 |
+
This differs from PEP 3148; the proper way to use this is:
|
| 532 |
+
|
| 533 |
+
for f in as_completed(fs):
|
| 534 |
+
result = await f # The 'await' may raise.
|
| 535 |
+
# Use result.
|
| 536 |
+
|
| 537 |
+
If a timeout is specified, the 'await' will raise
|
| 538 |
+
TimeoutError when the timeout occurs before all Futures are done.
|
| 539 |
+
|
| 540 |
+
Note: The futures 'f' are not necessarily members of fs.
|
| 541 |
+
"""
|
| 542 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 543 |
+
raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
|
| 544 |
+
|
| 545 |
+
from .queues import Queue # Import here to avoid circular import problem.
|
| 546 |
+
done = Queue()
|
| 547 |
+
|
| 548 |
+
loop = events._get_event_loop()
|
| 549 |
+
todo = {ensure_future(f, loop=loop) for f in set(fs)}
|
| 550 |
+
timeout_handle = None
|
| 551 |
+
|
| 552 |
+
def _on_timeout():
|
| 553 |
+
for f in todo:
|
| 554 |
+
f.remove_done_callback(_on_completion)
|
| 555 |
+
done.put_nowait(None) # Queue a dummy value for _wait_for_one().
|
| 556 |
+
todo.clear() # Can't do todo.remove(f) in the loop.
|
| 557 |
+
|
| 558 |
+
def _on_completion(f):
|
| 559 |
+
if not todo:
|
| 560 |
+
return # _on_timeout() was here first.
|
| 561 |
+
todo.remove(f)
|
| 562 |
+
done.put_nowait(f)
|
| 563 |
+
if not todo and timeout_handle is not None:
|
| 564 |
+
timeout_handle.cancel()
|
| 565 |
+
|
| 566 |
+
async def _wait_for_one():
|
| 567 |
+
f = await done.get()
|
| 568 |
+
if f is None:
|
| 569 |
+
# Dummy value from _on_timeout().
|
| 570 |
+
raise exceptions.TimeoutError
|
| 571 |
+
return f.result() # May raise f.exception().
|
| 572 |
+
|
| 573 |
+
for f in todo:
|
| 574 |
+
f.add_done_callback(_on_completion)
|
| 575 |
+
if todo and timeout is not None:
|
| 576 |
+
timeout_handle = loop.call_later(timeout, _on_timeout)
|
| 577 |
+
for _ in range(len(todo)):
|
| 578 |
+
yield _wait_for_one()
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@types.coroutine
|
| 582 |
+
def __sleep0():
|
| 583 |
+
"""Skip one event loop run cycle.
|
| 584 |
+
|
| 585 |
+
This is a private helper for 'asyncio.sleep()', used
|
| 586 |
+
when the 'delay' is set to 0. It uses a bare 'yield'
|
| 587 |
+
expression (which Task.__step knows how to handle)
|
| 588 |
+
instead of creating a Future object.
|
| 589 |
+
"""
|
| 590 |
+
yield
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
async def sleep(delay, result=None):
|
| 594 |
+
"""Coroutine that completes after a given time (in seconds)."""
|
| 595 |
+
if delay <= 0:
|
| 596 |
+
await __sleep0()
|
| 597 |
+
return result
|
| 598 |
+
|
| 599 |
+
loop = events.get_running_loop()
|
| 600 |
+
future = loop.create_future()
|
| 601 |
+
h = loop.call_later(delay,
|
| 602 |
+
futures._set_result_unless_cancelled,
|
| 603 |
+
future, result)
|
| 604 |
+
try:
|
| 605 |
+
return await future
|
| 606 |
+
finally:
|
| 607 |
+
h.cancel()
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def ensure_future(coro_or_future, *, loop=None):
|
| 611 |
+
"""Wrap a coroutine or an awaitable in a future.
|
| 612 |
+
|
| 613 |
+
If the argument is a Future, it is returned directly.
|
| 614 |
+
"""
|
| 615 |
+
return _ensure_future(coro_or_future, loop=loop)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def _ensure_future(coro_or_future, *, loop=None):
|
| 619 |
+
if futures.isfuture(coro_or_future):
|
| 620 |
+
if loop is not None and loop is not futures._get_loop(coro_or_future):
|
| 621 |
+
raise ValueError('The future belongs to a different loop than '
|
| 622 |
+
'the one specified as the loop argument')
|
| 623 |
+
return coro_or_future
|
| 624 |
+
called_wrap_awaitable = False
|
| 625 |
+
if not coroutines.iscoroutine(coro_or_future):
|
| 626 |
+
if inspect.isawaitable(coro_or_future):
|
| 627 |
+
coro_or_future = _wrap_awaitable(coro_or_future)
|
| 628 |
+
called_wrap_awaitable = True
|
| 629 |
+
else:
|
| 630 |
+
raise TypeError('An asyncio.Future, a coroutine or an awaitable '
|
| 631 |
+
'is required')
|
| 632 |
+
|
| 633 |
+
if loop is None:
|
| 634 |
+
loop = events._get_event_loop(stacklevel=4)
|
| 635 |
+
try:
|
| 636 |
+
return loop.create_task(coro_or_future)
|
| 637 |
+
except RuntimeError:
|
| 638 |
+
if not called_wrap_awaitable:
|
| 639 |
+
coro_or_future.close()
|
| 640 |
+
raise
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
@types.coroutine
|
| 644 |
+
def _wrap_awaitable(awaitable):
|
| 645 |
+
"""Helper for asyncio.ensure_future().
|
| 646 |
+
|
| 647 |
+
Wraps awaitable (an object with __await__) into a coroutine
|
| 648 |
+
that will later be wrapped in a Task by ensure_future().
|
| 649 |
+
"""
|
| 650 |
+
return (yield from awaitable.__await__())
|
| 651 |
+
|
| 652 |
+
_wrap_awaitable._is_coroutine = _is_coroutine
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class _GatheringFuture(futures.Future):
|
| 656 |
+
"""Helper for gather().
|
| 657 |
+
|
| 658 |
+
This overrides cancel() to cancel all the children and act more
|
| 659 |
+
like Task.cancel(), which doesn't immediately mark itself as
|
| 660 |
+
cancelled.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
def __init__(self, children, *, loop):
|
| 664 |
+
assert loop is not None
|
| 665 |
+
super().__init__(loop=loop)
|
| 666 |
+
self._children = children
|
| 667 |
+
self._cancel_requested = False
|
| 668 |
+
|
| 669 |
+
def cancel(self, msg=None):
|
| 670 |
+
if self.done():
|
| 671 |
+
return False
|
| 672 |
+
ret = False
|
| 673 |
+
for child in self._children:
|
| 674 |
+
if child.cancel(msg=msg):
|
| 675 |
+
ret = True
|
| 676 |
+
if ret:
|
| 677 |
+
# If any child tasks were actually cancelled, we should
|
| 678 |
+
# propagate the cancellation request regardless of
|
| 679 |
+
# *return_exceptions* argument. See issue 32684.
|
| 680 |
+
self._cancel_requested = True
|
| 681 |
+
return ret
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def gather(*coros_or_futures, return_exceptions=False):
|
| 685 |
+
"""Return a future aggregating results from the given coroutines/futures.
|
| 686 |
+
|
| 687 |
+
Coroutines will be wrapped in a future and scheduled in the event
|
| 688 |
+
loop. They will not necessarily be scheduled in the same order as
|
| 689 |
+
passed in.
|
| 690 |
+
|
| 691 |
+
All futures must share the same event loop. If all the tasks are
|
| 692 |
+
done successfully, the returned future's result is the list of
|
| 693 |
+
results (in the order of the original sequence, not necessarily
|
| 694 |
+
the order of results arrival). If *return_exceptions* is True,
|
| 695 |
+
exceptions in the tasks are treated the same as successful
|
| 696 |
+
results, and gathered in the result list; otherwise, the first
|
| 697 |
+
raised exception will be immediately propagated to the returned
|
| 698 |
+
future.
|
| 699 |
+
|
| 700 |
+
Cancellation: if the outer Future is cancelled, all children (that
|
| 701 |
+
have not completed yet) are also cancelled. If any child is
|
| 702 |
+
cancelled, this is treated as if it raised CancelledError --
|
| 703 |
+
the outer Future is *not* cancelled in this case. (This is to
|
| 704 |
+
prevent the cancellation of one child to cause other children to
|
| 705 |
+
be cancelled.)
|
| 706 |
+
|
| 707 |
+
If *return_exceptions* is False, cancelling gather() after it
|
| 708 |
+
has been marked done won't cancel any submitted awaitables.
|
| 709 |
+
For instance, gather can be marked done after propagating an
|
| 710 |
+
exception to the caller, therefore, calling ``gather.cancel()``
|
| 711 |
+
after catching an exception (raised by one of the awaitables) from
|
| 712 |
+
gather won't cancel any other awaitables.
|
| 713 |
+
"""
|
| 714 |
+
if not coros_or_futures:
|
| 715 |
+
loop = events._get_event_loop()
|
| 716 |
+
outer = loop.create_future()
|
| 717 |
+
outer.set_result([])
|
| 718 |
+
return outer
|
| 719 |
+
|
| 720 |
+
def _done_callback(fut):
|
| 721 |
+
nonlocal nfinished
|
| 722 |
+
nfinished += 1
|
| 723 |
+
|
| 724 |
+
if outer is None or outer.done():
|
| 725 |
+
if not fut.cancelled():
|
| 726 |
+
# Mark exception retrieved.
|
| 727 |
+
fut.exception()
|
| 728 |
+
return
|
| 729 |
+
|
| 730 |
+
if not return_exceptions:
|
| 731 |
+
if fut.cancelled():
|
| 732 |
+
# Check if 'fut' is cancelled first, as
|
| 733 |
+
# 'fut.exception()' will *raise* a CancelledError
|
| 734 |
+
# instead of returning it.
|
| 735 |
+
exc = fut._make_cancelled_error()
|
| 736 |
+
outer.set_exception(exc)
|
| 737 |
+
return
|
| 738 |
+
else:
|
| 739 |
+
exc = fut.exception()
|
| 740 |
+
if exc is not None:
|
| 741 |
+
outer.set_exception(exc)
|
| 742 |
+
return
|
| 743 |
+
|
| 744 |
+
if nfinished == nfuts:
|
| 745 |
+
# All futures are done; create a list of results
|
| 746 |
+
# and set it to the 'outer' future.
|
| 747 |
+
results = []
|
| 748 |
+
|
| 749 |
+
for fut in children:
|
| 750 |
+
if fut.cancelled():
|
| 751 |
+
# Check if 'fut' is cancelled first, as 'fut.exception()'
|
| 752 |
+
# will *raise* a CancelledError instead of returning it.
|
| 753 |
+
# Also, since we're adding the exception return value
|
| 754 |
+
# to 'results' instead of raising it, don't bother
|
| 755 |
+
# setting __context__. This also lets us preserve
|
| 756 |
+
# calling '_make_cancelled_error()' at most once.
|
| 757 |
+
res = exceptions.CancelledError(
|
| 758 |
+
'' if fut._cancel_message is None else
|
| 759 |
+
fut._cancel_message)
|
| 760 |
+
else:
|
| 761 |
+
res = fut.exception()
|
| 762 |
+
if res is None:
|
| 763 |
+
res = fut.result()
|
| 764 |
+
results.append(res)
|
| 765 |
+
|
| 766 |
+
if outer._cancel_requested:
|
| 767 |
+
# If gather is being cancelled we must propagate the
|
| 768 |
+
# cancellation regardless of *return_exceptions* argument.
|
| 769 |
+
# See issue 32684.
|
| 770 |
+
exc = fut._make_cancelled_error()
|
| 771 |
+
outer.set_exception(exc)
|
| 772 |
+
else:
|
| 773 |
+
outer.set_result(results)
|
| 774 |
+
|
| 775 |
+
arg_to_fut = {}
|
| 776 |
+
children = []
|
| 777 |
+
nfuts = 0
|
| 778 |
+
nfinished = 0
|
| 779 |
+
loop = None
|
| 780 |
+
outer = None # bpo-46672
|
| 781 |
+
for arg in coros_or_futures:
|
| 782 |
+
if arg not in arg_to_fut:
|
| 783 |
+
fut = _ensure_future(arg, loop=loop)
|
| 784 |
+
if loop is None:
|
| 785 |
+
loop = futures._get_loop(fut)
|
| 786 |
+
if fut is not arg:
|
| 787 |
+
# 'arg' was not a Future, therefore, 'fut' is a new
|
| 788 |
+
# Future created specifically for 'arg'. Since the caller
|
| 789 |
+
# can't control it, disable the "destroy pending task"
|
| 790 |
+
# warning.
|
| 791 |
+
fut._log_destroy_pending = False
|
| 792 |
+
|
| 793 |
+
nfuts += 1
|
| 794 |
+
arg_to_fut[arg] = fut
|
| 795 |
+
fut.add_done_callback(_done_callback)
|
| 796 |
+
|
| 797 |
+
else:
|
| 798 |
+
# There's a duplicate Future object in coros_or_futures.
|
| 799 |
+
fut = arg_to_fut[arg]
|
| 800 |
+
|
| 801 |
+
children.append(fut)
|
| 802 |
+
|
| 803 |
+
outer = _GatheringFuture(children, loop=loop)
|
| 804 |
+
return outer
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def shield(arg):
|
| 808 |
+
"""Wait for a future, shielding it from cancellation.
|
| 809 |
+
|
| 810 |
+
The statement
|
| 811 |
+
|
| 812 |
+
task = asyncio.create_task(something())
|
| 813 |
+
res = await shield(task)
|
| 814 |
+
|
| 815 |
+
is exactly equivalent to the statement
|
| 816 |
+
|
| 817 |
+
res = await something()
|
| 818 |
+
|
| 819 |
+
*except* that if the coroutine containing it is cancelled, the
|
| 820 |
+
task running in something() is not cancelled. From the POV of
|
| 821 |
+
something(), the cancellation did not happen. But its caller is
|
| 822 |
+
still cancelled, so the yield-from expression still raises
|
| 823 |
+
CancelledError. Note: If something() is cancelled by other means
|
| 824 |
+
this will still cancel shield().
|
| 825 |
+
|
| 826 |
+
If you want to completely ignore cancellation (not recommended)
|
| 827 |
+
you can combine shield() with a try/except clause, as follows:
|
| 828 |
+
|
| 829 |
+
task = asyncio.create_task(something())
|
| 830 |
+
try:
|
| 831 |
+
res = await shield(task)
|
| 832 |
+
except CancelledError:
|
| 833 |
+
res = None
|
| 834 |
+
|
| 835 |
+
Save a reference to tasks passed to this function, to avoid
|
| 836 |
+
a task disappearing mid-execution. The event loop only keeps
|
| 837 |
+
weak references to tasks. A task that isn't referenced elsewhere
|
| 838 |
+
may get garbage collected at any time, even before it's done.
|
| 839 |
+
"""
|
| 840 |
+
inner = _ensure_future(arg)
|
| 841 |
+
if inner.done():
|
| 842 |
+
# Shortcut.
|
| 843 |
+
return inner
|
| 844 |
+
loop = futures._get_loop(inner)
|
| 845 |
+
outer = loop.create_future()
|
| 846 |
+
|
| 847 |
+
def _inner_done_callback(inner):
|
| 848 |
+
if outer.cancelled():
|
| 849 |
+
if not inner.cancelled():
|
| 850 |
+
# Mark inner's result as retrieved.
|
| 851 |
+
inner.exception()
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
if inner.cancelled():
|
| 855 |
+
outer.cancel()
|
| 856 |
+
else:
|
| 857 |
+
exc = inner.exception()
|
| 858 |
+
if exc is not None:
|
| 859 |
+
outer.set_exception(exc)
|
| 860 |
+
else:
|
| 861 |
+
outer.set_result(inner.result())
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def _outer_done_callback(outer):
|
| 865 |
+
if not inner.done():
|
| 866 |
+
inner.remove_done_callback(_inner_done_callback)
|
| 867 |
+
|
| 868 |
+
inner.add_done_callback(_inner_done_callback)
|
| 869 |
+
outer.add_done_callback(_outer_done_callback)
|
| 870 |
+
return outer
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def run_coroutine_threadsafe(coro, loop):
|
| 874 |
+
"""Submit a coroutine object to a given event loop.
|
| 875 |
+
|
| 876 |
+
Return a concurrent.futures.Future to access the result.
|
| 877 |
+
"""
|
| 878 |
+
if not coroutines.iscoroutine(coro):
|
| 879 |
+
raise TypeError('A coroutine object is required')
|
| 880 |
+
future = concurrent.futures.Future()
|
| 881 |
+
|
| 882 |
+
def callback():
|
| 883 |
+
try:
|
| 884 |
+
futures._chain_future(ensure_future(coro, loop=loop), future)
|
| 885 |
+
except (SystemExit, KeyboardInterrupt):
|
| 886 |
+
raise
|
| 887 |
+
except BaseException as exc:
|
| 888 |
+
if future.set_running_or_notify_cancel():
|
| 889 |
+
future.set_exception(exc)
|
| 890 |
+
raise
|
| 891 |
+
|
| 892 |
+
loop.call_soon_threadsafe(callback)
|
| 893 |
+
return future
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
# WeakSet containing all alive tasks.
|
| 897 |
+
_all_tasks = weakref.WeakSet()
|
| 898 |
+
|
| 899 |
+
# Dictionary containing tasks that are currently active in
|
| 900 |
+
# all running event loops. {EventLoop: Task}
|
| 901 |
+
_current_tasks = {}
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def _register_task(task):
|
| 905 |
+
"""Register a new task in asyncio as executed by loop."""
|
| 906 |
+
_all_tasks.add(task)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _enter_task(loop, task):
|
| 910 |
+
current_task = _current_tasks.get(loop)
|
| 911 |
+
if current_task is not None:
|
| 912 |
+
raise RuntimeError(f"Cannot enter into task {task!r} while another "
|
| 913 |
+
f"task {current_task!r} is being executed.")
|
| 914 |
+
_current_tasks[loop] = task
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def _leave_task(loop, task):
|
| 918 |
+
current_task = _current_tasks.get(loop)
|
| 919 |
+
if current_task is not task:
|
| 920 |
+
raise RuntimeError(f"Leaving task {task!r} does not match "
|
| 921 |
+
f"the current task {current_task!r}.")
|
| 922 |
+
del _current_tasks[loop]
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def _unregister_task(task):
|
| 926 |
+
"""Unregister a task."""
|
| 927 |
+
_all_tasks.discard(task)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
_py_register_task = _register_task
|
| 931 |
+
_py_unregister_task = _unregister_task
|
| 932 |
+
_py_enter_task = _enter_task
|
| 933 |
+
_py_leave_task = _leave_task
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
try:
|
| 937 |
+
from _asyncio import (_register_task, _unregister_task,
|
| 938 |
+
_enter_task, _leave_task,
|
| 939 |
+
_all_tasks, _current_tasks)
|
| 940 |
+
except ImportError:
|
| 941 |
+
pass
|
| 942 |
+
else:
|
| 943 |
+
_c_register_task = _register_task
|
| 944 |
+
_c_unregister_task = _unregister_task
|
| 945 |
+
_c_enter_task = _enter_task
|
| 946 |
+
_c_leave_task = _leave_task
|
wemm/lib/python3.10/asyncio/threads.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""High-level support for working with threads in asyncio"""
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import contextvars
|
| 5 |
+
|
| 6 |
+
from . import events
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = "to_thread",
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def to_thread(func, /, *args, **kwargs):
|
| 13 |
+
"""Asynchronously run function *func* in a separate thread.
|
| 14 |
+
|
| 15 |
+
Any *args and **kwargs supplied for this function are directly passed
|
| 16 |
+
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
| 17 |
+
allowing context variables from the main thread to be accessed in the
|
| 18 |
+
separate thread.
|
| 19 |
+
|
| 20 |
+
Return a coroutine that can be awaited to get the eventual result of *func*.
|
| 21 |
+
"""
|
| 22 |
+
loop = events.get_running_loop()
|
| 23 |
+
ctx = contextvars.copy_context()
|
| 24 |
+
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
| 25 |
+
return await loop.run_in_executor(None, func_call)
|
wemm/lib/python3.10/asyncio/windows_utils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Various Windows specific bits and pieces."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
if sys.platform != 'win32': # pragma: no cover
|
| 6 |
+
raise ImportError('win32 only')
|
| 7 |
+
|
| 8 |
+
import _winapi
|
| 9 |
+
import itertools
|
| 10 |
+
import msvcrt
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import tempfile
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = 'pipe', 'Popen', 'PIPE', 'PipeHandle'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Constants/globals
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
BUFSIZE = 8192
|
| 24 |
+
PIPE = subprocess.PIPE
|
| 25 |
+
STDOUT = subprocess.STDOUT
|
| 26 |
+
_mmap_counter = itertools.count()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Replacement for os.pipe() using handles instead of fds
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
|
| 33 |
+
"""Like os.pipe() but with overlapped support and using handles not fds."""
|
| 34 |
+
address = tempfile.mktemp(
|
| 35 |
+
prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
|
| 36 |
+
os.getpid(), next(_mmap_counter)))
|
| 37 |
+
|
| 38 |
+
if duplex:
|
| 39 |
+
openmode = _winapi.PIPE_ACCESS_DUPLEX
|
| 40 |
+
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
|
| 41 |
+
obsize, ibsize = bufsize, bufsize
|
| 42 |
+
else:
|
| 43 |
+
openmode = _winapi.PIPE_ACCESS_INBOUND
|
| 44 |
+
access = _winapi.GENERIC_WRITE
|
| 45 |
+
obsize, ibsize = 0, bufsize
|
| 46 |
+
|
| 47 |
+
openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 48 |
+
|
| 49 |
+
if overlapped[0]:
|
| 50 |
+
openmode |= _winapi.FILE_FLAG_OVERLAPPED
|
| 51 |
+
|
| 52 |
+
if overlapped[1]:
|
| 53 |
+
flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED
|
| 54 |
+
else:
|
| 55 |
+
flags_and_attribs = 0
|
| 56 |
+
|
| 57 |
+
h1 = h2 = None
|
| 58 |
+
try:
|
| 59 |
+
h1 = _winapi.CreateNamedPipe(
|
| 60 |
+
address, openmode, _winapi.PIPE_WAIT,
|
| 61 |
+
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
|
| 62 |
+
|
| 63 |
+
h2 = _winapi.CreateFile(
|
| 64 |
+
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
|
| 65 |
+
flags_and_attribs, _winapi.NULL)
|
| 66 |
+
|
| 67 |
+
ov = _winapi.ConnectNamedPipe(h1, overlapped=True)
|
| 68 |
+
ov.GetOverlappedResult(True)
|
| 69 |
+
return h1, h2
|
| 70 |
+
except:
|
| 71 |
+
if h1 is not None:
|
| 72 |
+
_winapi.CloseHandle(h1)
|
| 73 |
+
if h2 is not None:
|
| 74 |
+
_winapi.CloseHandle(h2)
|
| 75 |
+
raise
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Wrapper for a pipe handle
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class PipeHandle:
|
| 82 |
+
"""Wrapper for an overlapped pipe handle which is vaguely file-object like.
|
| 83 |
+
|
| 84 |
+
The IOCP event loop can use these instead of socket objects.
|
| 85 |
+
"""
|
| 86 |
+
def __init__(self, handle):
|
| 87 |
+
self._handle = handle
|
| 88 |
+
|
| 89 |
+
def __repr__(self):
|
| 90 |
+
if self._handle is not None:
|
| 91 |
+
handle = f'handle={self._handle!r}'
|
| 92 |
+
else:
|
| 93 |
+
handle = 'closed'
|
| 94 |
+
return f'<{self.__class__.__name__} {handle}>'
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def handle(self):
|
| 98 |
+
return self._handle
|
| 99 |
+
|
| 100 |
+
def fileno(self):
|
| 101 |
+
if self._handle is None:
|
| 102 |
+
raise ValueError("I/O operation on closed pipe")
|
| 103 |
+
return self._handle
|
| 104 |
+
|
| 105 |
+
def close(self, *, CloseHandle=_winapi.CloseHandle):
|
| 106 |
+
if self._handle is not None:
|
| 107 |
+
CloseHandle(self._handle)
|
| 108 |
+
self._handle = None
|
| 109 |
+
|
| 110 |
+
def __del__(self, _warn=warnings.warn):
|
| 111 |
+
if self._handle is not None:
|
| 112 |
+
_warn(f"unclosed {self!r}", ResourceWarning, source=self)
|
| 113 |
+
self.close()
|
| 114 |
+
|
| 115 |
+
def __enter__(self):
|
| 116 |
+
return self
|
| 117 |
+
|
| 118 |
+
def __exit__(self, t, v, tb):
|
| 119 |
+
self.close()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Replacement for subprocess.Popen using overlapped pipe handles
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Popen(subprocess.Popen):
|
| 126 |
+
"""Replacement for subprocess.Popen using overlapped pipe handles.
|
| 127 |
+
|
| 128 |
+
The stdin, stdout, stderr are None or instances of PipeHandle.
|
| 129 |
+
"""
|
| 130 |
+
def __init__(self, args, stdin=None, stdout=None, stderr=None, **kwds):
|
| 131 |
+
assert not kwds.get('universal_newlines')
|
| 132 |
+
assert kwds.get('bufsize', 0) == 0
|
| 133 |
+
stdin_rfd = stdout_wfd = stderr_wfd = None
|
| 134 |
+
stdin_wh = stdout_rh = stderr_rh = None
|
| 135 |
+
if stdin == PIPE:
|
| 136 |
+
stdin_rh, stdin_wh = pipe(overlapped=(False, True), duplex=True)
|
| 137 |
+
stdin_rfd = msvcrt.open_osfhandle(stdin_rh, os.O_RDONLY)
|
| 138 |
+
else:
|
| 139 |
+
stdin_rfd = stdin
|
| 140 |
+
if stdout == PIPE:
|
| 141 |
+
stdout_rh, stdout_wh = pipe(overlapped=(True, False))
|
| 142 |
+
stdout_wfd = msvcrt.open_osfhandle(stdout_wh, 0)
|
| 143 |
+
else:
|
| 144 |
+
stdout_wfd = stdout
|
| 145 |
+
if stderr == PIPE:
|
| 146 |
+
stderr_rh, stderr_wh = pipe(overlapped=(True, False))
|
| 147 |
+
stderr_wfd = msvcrt.open_osfhandle(stderr_wh, 0)
|
| 148 |
+
elif stderr == STDOUT:
|
| 149 |
+
stderr_wfd = stdout_wfd
|
| 150 |
+
else:
|
| 151 |
+
stderr_wfd = stderr
|
| 152 |
+
try:
|
| 153 |
+
super().__init__(args, stdin=stdin_rfd, stdout=stdout_wfd,
|
| 154 |
+
stderr=stderr_wfd, **kwds)
|
| 155 |
+
except:
|
| 156 |
+
for h in (stdin_wh, stdout_rh, stderr_rh):
|
| 157 |
+
if h is not None:
|
| 158 |
+
_winapi.CloseHandle(h)
|
| 159 |
+
raise
|
| 160 |
+
else:
|
| 161 |
+
if stdin_wh is not None:
|
| 162 |
+
self.stdin = PipeHandle(stdin_wh)
|
| 163 |
+
if stdout_rh is not None:
|
| 164 |
+
self.stdout = PipeHandle(stdout_rh)
|
| 165 |
+
if stderr_rh is not None:
|
| 166 |
+
self.stderr = PipeHandle(stderr_rh)
|
| 167 |
+
finally:
|
| 168 |
+
if stdin == PIPE:
|
| 169 |
+
os.close(stdin_rfd)
|
| 170 |
+
if stdout == PIPE:
|
| 171 |
+
os.close(stdout_wfd)
|
| 172 |
+
if stderr == PIPE:
|
| 173 |
+
os.close(stderr_wfd)
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.58 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/_identifier.cpython-310.pyc
ADDED
|
Binary file (2.06 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/async_utils.cpython-310.pyc
ADDED
|
Binary file (3.44 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/bccache.cpython-310.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc
ADDED
|
Binary file (55.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/constants.cpython-310.pyc
ADDED
|
Binary file (1.52 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/defaults.cpython-310.pyc
ADDED
|
Binary file (1.32 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc
ADDED
|
Binary file (53.4 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/exceptions.cpython-310.pyc
ADDED
|
Binary file (5.52 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/filters.cpython-310.pyc
ADDED
|
Binary file (52.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/lexer.cpython-310.pyc
ADDED
|
Binary file (20.4 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/loaders.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/meta.cpython-310.pyc
ADDED
|
Binary file (3.8 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc
ADDED
|
Binary file (5 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc
ADDED
|
Binary file (40.3 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/optimizer.cpython-310.pyc
ADDED
|
Binary file (1.94 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/parser.cpython-310.pyc
ADDED
|
Binary file (28.1 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/runtime.cpython-310.pyc
ADDED
|
Binary file (32.3 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/tests.cpython-310.pyc
ADDED
|
Binary file (6.68 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (24.8 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/__pycache__/visitor.cpython-310.pyc
ADDED
|
Binary file (3.96 kB). View file
|
|
|
wemm/lib/python3.10/site-packages/jinja2/_identifier.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
# generated by scripts/generate_identifier_pattern.py
|
| 4 |
+
pattern = re.compile(
|
| 5 |
+
r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𐴤-𐽆𐴧-𐽐𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑅅𑅆𑅳𑆀-𑆂𑆳-𑇀𑇉-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌻𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑑞𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑠬-𑠺𑨁-𑨊𑨳-𑨹𑨻-𑨾𑩇𑩑-𑩛𑪊-𑪙𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𑴱-𑴶𑴺𑴼𑴽𑴿-𑵅𑵇𑶊-𑶎𑶐𑶑𑶓-𑶗𑻳-𑻶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B950
|
| 6 |
+
)
|
wemm/lib/python3.10/site-packages/jinja2/debug.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import typing as t
|
| 3 |
+
from types import CodeType
|
| 4 |
+
from types import TracebackType
|
| 5 |
+
|
| 6 |
+
from .exceptions import TemplateSyntaxError
|
| 7 |
+
from .utils import internal_code
|
| 8 |
+
from .utils import missing
|
| 9 |
+
|
| 10 |
+
if t.TYPE_CHECKING:
|
| 11 |
+
from .runtime import Context
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:
|
| 15 |
+
"""Rewrite the current exception to replace any tracebacks from
|
| 16 |
+
within compiled template code with tracebacks that look like they
|
| 17 |
+
came from the template source.
|
| 18 |
+
|
| 19 |
+
This must be called within an ``except`` block.
|
| 20 |
+
|
| 21 |
+
:param source: For ``TemplateSyntaxError``, the original source if
|
| 22 |
+
known.
|
| 23 |
+
:return: The original exception with the rewritten traceback.
|
| 24 |
+
"""
|
| 25 |
+
_, exc_value, tb = sys.exc_info()
|
| 26 |
+
exc_value = t.cast(BaseException, exc_value)
|
| 27 |
+
tb = t.cast(TracebackType, tb)
|
| 28 |
+
|
| 29 |
+
if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:
|
| 30 |
+
exc_value.translated = True
|
| 31 |
+
exc_value.source = source
|
| 32 |
+
# Remove the old traceback, otherwise the frames from the
|
| 33 |
+
# compiler still show up.
|
| 34 |
+
exc_value.with_traceback(None)
|
| 35 |
+
# Outside of runtime, so the frame isn't executing template
|
| 36 |
+
# code, but it still needs to point at the template.
|
| 37 |
+
tb = fake_traceback(
|
| 38 |
+
exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
|
| 39 |
+
)
|
| 40 |
+
else:
|
| 41 |
+
# Skip the frame for the render function.
|
| 42 |
+
tb = tb.tb_next
|
| 43 |
+
|
| 44 |
+
stack = []
|
| 45 |
+
|
| 46 |
+
# Build the stack of traceback object, replacing any in template
|
| 47 |
+
# code with the source file and line information.
|
| 48 |
+
while tb is not None:
|
| 49 |
+
# Skip frames decorated with @internalcode. These are internal
|
| 50 |
+
# calls that aren't useful in template debugging output.
|
| 51 |
+
if tb.tb_frame.f_code in internal_code:
|
| 52 |
+
tb = tb.tb_next
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
template = tb.tb_frame.f_globals.get("__jinja_template__")
|
| 56 |
+
|
| 57 |
+
if template is not None:
|
| 58 |
+
lineno = template.get_corresponding_lineno(tb.tb_lineno)
|
| 59 |
+
fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)
|
| 60 |
+
stack.append(fake_tb)
|
| 61 |
+
else:
|
| 62 |
+
stack.append(tb)
|
| 63 |
+
|
| 64 |
+
tb = tb.tb_next
|
| 65 |
+
|
| 66 |
+
tb_next = None
|
| 67 |
+
|
| 68 |
+
# Assign tb_next in reverse to avoid circular references.
|
| 69 |
+
for tb in reversed(stack):
|
| 70 |
+
tb.tb_next = tb_next
|
| 71 |
+
tb_next = tb
|
| 72 |
+
|
| 73 |
+
return exc_value.with_traceback(tb_next)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def fake_traceback( # type: ignore
|
| 77 |
+
exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int
|
| 78 |
+
) -> TracebackType:
|
| 79 |
+
"""Produce a new traceback object that looks like it came from the
|
| 80 |
+
template source instead of the compiled code. The filename, line
|
| 81 |
+
number, and location name will point to the template, and the local
|
| 82 |
+
variables will be the current template context.
|
| 83 |
+
|
| 84 |
+
:param exc_value: The original exception to be re-raised to create
|
| 85 |
+
the new traceback.
|
| 86 |
+
:param tb: The original traceback to get the local variables and
|
| 87 |
+
code info from.
|
| 88 |
+
:param filename: The template filename.
|
| 89 |
+
:param lineno: The line number in the template source.
|
| 90 |
+
"""
|
| 91 |
+
if tb is not None:
|
| 92 |
+
# Replace the real locals with the context that would be
|
| 93 |
+
# available at that point in the template.
|
| 94 |
+
locals = get_template_locals(tb.tb_frame.f_locals)
|
| 95 |
+
locals.pop("__jinja_exception__", None)
|
| 96 |
+
else:
|
| 97 |
+
locals = {}
|
| 98 |
+
|
| 99 |
+
globals = {
|
| 100 |
+
"__name__": filename,
|
| 101 |
+
"__file__": filename,
|
| 102 |
+
"__jinja_exception__": exc_value,
|
| 103 |
+
}
|
| 104 |
+
# Raise an exception at the correct line number.
|
| 105 |
+
code: CodeType = compile(
|
| 106 |
+
"\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Build a new code object that points to the template file and
|
| 110 |
+
# replaces the location with a block name.
|
| 111 |
+
location = "template"
|
| 112 |
+
|
| 113 |
+
if tb is not None:
|
| 114 |
+
function = tb.tb_frame.f_code.co_name
|
| 115 |
+
|
| 116 |
+
if function == "root":
|
| 117 |
+
location = "top-level template code"
|
| 118 |
+
elif function.startswith("block_"):
|
| 119 |
+
location = f"block {function[6:]!r}"
|
| 120 |
+
|
| 121 |
+
if sys.version_info >= (3, 8):
|
| 122 |
+
code = code.replace(co_name=location)
|
| 123 |
+
else:
|
| 124 |
+
code = CodeType(
|
| 125 |
+
code.co_argcount,
|
| 126 |
+
code.co_kwonlyargcount,
|
| 127 |
+
code.co_nlocals,
|
| 128 |
+
code.co_stacksize,
|
| 129 |
+
code.co_flags,
|
| 130 |
+
code.co_code,
|
| 131 |
+
code.co_consts,
|
| 132 |
+
code.co_names,
|
| 133 |
+
code.co_varnames,
|
| 134 |
+
code.co_filename,
|
| 135 |
+
location,
|
| 136 |
+
code.co_firstlineno,
|
| 137 |
+
code.co_lnotab,
|
| 138 |
+
code.co_freevars,
|
| 139 |
+
code.co_cellvars,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Execute the new code, which is guaranteed to raise, and return
|
| 143 |
+
# the new traceback without this frame.
|
| 144 |
+
try:
|
| 145 |
+
exec(code, globals, locals)
|
| 146 |
+
except BaseException:
|
| 147 |
+
return sys.exc_info()[2].tb_next # type: ignore
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:
|
| 151 |
+
"""Based on the runtime locals, get the context that would be
|
| 152 |
+
available at that point in the template.
|
| 153 |
+
"""
|
| 154 |
+
# Start with the current template context.
|
| 155 |
+
ctx: t.Optional[Context] = real_locals.get("context")
|
| 156 |
+
|
| 157 |
+
if ctx is not None:
|
| 158 |
+
data: t.Dict[str, t.Any] = ctx.get_all().copy()
|
| 159 |
+
else:
|
| 160 |
+
data = {}
|
| 161 |
+
|
| 162 |
+
# Might be in a derived context that only sets local variables
|
| 163 |
+
# rather than pushing a context. Local variables follow the scheme
|
| 164 |
+
# l_depth_name. Find the highest-depth local that has a value for
|
| 165 |
+
# each name.
|
| 166 |
+
local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}
|
| 167 |
+
|
| 168 |
+
for name, value in real_locals.items():
|
| 169 |
+
if not name.startswith("l_") or value is missing:
|
| 170 |
+
# Not a template variable, or no longer relevant.
|
| 171 |
+
continue
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
_, depth_str, name = name.split("_", 2)
|
| 175 |
+
depth = int(depth_str)
|
| 176 |
+
except ValueError:
|
| 177 |
+
continue
|
| 178 |
+
|
| 179 |
+
cur_depth = local_overrides.get(name, (-1,))[0]
|
| 180 |
+
|
| 181 |
+
if cur_depth < depth:
|
| 182 |
+
local_overrides[name] = (depth, value)
|
| 183 |
+
|
| 184 |
+
# Modify the context with any derived context.
|
| 185 |
+
for name, (_, value) in local_overrides.items():
|
| 186 |
+
if value is missing:
|
| 187 |
+
data.pop(name, None)
|
| 188 |
+
else:
|
| 189 |
+
data[name] = value
|
| 190 |
+
|
| 191 |
+
return data
|
wemm/lib/python3.10/site-packages/jinja2/environment.py
ADDED
|
@@ -0,0 +1,1672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classes for managing templates and their runtime and compile time
|
| 2 |
+
options.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import typing
|
| 7 |
+
import typing as t
|
| 8 |
+
import weakref
|
| 9 |
+
from collections import ChainMap
|
| 10 |
+
from functools import lru_cache
|
| 11 |
+
from functools import partial
|
| 12 |
+
from functools import reduce
|
| 13 |
+
from types import CodeType
|
| 14 |
+
|
| 15 |
+
from markupsafe import Markup
|
| 16 |
+
|
| 17 |
+
from . import nodes
|
| 18 |
+
from .compiler import CodeGenerator
|
| 19 |
+
from .compiler import generate
|
| 20 |
+
from .defaults import BLOCK_END_STRING
|
| 21 |
+
from .defaults import BLOCK_START_STRING
|
| 22 |
+
from .defaults import COMMENT_END_STRING
|
| 23 |
+
from .defaults import COMMENT_START_STRING
|
| 24 |
+
from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]
|
| 25 |
+
from .defaults import DEFAULT_NAMESPACE
|
| 26 |
+
from .defaults import DEFAULT_POLICIES
|
| 27 |
+
from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]
|
| 28 |
+
from .defaults import KEEP_TRAILING_NEWLINE
|
| 29 |
+
from .defaults import LINE_COMMENT_PREFIX
|
| 30 |
+
from .defaults import LINE_STATEMENT_PREFIX
|
| 31 |
+
from .defaults import LSTRIP_BLOCKS
|
| 32 |
+
from .defaults import NEWLINE_SEQUENCE
|
| 33 |
+
from .defaults import TRIM_BLOCKS
|
| 34 |
+
from .defaults import VARIABLE_END_STRING
|
| 35 |
+
from .defaults import VARIABLE_START_STRING
|
| 36 |
+
from .exceptions import TemplateNotFound
|
| 37 |
+
from .exceptions import TemplateRuntimeError
|
| 38 |
+
from .exceptions import TemplatesNotFound
|
| 39 |
+
from .exceptions import TemplateSyntaxError
|
| 40 |
+
from .exceptions import UndefinedError
|
| 41 |
+
from .lexer import get_lexer
|
| 42 |
+
from .lexer import Lexer
|
| 43 |
+
from .lexer import TokenStream
|
| 44 |
+
from .nodes import EvalContext
|
| 45 |
+
from .parser import Parser
|
| 46 |
+
from .runtime import Context
|
| 47 |
+
from .runtime import new_context
|
| 48 |
+
from .runtime import Undefined
|
| 49 |
+
from .utils import _PassArg
|
| 50 |
+
from .utils import concat
|
| 51 |
+
from .utils import consume
|
| 52 |
+
from .utils import import_string
|
| 53 |
+
from .utils import internalcode
|
| 54 |
+
from .utils import LRUCache
|
| 55 |
+
from .utils import missing
|
| 56 |
+
|
| 57 |
+
if t.TYPE_CHECKING:
|
| 58 |
+
import typing_extensions as te
|
| 59 |
+
|
| 60 |
+
from .bccache import BytecodeCache
|
| 61 |
+
from .ext import Extension
|
| 62 |
+
from .loaders import BaseLoader
|
| 63 |
+
|
| 64 |
+
_env_bound = t.TypeVar("_env_bound", bound="Environment")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# for direct template usage we have up to ten living environments
|
| 68 |
+
@lru_cache(maxsize=10)
|
| 69 |
+
def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound:
|
| 70 |
+
"""Return a new spontaneous environment. A spontaneous environment
|
| 71 |
+
is used for templates created directly rather than through an
|
| 72 |
+
existing environment.
|
| 73 |
+
|
| 74 |
+
:param cls: Environment class to create.
|
| 75 |
+
:param args: Positional arguments passed to environment.
|
| 76 |
+
"""
|
| 77 |
+
env = cls(*args)
|
| 78 |
+
env.shared = True
|
| 79 |
+
return env
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def create_cache(
|
| 83 |
+
size: int,
|
| 84 |
+
) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:
|
| 85 |
+
"""Return the cache class for the given size."""
|
| 86 |
+
if size == 0:
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
if size < 0:
|
| 90 |
+
return {}
|
| 91 |
+
|
| 92 |
+
return LRUCache(size) # type: ignore
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def copy_cache(
|
| 96 |
+
cache: t.Optional[t.MutableMapping[t.Any, t.Any]],
|
| 97 |
+
) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:
|
| 98 |
+
"""Create an empty copy of the given cache."""
|
| 99 |
+
if cache is None:
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
if type(cache) is dict: # noqa E721
|
| 103 |
+
return {}
|
| 104 |
+
|
| 105 |
+
return LRUCache(cache.capacity) # type: ignore
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def load_extensions(
|
| 109 |
+
environment: "Environment",
|
| 110 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]],
|
| 111 |
+
) -> t.Dict[str, "Extension"]:
|
| 112 |
+
"""Load the extensions from the list and bind it to the environment.
|
| 113 |
+
Returns a dict of instantiated extensions.
|
| 114 |
+
"""
|
| 115 |
+
result = {}
|
| 116 |
+
|
| 117 |
+
for extension in extensions:
|
| 118 |
+
if isinstance(extension, str):
|
| 119 |
+
extension = t.cast(t.Type["Extension"], import_string(extension))
|
| 120 |
+
|
| 121 |
+
result[extension.identifier] = extension(environment)
|
| 122 |
+
|
| 123 |
+
return result
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _environment_config_check(environment: _env_bound) -> _env_bound:
|
| 127 |
+
"""Perform a sanity check on the environment."""
|
| 128 |
+
assert issubclass(
|
| 129 |
+
environment.undefined, Undefined
|
| 130 |
+
), "'undefined' must be a subclass of 'jinja2.Undefined'."
|
| 131 |
+
assert (
|
| 132 |
+
environment.block_start_string
|
| 133 |
+
!= environment.variable_start_string
|
| 134 |
+
!= environment.comment_start_string
|
| 135 |
+
), "block, variable and comment start strings must be different."
|
| 136 |
+
assert environment.newline_sequence in {
|
| 137 |
+
"\r",
|
| 138 |
+
"\r\n",
|
| 139 |
+
"\n",
|
| 140 |
+
}, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."
|
| 141 |
+
return environment
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class Environment:
|
| 145 |
+
r"""The core component of Jinja is the `Environment`. It contains
|
| 146 |
+
important shared variables like configuration, filters, tests,
|
| 147 |
+
globals and others. Instances of this class may be modified if
|
| 148 |
+
they are not shared and if no template was loaded so far.
|
| 149 |
+
Modifications on environments after the first template was loaded
|
| 150 |
+
will lead to surprising effects and undefined behavior.
|
| 151 |
+
|
| 152 |
+
Here are the possible initialization parameters:
|
| 153 |
+
|
| 154 |
+
`block_start_string`
|
| 155 |
+
The string marking the beginning of a block. Defaults to ``'{%'``.
|
| 156 |
+
|
| 157 |
+
`block_end_string`
|
| 158 |
+
The string marking the end of a block. Defaults to ``'%}'``.
|
| 159 |
+
|
| 160 |
+
`variable_start_string`
|
| 161 |
+
The string marking the beginning of a print statement.
|
| 162 |
+
Defaults to ``'{{'``.
|
| 163 |
+
|
| 164 |
+
`variable_end_string`
|
| 165 |
+
The string marking the end of a print statement. Defaults to
|
| 166 |
+
``'}}'``.
|
| 167 |
+
|
| 168 |
+
`comment_start_string`
|
| 169 |
+
The string marking the beginning of a comment. Defaults to ``'{#'``.
|
| 170 |
+
|
| 171 |
+
`comment_end_string`
|
| 172 |
+
The string marking the end of a comment. Defaults to ``'#}'``.
|
| 173 |
+
|
| 174 |
+
`line_statement_prefix`
|
| 175 |
+
If given and a string, this will be used as prefix for line based
|
| 176 |
+
statements. See also :ref:`line-statements`.
|
| 177 |
+
|
| 178 |
+
`line_comment_prefix`
|
| 179 |
+
If given and a string, this will be used as prefix for line based
|
| 180 |
+
comments. See also :ref:`line-statements`.
|
| 181 |
+
|
| 182 |
+
.. versionadded:: 2.2
|
| 183 |
+
|
| 184 |
+
`trim_blocks`
|
| 185 |
+
If this is set to ``True`` the first newline after a block is
|
| 186 |
+
removed (block, not variable tag!). Defaults to `False`.
|
| 187 |
+
|
| 188 |
+
`lstrip_blocks`
|
| 189 |
+
If this is set to ``True`` leading spaces and tabs are stripped
|
| 190 |
+
from the start of a line to a block. Defaults to `False`.
|
| 191 |
+
|
| 192 |
+
`newline_sequence`
|
| 193 |
+
The sequence that starts a newline. Must be one of ``'\r'``,
|
| 194 |
+
``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
|
| 195 |
+
useful default for Linux and OS X systems as well as web
|
| 196 |
+
applications.
|
| 197 |
+
|
| 198 |
+
`keep_trailing_newline`
|
| 199 |
+
Preserve the trailing newline when rendering templates.
|
| 200 |
+
The default is ``False``, which causes a single newline,
|
| 201 |
+
if present, to be stripped from the end of the template.
|
| 202 |
+
|
| 203 |
+
.. versionadded:: 2.7
|
| 204 |
+
|
| 205 |
+
`extensions`
|
| 206 |
+
List of Jinja extensions to use. This can either be import paths
|
| 207 |
+
as strings or extension classes. For more information have a
|
| 208 |
+
look at :ref:`the extensions documentation <jinja-extensions>`.
|
| 209 |
+
|
| 210 |
+
`optimized`
|
| 211 |
+
should the optimizer be enabled? Default is ``True``.
|
| 212 |
+
|
| 213 |
+
`undefined`
|
| 214 |
+
:class:`Undefined` or a subclass of it that is used to represent
|
| 215 |
+
undefined values in the template.
|
| 216 |
+
|
| 217 |
+
`finalize`
|
| 218 |
+
A callable that can be used to process the result of a variable
|
| 219 |
+
expression before it is output. For example one can convert
|
| 220 |
+
``None`` implicitly into an empty string here.
|
| 221 |
+
|
| 222 |
+
`autoescape`
|
| 223 |
+
If set to ``True`` the XML/HTML autoescaping feature is enabled by
|
| 224 |
+
default. For more details about autoescaping see
|
| 225 |
+
:class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
|
| 226 |
+
be a callable that is passed the template name and has to
|
| 227 |
+
return ``True`` or ``False`` depending on autoescape should be
|
| 228 |
+
enabled by default.
|
| 229 |
+
|
| 230 |
+
.. versionchanged:: 2.4
|
| 231 |
+
`autoescape` can now be a function
|
| 232 |
+
|
| 233 |
+
`loader`
|
| 234 |
+
The template loader for this environment.
|
| 235 |
+
|
| 236 |
+
`cache_size`
|
| 237 |
+
The size of the cache. Per default this is ``400`` which means
|
| 238 |
+
that if more than 400 templates are loaded the loader will clean
|
| 239 |
+
out the least recently used template. If the cache size is set to
|
| 240 |
+
``0`` templates are recompiled all the time, if the cache size is
|
| 241 |
+
``-1`` the cache will not be cleaned.
|
| 242 |
+
|
| 243 |
+
.. versionchanged:: 2.8
|
| 244 |
+
The cache size was increased to 400 from a low 50.
|
| 245 |
+
|
| 246 |
+
`auto_reload`
|
| 247 |
+
Some loaders load templates from locations where the template
|
| 248 |
+
sources may change (ie: file system or database). If
|
| 249 |
+
``auto_reload`` is set to ``True`` (default) every time a template is
|
| 250 |
+
requested the loader checks if the source changed and if yes, it
|
| 251 |
+
will reload the template. For higher performance it's possible to
|
| 252 |
+
disable that.
|
| 253 |
+
|
| 254 |
+
`bytecode_cache`
|
| 255 |
+
If set to a bytecode cache object, this object will provide a
|
| 256 |
+
cache for the internal Jinja bytecode so that templates don't
|
| 257 |
+
have to be parsed if they were not changed.
|
| 258 |
+
|
| 259 |
+
See :ref:`bytecode-cache` for more information.
|
| 260 |
+
|
| 261 |
+
`enable_async`
|
| 262 |
+
If set to true this enables async template execution which
|
| 263 |
+
allows using async functions and generators.
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
#: if this environment is sandboxed. Modifying this variable won't make
|
| 267 |
+
#: the environment sandboxed though. For a real sandboxed environment
|
| 268 |
+
#: have a look at jinja2.sandbox. This flag alone controls the code
|
| 269 |
+
#: generation by the compiler.
|
| 270 |
+
sandboxed = False
|
| 271 |
+
|
| 272 |
+
#: True if the environment is just an overlay
|
| 273 |
+
overlayed = False
|
| 274 |
+
|
| 275 |
+
#: the environment this environment is linked to if it is an overlay
|
| 276 |
+
linked_to: t.Optional["Environment"] = None
|
| 277 |
+
|
| 278 |
+
#: shared environments have this set to `True`. A shared environment
|
| 279 |
+
#: must not be modified
|
| 280 |
+
shared = False
|
| 281 |
+
|
| 282 |
+
#: the class that is used for code generation. See
|
| 283 |
+
#: :class:`~jinja2.compiler.CodeGenerator` for more information.
|
| 284 |
+
code_generator_class: t.Type["CodeGenerator"] = CodeGenerator
|
| 285 |
+
|
| 286 |
+
concat = "".join
|
| 287 |
+
|
| 288 |
+
#: the context class that is used for templates. See
|
| 289 |
+
#: :class:`~jinja2.runtime.Context` for more information.
|
| 290 |
+
context_class: t.Type[Context] = Context
|
| 291 |
+
|
| 292 |
+
template_class: t.Type["Template"]
|
| 293 |
+
|
| 294 |
+
def __init__(
|
| 295 |
+
self,
|
| 296 |
+
block_start_string: str = BLOCK_START_STRING,
|
| 297 |
+
block_end_string: str = BLOCK_END_STRING,
|
| 298 |
+
variable_start_string: str = VARIABLE_START_STRING,
|
| 299 |
+
variable_end_string: str = VARIABLE_END_STRING,
|
| 300 |
+
comment_start_string: str = COMMENT_START_STRING,
|
| 301 |
+
comment_end_string: str = COMMENT_END_STRING,
|
| 302 |
+
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
|
| 303 |
+
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
|
| 304 |
+
trim_blocks: bool = TRIM_BLOCKS,
|
| 305 |
+
lstrip_blocks: bool = LSTRIP_BLOCKS,
|
| 306 |
+
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
|
| 307 |
+
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
|
| 308 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
|
| 309 |
+
optimized: bool = True,
|
| 310 |
+
undefined: t.Type[Undefined] = Undefined,
|
| 311 |
+
finalize: t.Optional[t.Callable[..., t.Any]] = None,
|
| 312 |
+
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
|
| 313 |
+
loader: t.Optional["BaseLoader"] = None,
|
| 314 |
+
cache_size: int = 400,
|
| 315 |
+
auto_reload: bool = True,
|
| 316 |
+
bytecode_cache: t.Optional["BytecodeCache"] = None,
|
| 317 |
+
enable_async: bool = False,
|
| 318 |
+
):
|
| 319 |
+
# !!Important notice!!
|
| 320 |
+
# The constructor accepts quite a few arguments that should be
|
| 321 |
+
# passed by keyword rather than position. However it's important to
|
| 322 |
+
# not change the order of arguments because it's used at least
|
| 323 |
+
# internally in those cases:
|
| 324 |
+
# - spontaneous environments (i18n extension and Template)
|
| 325 |
+
# - unittests
|
| 326 |
+
# If parameter changes are required only add parameters at the end
|
| 327 |
+
# and don't change the arguments (or the defaults!) of the arguments
|
| 328 |
+
# existing already.
|
| 329 |
+
|
| 330 |
+
# lexer / parser information
|
| 331 |
+
self.block_start_string = block_start_string
|
| 332 |
+
self.block_end_string = block_end_string
|
| 333 |
+
self.variable_start_string = variable_start_string
|
| 334 |
+
self.variable_end_string = variable_end_string
|
| 335 |
+
self.comment_start_string = comment_start_string
|
| 336 |
+
self.comment_end_string = comment_end_string
|
| 337 |
+
self.line_statement_prefix = line_statement_prefix
|
| 338 |
+
self.line_comment_prefix = line_comment_prefix
|
| 339 |
+
self.trim_blocks = trim_blocks
|
| 340 |
+
self.lstrip_blocks = lstrip_blocks
|
| 341 |
+
self.newline_sequence = newline_sequence
|
| 342 |
+
self.keep_trailing_newline = keep_trailing_newline
|
| 343 |
+
|
| 344 |
+
# runtime information
|
| 345 |
+
self.undefined: t.Type[Undefined] = undefined
|
| 346 |
+
self.optimized = optimized
|
| 347 |
+
self.finalize = finalize
|
| 348 |
+
self.autoescape = autoescape
|
| 349 |
+
|
| 350 |
+
# defaults
|
| 351 |
+
self.filters = DEFAULT_FILTERS.copy()
|
| 352 |
+
self.tests = DEFAULT_TESTS.copy()
|
| 353 |
+
self.globals = DEFAULT_NAMESPACE.copy()
|
| 354 |
+
|
| 355 |
+
# set the loader provided
|
| 356 |
+
self.loader = loader
|
| 357 |
+
self.cache = create_cache(cache_size)
|
| 358 |
+
self.bytecode_cache = bytecode_cache
|
| 359 |
+
self.auto_reload = auto_reload
|
| 360 |
+
|
| 361 |
+
# configurable policies
|
| 362 |
+
self.policies = DEFAULT_POLICIES.copy()
|
| 363 |
+
|
| 364 |
+
# load extensions
|
| 365 |
+
self.extensions = load_extensions(self, extensions)
|
| 366 |
+
|
| 367 |
+
self.is_async = enable_async
|
| 368 |
+
_environment_config_check(self)
|
| 369 |
+
|
| 370 |
+
def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
|
| 371 |
+
"""Adds an extension after the environment was created.
|
| 372 |
+
|
| 373 |
+
.. versionadded:: 2.5
|
| 374 |
+
"""
|
| 375 |
+
self.extensions.update(load_extensions(self, [extension]))
|
| 376 |
+
|
| 377 |
+
def extend(self, **attributes: t.Any) -> None:
|
| 378 |
+
"""Add the items to the instance of the environment if they do not exist
|
| 379 |
+
yet. This is used by :ref:`extensions <writing-extensions>` to register
|
| 380 |
+
callbacks and configuration values without breaking inheritance.
|
| 381 |
+
"""
|
| 382 |
+
for key, value in attributes.items():
|
| 383 |
+
if not hasattr(self, key):
|
| 384 |
+
setattr(self, key, value)
|
| 385 |
+
|
| 386 |
+
def overlay(
|
| 387 |
+
self,
|
| 388 |
+
block_start_string: str = missing,
|
| 389 |
+
block_end_string: str = missing,
|
| 390 |
+
variable_start_string: str = missing,
|
| 391 |
+
variable_end_string: str = missing,
|
| 392 |
+
comment_start_string: str = missing,
|
| 393 |
+
comment_end_string: str = missing,
|
| 394 |
+
line_statement_prefix: t.Optional[str] = missing,
|
| 395 |
+
line_comment_prefix: t.Optional[str] = missing,
|
| 396 |
+
trim_blocks: bool = missing,
|
| 397 |
+
lstrip_blocks: bool = missing,
|
| 398 |
+
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,
|
| 399 |
+
keep_trailing_newline: bool = missing,
|
| 400 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
|
| 401 |
+
optimized: bool = missing,
|
| 402 |
+
undefined: t.Type[Undefined] = missing,
|
| 403 |
+
finalize: t.Optional[t.Callable[..., t.Any]] = missing,
|
| 404 |
+
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
|
| 405 |
+
loader: t.Optional["BaseLoader"] = missing,
|
| 406 |
+
cache_size: int = missing,
|
| 407 |
+
auto_reload: bool = missing,
|
| 408 |
+
bytecode_cache: t.Optional["BytecodeCache"] = missing,
|
| 409 |
+
enable_async: bool = missing,
|
| 410 |
+
) -> "te.Self":
|
| 411 |
+
"""Create a new overlay environment that shares all the data with the
|
| 412 |
+
current environment except for cache and the overridden attributes.
|
| 413 |
+
Extensions cannot be removed for an overlayed environment. An overlayed
|
| 414 |
+
environment automatically gets all the extensions of the environment it
|
| 415 |
+
is linked to plus optional extra extensions.
|
| 416 |
+
|
| 417 |
+
Creating overlays should happen after the initial environment was set
|
| 418 |
+
up completely. Not all attributes are truly linked, some are just
|
| 419 |
+
copied over so modifications on the original environment may not shine
|
| 420 |
+
through.
|
| 421 |
+
|
| 422 |
+
.. versionchanged:: 3.1.5
|
| 423 |
+
``enable_async`` is applied correctly.
|
| 424 |
+
|
| 425 |
+
.. versionchanged:: 3.1.2
|
| 426 |
+
Added the ``newline_sequence``, ``keep_trailing_newline``,
|
| 427 |
+
and ``enable_async`` parameters to match ``__init__``.
|
| 428 |
+
"""
|
| 429 |
+
args = dict(locals())
|
| 430 |
+
del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
|
| 431 |
+
|
| 432 |
+
rv = object.__new__(self.__class__)
|
| 433 |
+
rv.__dict__.update(self.__dict__)
|
| 434 |
+
rv.overlayed = True
|
| 435 |
+
rv.linked_to = self
|
| 436 |
+
|
| 437 |
+
for key, value in args.items():
|
| 438 |
+
if value is not missing:
|
| 439 |
+
setattr(rv, key, value)
|
| 440 |
+
|
| 441 |
+
if cache_size is not missing:
|
| 442 |
+
rv.cache = create_cache(cache_size)
|
| 443 |
+
else:
|
| 444 |
+
rv.cache = copy_cache(self.cache)
|
| 445 |
+
|
| 446 |
+
rv.extensions = {}
|
| 447 |
+
for key, value in self.extensions.items():
|
| 448 |
+
rv.extensions[key] = value.bind(rv)
|
| 449 |
+
if extensions is not missing:
|
| 450 |
+
rv.extensions.update(load_extensions(rv, extensions))
|
| 451 |
+
|
| 452 |
+
if enable_async is not missing:
|
| 453 |
+
rv.is_async = enable_async
|
| 454 |
+
|
| 455 |
+
return _environment_config_check(rv)
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def lexer(self) -> Lexer:
|
| 459 |
+
"""The lexer for this environment."""
|
| 460 |
+
return get_lexer(self)
|
| 461 |
+
|
| 462 |
+
def iter_extensions(self) -> t.Iterator["Extension"]:
|
| 463 |
+
"""Iterates over the extensions by priority."""
|
| 464 |
+
return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
|
| 465 |
+
|
| 466 |
+
def getitem(
|
| 467 |
+
self, obj: t.Any, argument: t.Union[str, t.Any]
|
| 468 |
+
) -> t.Union[t.Any, Undefined]:
|
| 469 |
+
"""Get an item or attribute of an object but prefer the item."""
|
| 470 |
+
try:
|
| 471 |
+
return obj[argument]
|
| 472 |
+
except (AttributeError, TypeError, LookupError):
|
| 473 |
+
if isinstance(argument, str):
|
| 474 |
+
try:
|
| 475 |
+
attr = str(argument)
|
| 476 |
+
except Exception:
|
| 477 |
+
pass
|
| 478 |
+
else:
|
| 479 |
+
try:
|
| 480 |
+
return getattr(obj, attr)
|
| 481 |
+
except AttributeError:
|
| 482 |
+
pass
|
| 483 |
+
return self.undefined(obj=obj, name=argument)
|
| 484 |
+
|
| 485 |
+
def getattr(self, obj: t.Any, attribute: str) -> t.Any:
|
| 486 |
+
"""Get an item or attribute of an object but prefer the attribute.
|
| 487 |
+
Unlike :meth:`getitem` the attribute *must* be a string.
|
| 488 |
+
"""
|
| 489 |
+
try:
|
| 490 |
+
return getattr(obj, attribute)
|
| 491 |
+
except AttributeError:
|
| 492 |
+
pass
|
| 493 |
+
try:
|
| 494 |
+
return obj[attribute]
|
| 495 |
+
except (TypeError, LookupError, AttributeError):
|
| 496 |
+
return self.undefined(obj=obj, name=attribute)
|
| 497 |
+
|
| 498 |
+
def _filter_test_common(
|
| 499 |
+
self,
|
| 500 |
+
name: t.Union[str, Undefined],
|
| 501 |
+
value: t.Any,
|
| 502 |
+
args: t.Optional[t.Sequence[t.Any]],
|
| 503 |
+
kwargs: t.Optional[t.Mapping[str, t.Any]],
|
| 504 |
+
context: t.Optional[Context],
|
| 505 |
+
eval_ctx: t.Optional[EvalContext],
|
| 506 |
+
is_filter: bool,
|
| 507 |
+
) -> t.Any:
|
| 508 |
+
if is_filter:
|
| 509 |
+
env_map = self.filters
|
| 510 |
+
type_name = "filter"
|
| 511 |
+
else:
|
| 512 |
+
env_map = self.tests
|
| 513 |
+
type_name = "test"
|
| 514 |
+
|
| 515 |
+
func = env_map.get(name) # type: ignore
|
| 516 |
+
|
| 517 |
+
if func is None:
|
| 518 |
+
msg = f"No {type_name} named {name!r}."
|
| 519 |
+
|
| 520 |
+
if isinstance(name, Undefined):
|
| 521 |
+
try:
|
| 522 |
+
name._fail_with_undefined_error()
|
| 523 |
+
except Exception as e:
|
| 524 |
+
msg = f"{msg} ({e}; did you forget to quote the callable name?)"
|
| 525 |
+
|
| 526 |
+
raise TemplateRuntimeError(msg)
|
| 527 |
+
|
| 528 |
+
args = [value, *(args if args is not None else ())]
|
| 529 |
+
kwargs = kwargs if kwargs is not None else {}
|
| 530 |
+
pass_arg = _PassArg.from_obj(func)
|
| 531 |
+
|
| 532 |
+
if pass_arg is _PassArg.context:
|
| 533 |
+
if context is None:
|
| 534 |
+
raise TemplateRuntimeError(
|
| 535 |
+
f"Attempted to invoke a context {type_name} without context."
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
args.insert(0, context)
|
| 539 |
+
elif pass_arg is _PassArg.eval_context:
|
| 540 |
+
if eval_ctx is None:
|
| 541 |
+
if context is not None:
|
| 542 |
+
eval_ctx = context.eval_ctx
|
| 543 |
+
else:
|
| 544 |
+
eval_ctx = EvalContext(self)
|
| 545 |
+
|
| 546 |
+
args.insert(0, eval_ctx)
|
| 547 |
+
elif pass_arg is _PassArg.environment:
|
| 548 |
+
args.insert(0, self)
|
| 549 |
+
|
| 550 |
+
return func(*args, **kwargs)
|
| 551 |
+
|
| 552 |
+
def call_filter(
|
| 553 |
+
self,
|
| 554 |
+
name: str,
|
| 555 |
+
value: t.Any,
|
| 556 |
+
args: t.Optional[t.Sequence[t.Any]] = None,
|
| 557 |
+
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
|
| 558 |
+
context: t.Optional[Context] = None,
|
| 559 |
+
eval_ctx: t.Optional[EvalContext] = None,
|
| 560 |
+
) -> t.Any:
|
| 561 |
+
"""Invoke a filter on a value the same way the compiler does.
|
| 562 |
+
|
| 563 |
+
This might return a coroutine if the filter is running from an
|
| 564 |
+
environment in async mode and the filter supports async
|
| 565 |
+
execution. It's your responsibility to await this if needed.
|
| 566 |
+
|
| 567 |
+
.. versionadded:: 2.7
|
| 568 |
+
"""
|
| 569 |
+
return self._filter_test_common(
|
| 570 |
+
name, value, args, kwargs, context, eval_ctx, True
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
def call_test(
|
| 574 |
+
self,
|
| 575 |
+
name: str,
|
| 576 |
+
value: t.Any,
|
| 577 |
+
args: t.Optional[t.Sequence[t.Any]] = None,
|
| 578 |
+
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
|
| 579 |
+
context: t.Optional[Context] = None,
|
| 580 |
+
eval_ctx: t.Optional[EvalContext] = None,
|
| 581 |
+
) -> t.Any:
|
| 582 |
+
"""Invoke a test on a value the same way the compiler does.
|
| 583 |
+
|
| 584 |
+
This might return a coroutine if the test is running from an
|
| 585 |
+
environment in async mode and the test supports async execution.
|
| 586 |
+
It's your responsibility to await this if needed.
|
| 587 |
+
|
| 588 |
+
.. versionchanged:: 3.0
|
| 589 |
+
Tests support ``@pass_context``, etc. decorators. Added
|
| 590 |
+
the ``context`` and ``eval_ctx`` parameters.
|
| 591 |
+
|
| 592 |
+
.. versionadded:: 2.7
|
| 593 |
+
"""
|
| 594 |
+
return self._filter_test_common(
|
| 595 |
+
name, value, args, kwargs, context, eval_ctx, False
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
@internalcode
|
| 599 |
+
def parse(
|
| 600 |
+
self,
|
| 601 |
+
source: str,
|
| 602 |
+
name: t.Optional[str] = None,
|
| 603 |
+
filename: t.Optional[str] = None,
|
| 604 |
+
) -> nodes.Template:
|
| 605 |
+
"""Parse the sourcecode and return the abstract syntax tree. This
|
| 606 |
+
tree of nodes is used by the compiler to convert the template into
|
| 607 |
+
executable source- or bytecode. This is useful for debugging or to
|
| 608 |
+
extract information from templates.
|
| 609 |
+
|
| 610 |
+
If you are :ref:`developing Jinja extensions <writing-extensions>`
|
| 611 |
+
this gives you a good overview of the node tree generated.
|
| 612 |
+
"""
|
| 613 |
+
try:
|
| 614 |
+
return self._parse(source, name, filename)
|
| 615 |
+
except TemplateSyntaxError:
|
| 616 |
+
self.handle_exception(source=source)
|
| 617 |
+
|
| 618 |
+
def _parse(
|
| 619 |
+
self, source: str, name: t.Optional[str], filename: t.Optional[str]
|
| 620 |
+
) -> nodes.Template:
|
| 621 |
+
"""Internal parsing function used by `parse` and `compile`."""
|
| 622 |
+
return Parser(self, source, name, filename).parse()
|
| 623 |
+
|
| 624 |
+
def lex(
|
| 625 |
+
self,
|
| 626 |
+
source: str,
|
| 627 |
+
name: t.Optional[str] = None,
|
| 628 |
+
filename: t.Optional[str] = None,
|
| 629 |
+
) -> t.Iterator[t.Tuple[int, str, str]]:
|
| 630 |
+
"""Lex the given sourcecode and return a generator that yields
|
| 631 |
+
tokens as tuples in the form ``(lineno, token_type, value)``.
|
| 632 |
+
This can be useful for :ref:`extension development <writing-extensions>`
|
| 633 |
+
and debugging templates.
|
| 634 |
+
|
| 635 |
+
This does not perform preprocessing. If you want the preprocessing
|
| 636 |
+
of the extensions to be applied you have to filter source through
|
| 637 |
+
the :meth:`preprocess` method.
|
| 638 |
+
"""
|
| 639 |
+
source = str(source)
|
| 640 |
+
try:
|
| 641 |
+
return self.lexer.tokeniter(source, name, filename)
|
| 642 |
+
except TemplateSyntaxError:
|
| 643 |
+
self.handle_exception(source=source)
|
| 644 |
+
|
| 645 |
+
def preprocess(
|
| 646 |
+
self,
|
| 647 |
+
source: str,
|
| 648 |
+
name: t.Optional[str] = None,
|
| 649 |
+
filename: t.Optional[str] = None,
|
| 650 |
+
) -> str:
|
| 651 |
+
"""Preprocesses the source with all extensions. This is automatically
|
| 652 |
+
called for all parsing and compiling methods but *not* for :meth:`lex`
|
| 653 |
+
because there you usually only want the actual source tokenized.
|
| 654 |
+
"""
|
| 655 |
+
return reduce(
|
| 656 |
+
lambda s, e: e.preprocess(s, name, filename),
|
| 657 |
+
self.iter_extensions(),
|
| 658 |
+
str(source),
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
def _tokenize(
|
| 662 |
+
self,
|
| 663 |
+
source: str,
|
| 664 |
+
name: t.Optional[str],
|
| 665 |
+
filename: t.Optional[str] = None,
|
| 666 |
+
state: t.Optional[str] = None,
|
| 667 |
+
) -> TokenStream:
|
| 668 |
+
"""Called by the parser to do the preprocessing and filtering
|
| 669 |
+
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
|
| 670 |
+
"""
|
| 671 |
+
source = self.preprocess(source, name, filename)
|
| 672 |
+
stream = self.lexer.tokenize(source, name, filename, state)
|
| 673 |
+
|
| 674 |
+
for ext in self.iter_extensions():
|
| 675 |
+
stream = ext.filter_stream(stream) # type: ignore
|
| 676 |
+
|
| 677 |
+
if not isinstance(stream, TokenStream):
|
| 678 |
+
stream = TokenStream(stream, name, filename)
|
| 679 |
+
|
| 680 |
+
return stream
|
| 681 |
+
|
| 682 |
+
def _generate(
|
| 683 |
+
self,
|
| 684 |
+
source: nodes.Template,
|
| 685 |
+
name: t.Optional[str],
|
| 686 |
+
filename: t.Optional[str],
|
| 687 |
+
defer_init: bool = False,
|
| 688 |
+
) -> str:
|
| 689 |
+
"""Internal hook that can be overridden to hook a different generate
|
| 690 |
+
method in.
|
| 691 |
+
|
| 692 |
+
.. versionadded:: 2.5
|
| 693 |
+
"""
|
| 694 |
+
return generate( # type: ignore
|
| 695 |
+
source,
|
| 696 |
+
self,
|
| 697 |
+
name,
|
| 698 |
+
filename,
|
| 699 |
+
defer_init=defer_init,
|
| 700 |
+
optimized=self.optimized,
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
def _compile(self, source: str, filename: str) -> CodeType:
|
| 704 |
+
"""Internal hook that can be overridden to hook a different compile
|
| 705 |
+
method in.
|
| 706 |
+
|
| 707 |
+
.. versionadded:: 2.5
|
| 708 |
+
"""
|
| 709 |
+
return compile(source, filename, "exec")
|
| 710 |
+
|
| 711 |
+
@typing.overload
|
| 712 |
+
def compile(
|
| 713 |
+
self,
|
| 714 |
+
source: t.Union[str, nodes.Template],
|
| 715 |
+
name: t.Optional[str] = None,
|
| 716 |
+
filename: t.Optional[str] = None,
|
| 717 |
+
raw: "te.Literal[False]" = False,
|
| 718 |
+
defer_init: bool = False,
|
| 719 |
+
) -> CodeType: ...
|
| 720 |
+
|
| 721 |
+
@typing.overload
|
| 722 |
+
def compile(
|
| 723 |
+
self,
|
| 724 |
+
source: t.Union[str, nodes.Template],
|
| 725 |
+
name: t.Optional[str] = None,
|
| 726 |
+
filename: t.Optional[str] = None,
|
| 727 |
+
raw: "te.Literal[True]" = ...,
|
| 728 |
+
defer_init: bool = False,
|
| 729 |
+
) -> str: ...
|
| 730 |
+
|
| 731 |
+
@internalcode
|
| 732 |
+
def compile(
|
| 733 |
+
self,
|
| 734 |
+
source: t.Union[str, nodes.Template],
|
| 735 |
+
name: t.Optional[str] = None,
|
| 736 |
+
filename: t.Optional[str] = None,
|
| 737 |
+
raw: bool = False,
|
| 738 |
+
defer_init: bool = False,
|
| 739 |
+
) -> t.Union[str, CodeType]:
|
| 740 |
+
"""Compile a node or template source code. The `name` parameter is
|
| 741 |
+
the load name of the template after it was joined using
|
| 742 |
+
:meth:`join_path` if necessary, not the filename on the file system.
|
| 743 |
+
the `filename` parameter is the estimated filename of the template on
|
| 744 |
+
the file system. If the template came from a database or memory this
|
| 745 |
+
can be omitted.
|
| 746 |
+
|
| 747 |
+
The return value of this method is a python code object. If the `raw`
|
| 748 |
+
parameter is `True` the return value will be a string with python
|
| 749 |
+
code equivalent to the bytecode returned otherwise. This method is
|
| 750 |
+
mainly used internally.
|
| 751 |
+
|
| 752 |
+
`defer_init` is use internally to aid the module code generator. This
|
| 753 |
+
causes the generated code to be able to import without the global
|
| 754 |
+
environment variable to be set.
|
| 755 |
+
|
| 756 |
+
.. versionadded:: 2.4
|
| 757 |
+
`defer_init` parameter added.
|
| 758 |
+
"""
|
| 759 |
+
source_hint = None
|
| 760 |
+
try:
|
| 761 |
+
if isinstance(source, str):
|
| 762 |
+
source_hint = source
|
| 763 |
+
source = self._parse(source, name, filename)
|
| 764 |
+
source = self._generate(source, name, filename, defer_init=defer_init)
|
| 765 |
+
if raw:
|
| 766 |
+
return source
|
| 767 |
+
if filename is None:
|
| 768 |
+
filename = "<template>"
|
| 769 |
+
return self._compile(source, filename)
|
| 770 |
+
except TemplateSyntaxError:
|
| 771 |
+
self.handle_exception(source=source_hint)
|
| 772 |
+
|
| 773 |
+
def compile_expression(
|
| 774 |
+
self, source: str, undefined_to_none: bool = True
|
| 775 |
+
) -> "TemplateExpression":
|
| 776 |
+
"""A handy helper method that returns a callable that accepts keyword
|
| 777 |
+
arguments that appear as variables in the expression. If called it
|
| 778 |
+
returns the result of the expression.
|
| 779 |
+
|
| 780 |
+
This is useful if applications want to use the same rules as Jinja
|
| 781 |
+
in template "configuration files" or similar situations.
|
| 782 |
+
|
| 783 |
+
Example usage:
|
| 784 |
+
|
| 785 |
+
>>> env = Environment()
|
| 786 |
+
>>> expr = env.compile_expression('foo == 42')
|
| 787 |
+
>>> expr(foo=23)
|
| 788 |
+
False
|
| 789 |
+
>>> expr(foo=42)
|
| 790 |
+
True
|
| 791 |
+
|
| 792 |
+
Per default the return value is converted to `None` if the
|
| 793 |
+
expression returns an undefined value. This can be changed
|
| 794 |
+
by setting `undefined_to_none` to `False`.
|
| 795 |
+
|
| 796 |
+
>>> env.compile_expression('var')() is None
|
| 797 |
+
True
|
| 798 |
+
>>> env.compile_expression('var', undefined_to_none=False)()
|
| 799 |
+
Undefined
|
| 800 |
+
|
| 801 |
+
.. versionadded:: 2.1
|
| 802 |
+
"""
|
| 803 |
+
parser = Parser(self, source, state="variable")
|
| 804 |
+
try:
|
| 805 |
+
expr = parser.parse_expression()
|
| 806 |
+
if not parser.stream.eos:
|
| 807 |
+
raise TemplateSyntaxError(
|
| 808 |
+
"chunk after expression", parser.stream.current.lineno, None, None
|
| 809 |
+
)
|
| 810 |
+
expr.set_environment(self)
|
| 811 |
+
except TemplateSyntaxError:
|
| 812 |
+
self.handle_exception(source=source)
|
| 813 |
+
|
| 814 |
+
body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
|
| 815 |
+
template = self.from_string(nodes.Template(body, lineno=1))
|
| 816 |
+
return TemplateExpression(template, undefined_to_none)
|
| 817 |
+
|
| 818 |
+
def compile_templates(
|
| 819 |
+
self,
|
| 820 |
+
target: t.Union[str, "os.PathLike[str]"],
|
| 821 |
+
extensions: t.Optional[t.Collection[str]] = None,
|
| 822 |
+
filter_func: t.Optional[t.Callable[[str], bool]] = None,
|
| 823 |
+
zip: t.Optional[str] = "deflated",
|
| 824 |
+
log_function: t.Optional[t.Callable[[str], None]] = None,
|
| 825 |
+
ignore_errors: bool = True,
|
| 826 |
+
) -> None:
|
| 827 |
+
"""Finds all the templates the loader can find, compiles them
|
| 828 |
+
and stores them in `target`. If `zip` is `None`, instead of in a
|
| 829 |
+
zipfile, the templates will be stored in a directory.
|
| 830 |
+
By default a deflate zip algorithm is used. To switch to
|
| 831 |
+
the stored algorithm, `zip` can be set to ``'stored'``.
|
| 832 |
+
|
| 833 |
+
`extensions` and `filter_func` are passed to :meth:`list_templates`.
|
| 834 |
+
Each template returned will be compiled to the target folder or
|
| 835 |
+
zipfile.
|
| 836 |
+
|
| 837 |
+
By default template compilation errors are ignored. In case a
|
| 838 |
+
log function is provided, errors are logged. If you want template
|
| 839 |
+
syntax errors to abort the compilation you can set `ignore_errors`
|
| 840 |
+
to `False` and you will get an exception on syntax errors.
|
| 841 |
+
|
| 842 |
+
.. versionadded:: 2.4
|
| 843 |
+
"""
|
| 844 |
+
from .loaders import ModuleLoader
|
| 845 |
+
|
| 846 |
+
if log_function is None:
|
| 847 |
+
|
| 848 |
+
def log_function(x: str) -> None:
|
| 849 |
+
pass
|
| 850 |
+
|
| 851 |
+
assert log_function is not None
|
| 852 |
+
assert self.loader is not None, "No loader configured."
|
| 853 |
+
|
| 854 |
+
def write_file(filename: str, data: str) -> None:
|
| 855 |
+
if zip:
|
| 856 |
+
info = ZipInfo(filename)
|
| 857 |
+
info.external_attr = 0o755 << 16
|
| 858 |
+
zip_file.writestr(info, data)
|
| 859 |
+
else:
|
| 860 |
+
with open(os.path.join(target, filename), "wb") as f:
|
| 861 |
+
f.write(data.encode("utf8"))
|
| 862 |
+
|
| 863 |
+
if zip is not None:
|
| 864 |
+
from zipfile import ZIP_DEFLATED
|
| 865 |
+
from zipfile import ZIP_STORED
|
| 866 |
+
from zipfile import ZipFile
|
| 867 |
+
from zipfile import ZipInfo
|
| 868 |
+
|
| 869 |
+
zip_file = ZipFile(
|
| 870 |
+
target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
|
| 871 |
+
)
|
| 872 |
+
log_function(f"Compiling into Zip archive {target!r}")
|
| 873 |
+
else:
|
| 874 |
+
if not os.path.isdir(target):
|
| 875 |
+
os.makedirs(target)
|
| 876 |
+
log_function(f"Compiling into folder {target!r}")
|
| 877 |
+
|
| 878 |
+
try:
|
| 879 |
+
for name in self.list_templates(extensions, filter_func):
|
| 880 |
+
source, filename, _ = self.loader.get_source(self, name)
|
| 881 |
+
try:
|
| 882 |
+
code = self.compile(source, name, filename, True, True)
|
| 883 |
+
except TemplateSyntaxError as e:
|
| 884 |
+
if not ignore_errors:
|
| 885 |
+
raise
|
| 886 |
+
log_function(f'Could not compile "{name}": {e}')
|
| 887 |
+
continue
|
| 888 |
+
|
| 889 |
+
filename = ModuleLoader.get_module_filename(name)
|
| 890 |
+
|
| 891 |
+
write_file(filename, code)
|
| 892 |
+
log_function(f'Compiled "{name}" as {filename}')
|
| 893 |
+
finally:
|
| 894 |
+
if zip:
|
| 895 |
+
zip_file.close()
|
| 896 |
+
|
| 897 |
+
log_function("Finished compiling templates")
|
| 898 |
+
|
| 899 |
+
def list_templates(
|
| 900 |
+
self,
|
| 901 |
+
extensions: t.Optional[t.Collection[str]] = None,
|
| 902 |
+
filter_func: t.Optional[t.Callable[[str], bool]] = None,
|
| 903 |
+
) -> t.List[str]:
|
| 904 |
+
"""Returns a list of templates for this environment. This requires
|
| 905 |
+
that the loader supports the loader's
|
| 906 |
+
:meth:`~BaseLoader.list_templates` method.
|
| 907 |
+
|
| 908 |
+
If there are other files in the template folder besides the
|
| 909 |
+
actual templates, the returned list can be filtered. There are two
|
| 910 |
+
ways: either `extensions` is set to a list of file extensions for
|
| 911 |
+
templates, or a `filter_func` can be provided which is a callable that
|
| 912 |
+
is passed a template name and should return `True` if it should end up
|
| 913 |
+
in the result list.
|
| 914 |
+
|
| 915 |
+
If the loader does not support that, a :exc:`TypeError` is raised.
|
| 916 |
+
|
| 917 |
+
.. versionadded:: 2.4
|
| 918 |
+
"""
|
| 919 |
+
assert self.loader is not None, "No loader configured."
|
| 920 |
+
names = self.loader.list_templates()
|
| 921 |
+
|
| 922 |
+
if extensions is not None:
|
| 923 |
+
if filter_func is not None:
|
| 924 |
+
raise TypeError(
|
| 925 |
+
"either extensions or filter_func can be passed, but not both"
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
def filter_func(x: str) -> bool:
|
| 929 |
+
return "." in x and x.rsplit(".", 1)[1] in extensions
|
| 930 |
+
|
| 931 |
+
if filter_func is not None:
|
| 932 |
+
names = [name for name in names if filter_func(name)]
|
| 933 |
+
|
| 934 |
+
return names
|
| 935 |
+
|
| 936 |
+
def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
|
| 937 |
+
"""Exception handling helper. This is used internally to either raise
|
| 938 |
+
rewritten exceptions or return a rendered traceback for the template.
|
| 939 |
+
"""
|
| 940 |
+
from .debug import rewrite_traceback_stack
|
| 941 |
+
|
| 942 |
+
raise rewrite_traceback_stack(source=source)
|
| 943 |
+
|
| 944 |
+
def join_path(self, template: str, parent: str) -> str:
|
| 945 |
+
"""Join a template with the parent. By default all the lookups are
|
| 946 |
+
relative to the loader root so this method returns the `template`
|
| 947 |
+
parameter unchanged, but if the paths should be relative to the
|
| 948 |
+
parent template, this function can be used to calculate the real
|
| 949 |
+
template name.
|
| 950 |
+
|
| 951 |
+
Subclasses may override this method and implement template path
|
| 952 |
+
joining here.
|
| 953 |
+
"""
|
| 954 |
+
return template
|
| 955 |
+
|
| 956 |
+
@internalcode
|
| 957 |
+
def _load_template(
|
| 958 |
+
self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]
|
| 959 |
+
) -> "Template":
|
| 960 |
+
if self.loader is None:
|
| 961 |
+
raise TypeError("no loader for this environment specified")
|
| 962 |
+
cache_key = (weakref.ref(self.loader), name)
|
| 963 |
+
if self.cache is not None:
|
| 964 |
+
template = self.cache.get(cache_key)
|
| 965 |
+
if template is not None and (
|
| 966 |
+
not self.auto_reload or template.is_up_to_date
|
| 967 |
+
):
|
| 968 |
+
# template.globals is a ChainMap, modifying it will only
|
| 969 |
+
# affect the template, not the environment globals.
|
| 970 |
+
if globals:
|
| 971 |
+
template.globals.update(globals)
|
| 972 |
+
|
| 973 |
+
return template
|
| 974 |
+
|
| 975 |
+
template = self.loader.load(self, name, self.make_globals(globals))
|
| 976 |
+
|
| 977 |
+
if self.cache is not None:
|
| 978 |
+
self.cache[cache_key] = template
|
| 979 |
+
return template
|
| 980 |
+
|
| 981 |
+
@internalcode
|
| 982 |
+
def get_template(
|
| 983 |
+
self,
|
| 984 |
+
name: t.Union[str, "Template"],
|
| 985 |
+
parent: t.Optional[str] = None,
|
| 986 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 987 |
+
) -> "Template":
|
| 988 |
+
"""Load a template by name with :attr:`loader` and return a
|
| 989 |
+
:class:`Template`. If the template does not exist a
|
| 990 |
+
:exc:`TemplateNotFound` exception is raised.
|
| 991 |
+
|
| 992 |
+
:param name: Name of the template to load. When loading
|
| 993 |
+
templates from the filesystem, "/" is used as the path
|
| 994 |
+
separator, even on Windows.
|
| 995 |
+
:param parent: The name of the parent template importing this
|
| 996 |
+
template. :meth:`join_path` can be used to implement name
|
| 997 |
+
transformations with this.
|
| 998 |
+
:param globals: Extend the environment :attr:`globals` with
|
| 999 |
+
these extra variables available for all renders of this
|
| 1000 |
+
template. If the template has already been loaded and
|
| 1001 |
+
cached, its globals are updated with any new items.
|
| 1002 |
+
|
| 1003 |
+
.. versionchanged:: 3.0
|
| 1004 |
+
If a template is loaded from cache, ``globals`` will update
|
| 1005 |
+
the template's globals instead of ignoring the new values.
|
| 1006 |
+
|
| 1007 |
+
.. versionchanged:: 2.4
|
| 1008 |
+
If ``name`` is a :class:`Template` object it is returned
|
| 1009 |
+
unchanged.
|
| 1010 |
+
"""
|
| 1011 |
+
if isinstance(name, Template):
|
| 1012 |
+
return name
|
| 1013 |
+
if parent is not None:
|
| 1014 |
+
name = self.join_path(name, parent)
|
| 1015 |
+
|
| 1016 |
+
return self._load_template(name, globals)
|
| 1017 |
+
|
| 1018 |
+
@internalcode
|
| 1019 |
+
def select_template(
|
| 1020 |
+
self,
|
| 1021 |
+
names: t.Iterable[t.Union[str, "Template"]],
|
| 1022 |
+
parent: t.Optional[str] = None,
|
| 1023 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 1024 |
+
) -> "Template":
|
| 1025 |
+
"""Like :meth:`get_template`, but tries loading multiple names.
|
| 1026 |
+
If none of the names can be loaded a :exc:`TemplatesNotFound`
|
| 1027 |
+
exception is raised.
|
| 1028 |
+
|
| 1029 |
+
:param names: List of template names to try loading in order.
|
| 1030 |
+
:param parent: The name of the parent template importing this
|
| 1031 |
+
template. :meth:`join_path` can be used to implement name
|
| 1032 |
+
transformations with this.
|
| 1033 |
+
:param globals: Extend the environment :attr:`globals` with
|
| 1034 |
+
these extra variables available for all renders of this
|
| 1035 |
+
template. If the template has already been loaded and
|
| 1036 |
+
cached, its globals are updated with any new items.
|
| 1037 |
+
|
| 1038 |
+
.. versionchanged:: 3.0
|
| 1039 |
+
If a template is loaded from cache, ``globals`` will update
|
| 1040 |
+
the template's globals instead of ignoring the new values.
|
| 1041 |
+
|
| 1042 |
+
.. versionchanged:: 2.11
|
| 1043 |
+
If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
|
| 1044 |
+
is raised instead. If no templates were found and ``names``
|
| 1045 |
+
contains :class:`Undefined`, the message is more helpful.
|
| 1046 |
+
|
| 1047 |
+
.. versionchanged:: 2.4
|
| 1048 |
+
If ``names`` contains a :class:`Template` object it is
|
| 1049 |
+
returned unchanged.
|
| 1050 |
+
|
| 1051 |
+
.. versionadded:: 2.3
|
| 1052 |
+
"""
|
| 1053 |
+
if isinstance(names, Undefined):
|
| 1054 |
+
names._fail_with_undefined_error()
|
| 1055 |
+
|
| 1056 |
+
if not names:
|
| 1057 |
+
raise TemplatesNotFound(
|
| 1058 |
+
message="Tried to select from an empty list of templates."
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
for name in names:
|
| 1062 |
+
if isinstance(name, Template):
|
| 1063 |
+
return name
|
| 1064 |
+
if parent is not None:
|
| 1065 |
+
name = self.join_path(name, parent)
|
| 1066 |
+
try:
|
| 1067 |
+
return self._load_template(name, globals)
|
| 1068 |
+
except (TemplateNotFound, UndefinedError):
|
| 1069 |
+
pass
|
| 1070 |
+
raise TemplatesNotFound(names) # type: ignore
|
| 1071 |
+
|
| 1072 |
+
@internalcode
|
| 1073 |
+
def get_or_select_template(
|
| 1074 |
+
self,
|
| 1075 |
+
template_name_or_list: t.Union[
|
| 1076 |
+
str, "Template", t.List[t.Union[str, "Template"]]
|
| 1077 |
+
],
|
| 1078 |
+
parent: t.Optional[str] = None,
|
| 1079 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 1080 |
+
) -> "Template":
|
| 1081 |
+
"""Use :meth:`select_template` if an iterable of template names
|
| 1082 |
+
is given, or :meth:`get_template` if one name is given.
|
| 1083 |
+
|
| 1084 |
+
.. versionadded:: 2.3
|
| 1085 |
+
"""
|
| 1086 |
+
if isinstance(template_name_or_list, (str, Undefined)):
|
| 1087 |
+
return self.get_template(template_name_or_list, parent, globals)
|
| 1088 |
+
elif isinstance(template_name_or_list, Template):
|
| 1089 |
+
return template_name_or_list
|
| 1090 |
+
return self.select_template(template_name_or_list, parent, globals)
|
| 1091 |
+
|
| 1092 |
+
def from_string(
|
| 1093 |
+
self,
|
| 1094 |
+
source: t.Union[str, nodes.Template],
|
| 1095 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 1096 |
+
template_class: t.Optional[t.Type["Template"]] = None,
|
| 1097 |
+
) -> "Template":
|
| 1098 |
+
"""Load a template from a source string without using
|
| 1099 |
+
:attr:`loader`.
|
| 1100 |
+
|
| 1101 |
+
:param source: Jinja source to compile into a template.
|
| 1102 |
+
:param globals: Extend the environment :attr:`globals` with
|
| 1103 |
+
these extra variables available for all renders of this
|
| 1104 |
+
template. If the template has already been loaded and
|
| 1105 |
+
cached, its globals are updated with any new items.
|
| 1106 |
+
:param template_class: Return an instance of this
|
| 1107 |
+
:class:`Template` class.
|
| 1108 |
+
"""
|
| 1109 |
+
gs = self.make_globals(globals)
|
| 1110 |
+
cls = template_class or self.template_class
|
| 1111 |
+
return cls.from_code(self, self.compile(source), gs, None)
|
| 1112 |
+
|
| 1113 |
+
def make_globals(
|
| 1114 |
+
self, d: t.Optional[t.MutableMapping[str, t.Any]]
|
| 1115 |
+
) -> t.MutableMapping[str, t.Any]:
|
| 1116 |
+
"""Make the globals map for a template. Any given template
|
| 1117 |
+
globals overlay the environment :attr:`globals`.
|
| 1118 |
+
|
| 1119 |
+
Returns a :class:`collections.ChainMap`. This allows any changes
|
| 1120 |
+
to a template's globals to only affect that template, while
|
| 1121 |
+
changes to the environment's globals are still reflected.
|
| 1122 |
+
However, avoid modifying any globals after a template is loaded.
|
| 1123 |
+
|
| 1124 |
+
:param d: Dict of template-specific globals.
|
| 1125 |
+
|
| 1126 |
+
.. versionchanged:: 3.0
|
| 1127 |
+
Use :class:`collections.ChainMap` to always prevent mutating
|
| 1128 |
+
environment globals.
|
| 1129 |
+
"""
|
| 1130 |
+
if d is None:
|
| 1131 |
+
d = {}
|
| 1132 |
+
|
| 1133 |
+
return ChainMap(d, self.globals)
|
| 1134 |
+
|
| 1135 |
+
|
| 1136 |
+
class Template:
|
| 1137 |
+
"""A compiled template that can be rendered.
|
| 1138 |
+
|
| 1139 |
+
Use the methods on :class:`Environment` to create or load templates.
|
| 1140 |
+
The environment is used to configure how templates are compiled and
|
| 1141 |
+
behave.
|
| 1142 |
+
|
| 1143 |
+
It is also possible to create a template object directly. This is
|
| 1144 |
+
not usually recommended. The constructor takes most of the same
|
| 1145 |
+
arguments as :class:`Environment`. All templates created with the
|
| 1146 |
+
same environment arguments share the same ephemeral ``Environment``
|
| 1147 |
+
instance behind the scenes.
|
| 1148 |
+
|
| 1149 |
+
A template object should be considered immutable. Modifications on
|
| 1150 |
+
the object are not supported.
|
| 1151 |
+
"""
|
| 1152 |
+
|
| 1153 |
+
#: Type of environment to create when creating a template directly
|
| 1154 |
+
#: rather than through an existing environment.
|
| 1155 |
+
environment_class: t.Type[Environment] = Environment
|
| 1156 |
+
|
| 1157 |
+
environment: Environment
|
| 1158 |
+
globals: t.MutableMapping[str, t.Any]
|
| 1159 |
+
name: t.Optional[str]
|
| 1160 |
+
filename: t.Optional[str]
|
| 1161 |
+
blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]]
|
| 1162 |
+
root_render_func: t.Callable[[Context], t.Iterator[str]]
|
| 1163 |
+
_module: t.Optional["TemplateModule"]
|
| 1164 |
+
_debug_info: str
|
| 1165 |
+
_uptodate: t.Optional[t.Callable[[], bool]]
|
| 1166 |
+
|
| 1167 |
+
def __new__(
|
| 1168 |
+
cls,
|
| 1169 |
+
source: t.Union[str, nodes.Template],
|
| 1170 |
+
block_start_string: str = BLOCK_START_STRING,
|
| 1171 |
+
block_end_string: str = BLOCK_END_STRING,
|
| 1172 |
+
variable_start_string: str = VARIABLE_START_STRING,
|
| 1173 |
+
variable_end_string: str = VARIABLE_END_STRING,
|
| 1174 |
+
comment_start_string: str = COMMENT_START_STRING,
|
| 1175 |
+
comment_end_string: str = COMMENT_END_STRING,
|
| 1176 |
+
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
|
| 1177 |
+
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
|
| 1178 |
+
trim_blocks: bool = TRIM_BLOCKS,
|
| 1179 |
+
lstrip_blocks: bool = LSTRIP_BLOCKS,
|
| 1180 |
+
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
|
| 1181 |
+
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
|
| 1182 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
|
| 1183 |
+
optimized: bool = True,
|
| 1184 |
+
undefined: t.Type[Undefined] = Undefined,
|
| 1185 |
+
finalize: t.Optional[t.Callable[..., t.Any]] = None,
|
| 1186 |
+
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
|
| 1187 |
+
enable_async: bool = False,
|
| 1188 |
+
) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...
|
| 1189 |
+
env = get_spontaneous_environment(
|
| 1190 |
+
cls.environment_class, # type: ignore
|
| 1191 |
+
block_start_string,
|
| 1192 |
+
block_end_string,
|
| 1193 |
+
variable_start_string,
|
| 1194 |
+
variable_end_string,
|
| 1195 |
+
comment_start_string,
|
| 1196 |
+
comment_end_string,
|
| 1197 |
+
line_statement_prefix,
|
| 1198 |
+
line_comment_prefix,
|
| 1199 |
+
trim_blocks,
|
| 1200 |
+
lstrip_blocks,
|
| 1201 |
+
newline_sequence,
|
| 1202 |
+
keep_trailing_newline,
|
| 1203 |
+
frozenset(extensions),
|
| 1204 |
+
optimized,
|
| 1205 |
+
undefined, # type: ignore
|
| 1206 |
+
finalize,
|
| 1207 |
+
autoescape,
|
| 1208 |
+
None,
|
| 1209 |
+
0,
|
| 1210 |
+
False,
|
| 1211 |
+
None,
|
| 1212 |
+
enable_async,
|
| 1213 |
+
)
|
| 1214 |
+
return env.from_string(source, template_class=cls)
|
| 1215 |
+
|
| 1216 |
+
@classmethod
|
| 1217 |
+
def from_code(
|
| 1218 |
+
cls,
|
| 1219 |
+
environment: Environment,
|
| 1220 |
+
code: CodeType,
|
| 1221 |
+
globals: t.MutableMapping[str, t.Any],
|
| 1222 |
+
uptodate: t.Optional[t.Callable[[], bool]] = None,
|
| 1223 |
+
) -> "Template":
|
| 1224 |
+
"""Creates a template object from compiled code and the globals. This
|
| 1225 |
+
is used by the loaders and environment to create a template object.
|
| 1226 |
+
"""
|
| 1227 |
+
namespace = {"environment": environment, "__file__": code.co_filename}
|
| 1228 |
+
exec(code, namespace)
|
| 1229 |
+
rv = cls._from_namespace(environment, namespace, globals)
|
| 1230 |
+
rv._uptodate = uptodate
|
| 1231 |
+
return rv
|
| 1232 |
+
|
| 1233 |
+
@classmethod
|
| 1234 |
+
def from_module_dict(
|
| 1235 |
+
cls,
|
| 1236 |
+
environment: Environment,
|
| 1237 |
+
module_dict: t.MutableMapping[str, t.Any],
|
| 1238 |
+
globals: t.MutableMapping[str, t.Any],
|
| 1239 |
+
) -> "Template":
|
| 1240 |
+
"""Creates a template object from a module. This is used by the
|
| 1241 |
+
module loader to create a template object.
|
| 1242 |
+
|
| 1243 |
+
.. versionadded:: 2.4
|
| 1244 |
+
"""
|
| 1245 |
+
return cls._from_namespace(environment, module_dict, globals)
|
| 1246 |
+
|
| 1247 |
+
@classmethod
|
| 1248 |
+
def _from_namespace(
|
| 1249 |
+
cls,
|
| 1250 |
+
environment: Environment,
|
| 1251 |
+
namespace: t.MutableMapping[str, t.Any],
|
| 1252 |
+
globals: t.MutableMapping[str, t.Any],
|
| 1253 |
+
) -> "Template":
|
| 1254 |
+
t: Template = object.__new__(cls)
|
| 1255 |
+
t.environment = environment
|
| 1256 |
+
t.globals = globals
|
| 1257 |
+
t.name = namespace["name"]
|
| 1258 |
+
t.filename = namespace["__file__"]
|
| 1259 |
+
t.blocks = namespace["blocks"]
|
| 1260 |
+
|
| 1261 |
+
# render function and module
|
| 1262 |
+
t.root_render_func = namespace["root"]
|
| 1263 |
+
t._module = None
|
| 1264 |
+
|
| 1265 |
+
# debug and loader helpers
|
| 1266 |
+
t._debug_info = namespace["debug_info"]
|
| 1267 |
+
t._uptodate = None
|
| 1268 |
+
|
| 1269 |
+
# store the reference
|
| 1270 |
+
namespace["environment"] = environment
|
| 1271 |
+
namespace["__jinja_template__"] = t
|
| 1272 |
+
|
| 1273 |
+
return t
|
| 1274 |
+
|
| 1275 |
+
def render(self, *args: t.Any, **kwargs: t.Any) -> str:
|
| 1276 |
+
"""This method accepts the same arguments as the `dict` constructor:
|
| 1277 |
+
A dict, a dict subclass or some keyword arguments. If no arguments
|
| 1278 |
+
are given the context will be empty. These two calls do the same::
|
| 1279 |
+
|
| 1280 |
+
template.render(knights='that say nih')
|
| 1281 |
+
template.render({'knights': 'that say nih'})
|
| 1282 |
+
|
| 1283 |
+
This will return the rendered template as a string.
|
| 1284 |
+
"""
|
| 1285 |
+
if self.environment.is_async:
|
| 1286 |
+
import asyncio
|
| 1287 |
+
|
| 1288 |
+
return asyncio.run(self.render_async(*args, **kwargs))
|
| 1289 |
+
|
| 1290 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
| 1291 |
+
|
| 1292 |
+
try:
|
| 1293 |
+
return self.environment.concat(self.root_render_func(ctx)) # type: ignore
|
| 1294 |
+
except Exception:
|
| 1295 |
+
self.environment.handle_exception()
|
| 1296 |
+
|
| 1297 |
+
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:
|
| 1298 |
+
"""This works similar to :meth:`render` but returns a coroutine
|
| 1299 |
+
that when awaited returns the entire rendered template string. This
|
| 1300 |
+
requires the async feature to be enabled.
|
| 1301 |
+
|
| 1302 |
+
Example usage::
|
| 1303 |
+
|
| 1304 |
+
await template.render_async(knights='that say nih; asynchronously')
|
| 1305 |
+
"""
|
| 1306 |
+
if not self.environment.is_async:
|
| 1307 |
+
raise RuntimeError(
|
| 1308 |
+
"The environment was not created with async mode enabled."
|
| 1309 |
+
)
|
| 1310 |
+
|
| 1311 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
| 1312 |
+
|
| 1313 |
+
try:
|
| 1314 |
+
return self.environment.concat( # type: ignore
|
| 1315 |
+
[n async for n in self.root_render_func(ctx)] # type: ignore
|
| 1316 |
+
)
|
| 1317 |
+
except Exception:
|
| 1318 |
+
return self.environment.handle_exception()
|
| 1319 |
+
|
| 1320 |
+
def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":
|
| 1321 |
+
"""Works exactly like :meth:`generate` but returns a
|
| 1322 |
+
:class:`TemplateStream`.
|
| 1323 |
+
"""
|
| 1324 |
+
return TemplateStream(self.generate(*args, **kwargs))
|
| 1325 |
+
|
| 1326 |
+
def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:
|
| 1327 |
+
"""For very large templates it can be useful to not render the whole
|
| 1328 |
+
template at once but evaluate each statement after another and yield
|
| 1329 |
+
piece for piece. This method basically does exactly that and returns
|
| 1330 |
+
a generator that yields one item after another as strings.
|
| 1331 |
+
|
| 1332 |
+
It accepts the same arguments as :meth:`render`.
|
| 1333 |
+
"""
|
| 1334 |
+
if self.environment.is_async:
|
| 1335 |
+
import asyncio
|
| 1336 |
+
|
| 1337 |
+
async def to_list() -> t.List[str]:
|
| 1338 |
+
return [x async for x in self.generate_async(*args, **kwargs)]
|
| 1339 |
+
|
| 1340 |
+
yield from asyncio.run(to_list())
|
| 1341 |
+
return
|
| 1342 |
+
|
| 1343 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
| 1344 |
+
|
| 1345 |
+
try:
|
| 1346 |
+
yield from self.root_render_func(ctx)
|
| 1347 |
+
except Exception:
|
| 1348 |
+
yield self.environment.handle_exception()
|
| 1349 |
+
|
| 1350 |
+
async def generate_async(
|
| 1351 |
+
self, *args: t.Any, **kwargs: t.Any
|
| 1352 |
+
) -> t.AsyncGenerator[str, object]:
|
| 1353 |
+
"""An async version of :meth:`generate`. Works very similarly but
|
| 1354 |
+
returns an async iterator instead.
|
| 1355 |
+
"""
|
| 1356 |
+
if not self.environment.is_async:
|
| 1357 |
+
raise RuntimeError(
|
| 1358 |
+
"The environment was not created with async mode enabled."
|
| 1359 |
+
)
|
| 1360 |
+
|
| 1361 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
| 1362 |
+
|
| 1363 |
+
try:
|
| 1364 |
+
agen = self.root_render_func(ctx)
|
| 1365 |
+
try:
|
| 1366 |
+
async for event in agen: # type: ignore
|
| 1367 |
+
yield event
|
| 1368 |
+
finally:
|
| 1369 |
+
# we can't use async with aclosing(...) because that's only
|
| 1370 |
+
# in 3.10+
|
| 1371 |
+
await agen.aclose() # type: ignore
|
| 1372 |
+
except Exception:
|
| 1373 |
+
yield self.environment.handle_exception()
|
| 1374 |
+
|
| 1375 |
+
def new_context(
|
| 1376 |
+
self,
|
| 1377 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
| 1378 |
+
shared: bool = False,
|
| 1379 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
| 1380 |
+
) -> Context:
|
| 1381 |
+
"""Create a new :class:`Context` for this template. The vars
|
| 1382 |
+
provided will be passed to the template. Per default the globals
|
| 1383 |
+
are added to the context. If shared is set to `True` the data
|
| 1384 |
+
is passed as is to the context without adding the globals.
|
| 1385 |
+
|
| 1386 |
+
`locals` can be a dict of local variables for internal usage.
|
| 1387 |
+
"""
|
| 1388 |
+
return new_context(
|
| 1389 |
+
self.environment, self.name, self.blocks, vars, shared, self.globals, locals
|
| 1390 |
+
)
|
| 1391 |
+
|
| 1392 |
+
def make_module(
|
| 1393 |
+
self,
|
| 1394 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
| 1395 |
+
shared: bool = False,
|
| 1396 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
| 1397 |
+
) -> "TemplateModule":
|
| 1398 |
+
"""This method works like the :attr:`module` attribute when called
|
| 1399 |
+
without arguments but it will evaluate the template on every call
|
| 1400 |
+
rather than caching it. It's also possible to provide
|
| 1401 |
+
a dict which is then used as context. The arguments are the same
|
| 1402 |
+
as for the :meth:`new_context` method.
|
| 1403 |
+
"""
|
| 1404 |
+
ctx = self.new_context(vars, shared, locals)
|
| 1405 |
+
return TemplateModule(self, ctx)
|
| 1406 |
+
|
| 1407 |
+
async def make_module_async(
|
| 1408 |
+
self,
|
| 1409 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
| 1410 |
+
shared: bool = False,
|
| 1411 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
| 1412 |
+
) -> "TemplateModule":
|
| 1413 |
+
"""As template module creation can invoke template code for
|
| 1414 |
+
asynchronous executions this method must be used instead of the
|
| 1415 |
+
normal :meth:`make_module` one. Likewise the module attribute
|
| 1416 |
+
becomes unavailable in async mode.
|
| 1417 |
+
"""
|
| 1418 |
+
ctx = self.new_context(vars, shared, locals)
|
| 1419 |
+
return TemplateModule(
|
| 1420 |
+
self,
|
| 1421 |
+
ctx,
|
| 1422 |
+
[x async for x in self.root_render_func(ctx)], # type: ignore
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
@internalcode
|
| 1426 |
+
def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":
|
| 1427 |
+
"""If a context is passed in, this means that the template was
|
| 1428 |
+
imported. Imported templates have access to the current
|
| 1429 |
+
template's globals by default, but they can only be accessed via
|
| 1430 |
+
the context during runtime.
|
| 1431 |
+
|
| 1432 |
+
If there are new globals, we need to create a new module because
|
| 1433 |
+
the cached module is already rendered and will not have access
|
| 1434 |
+
to globals from the current context. This new module is not
|
| 1435 |
+
cached because the template can be imported elsewhere, and it
|
| 1436 |
+
should have access to only the current template's globals.
|
| 1437 |
+
"""
|
| 1438 |
+
if self.environment.is_async:
|
| 1439 |
+
raise RuntimeError("Module is not available in async mode.")
|
| 1440 |
+
|
| 1441 |
+
if ctx is not None:
|
| 1442 |
+
keys = ctx.globals_keys - self.globals.keys()
|
| 1443 |
+
|
| 1444 |
+
if keys:
|
| 1445 |
+
return self.make_module({k: ctx.parent[k] for k in keys})
|
| 1446 |
+
|
| 1447 |
+
if self._module is None:
|
| 1448 |
+
self._module = self.make_module()
|
| 1449 |
+
|
| 1450 |
+
return self._module
|
| 1451 |
+
|
| 1452 |
+
async def _get_default_module_async(
|
| 1453 |
+
self, ctx: t.Optional[Context] = None
|
| 1454 |
+
) -> "TemplateModule":
|
| 1455 |
+
if ctx is not None:
|
| 1456 |
+
keys = ctx.globals_keys - self.globals.keys()
|
| 1457 |
+
|
| 1458 |
+
if keys:
|
| 1459 |
+
return await self.make_module_async({k: ctx.parent[k] for k in keys})
|
| 1460 |
+
|
| 1461 |
+
if self._module is None:
|
| 1462 |
+
self._module = await self.make_module_async()
|
| 1463 |
+
|
| 1464 |
+
return self._module
|
| 1465 |
+
|
| 1466 |
+
@property
|
| 1467 |
+
def module(self) -> "TemplateModule":
|
| 1468 |
+
"""The template as module. This is used for imports in the
|
| 1469 |
+
template runtime but is also useful if one wants to access
|
| 1470 |
+
exported template variables from the Python layer:
|
| 1471 |
+
|
| 1472 |
+
>>> t = Template('{% macro foo() %}42{% endmacro %}23')
|
| 1473 |
+
>>> str(t.module)
|
| 1474 |
+
'23'
|
| 1475 |
+
>>> t.module.foo() == u'42'
|
| 1476 |
+
True
|
| 1477 |
+
|
| 1478 |
+
This attribute is not available if async mode is enabled.
|
| 1479 |
+
"""
|
| 1480 |
+
return self._get_default_module()
|
| 1481 |
+
|
| 1482 |
+
def get_corresponding_lineno(self, lineno: int) -> int:
|
| 1483 |
+
"""Return the source line number of a line number in the
|
| 1484 |
+
generated bytecode as they are not in sync.
|
| 1485 |
+
"""
|
| 1486 |
+
for template_line, code_line in reversed(self.debug_info):
|
| 1487 |
+
if code_line <= lineno:
|
| 1488 |
+
return template_line
|
| 1489 |
+
return 1
|
| 1490 |
+
|
| 1491 |
+
@property
|
| 1492 |
+
def is_up_to_date(self) -> bool:
|
| 1493 |
+
"""If this variable is `False` there is a newer version available."""
|
| 1494 |
+
if self._uptodate is None:
|
| 1495 |
+
return True
|
| 1496 |
+
return self._uptodate()
|
| 1497 |
+
|
| 1498 |
+
@property
|
| 1499 |
+
def debug_info(self) -> t.List[t.Tuple[int, int]]:
|
| 1500 |
+
"""The debug info mapping."""
|
| 1501 |
+
if self._debug_info:
|
| 1502 |
+
return [
|
| 1503 |
+
tuple(map(int, x.split("="))) # type: ignore
|
| 1504 |
+
for x in self._debug_info.split("&")
|
| 1505 |
+
]
|
| 1506 |
+
|
| 1507 |
+
return []
|
| 1508 |
+
|
| 1509 |
+
def __repr__(self) -> str:
|
| 1510 |
+
if self.name is None:
|
| 1511 |
+
name = f"memory:{id(self):x}"
|
| 1512 |
+
else:
|
| 1513 |
+
name = repr(self.name)
|
| 1514 |
+
return f"<{type(self).__name__} {name}>"
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
class TemplateModule:
|
| 1518 |
+
"""Represents an imported template. All the exported names of the
|
| 1519 |
+
template are available as attributes on this object. Additionally
|
| 1520 |
+
converting it into a string renders the contents.
|
| 1521 |
+
"""
|
| 1522 |
+
|
| 1523 |
+
def __init__(
|
| 1524 |
+
self,
|
| 1525 |
+
template: Template,
|
| 1526 |
+
context: Context,
|
| 1527 |
+
body_stream: t.Optional[t.Iterable[str]] = None,
|
| 1528 |
+
) -> None:
|
| 1529 |
+
if body_stream is None:
|
| 1530 |
+
if context.environment.is_async:
|
| 1531 |
+
raise RuntimeError(
|
| 1532 |
+
"Async mode requires a body stream to be passed to"
|
| 1533 |
+
" a template module. Use the async methods of the"
|
| 1534 |
+
" API you are using."
|
| 1535 |
+
)
|
| 1536 |
+
|
| 1537 |
+
body_stream = list(template.root_render_func(context))
|
| 1538 |
+
|
| 1539 |
+
self._body_stream = body_stream
|
| 1540 |
+
self.__dict__.update(context.get_exported())
|
| 1541 |
+
self.__name__ = template.name
|
| 1542 |
+
|
| 1543 |
+
def __html__(self) -> Markup:
|
| 1544 |
+
return Markup(concat(self._body_stream))
|
| 1545 |
+
|
| 1546 |
+
def __str__(self) -> str:
|
| 1547 |
+
return concat(self._body_stream)
|
| 1548 |
+
|
| 1549 |
+
def __repr__(self) -> str:
|
| 1550 |
+
if self.__name__ is None:
|
| 1551 |
+
name = f"memory:{id(self):x}"
|
| 1552 |
+
else:
|
| 1553 |
+
name = repr(self.__name__)
|
| 1554 |
+
return f"<{type(self).__name__} {name}>"
|
| 1555 |
+
|
| 1556 |
+
|
| 1557 |
+
class TemplateExpression:
|
| 1558 |
+
"""The :meth:`jinja2.Environment.compile_expression` method returns an
|
| 1559 |
+
instance of this object. It encapsulates the expression-like access
|
| 1560 |
+
to the template with an expression it wraps.
|
| 1561 |
+
"""
|
| 1562 |
+
|
| 1563 |
+
def __init__(self, template: Template, undefined_to_none: bool) -> None:
|
| 1564 |
+
self._template = template
|
| 1565 |
+
self._undefined_to_none = undefined_to_none
|
| 1566 |
+
|
| 1567 |
+
def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]:
|
| 1568 |
+
context = self._template.new_context(dict(*args, **kwargs))
|
| 1569 |
+
consume(self._template.root_render_func(context))
|
| 1570 |
+
rv = context.vars["result"]
|
| 1571 |
+
if self._undefined_to_none and isinstance(rv, Undefined):
|
| 1572 |
+
rv = None
|
| 1573 |
+
return rv
|
| 1574 |
+
|
| 1575 |
+
|
| 1576 |
+
class TemplateStream:
|
| 1577 |
+
"""A template stream works pretty much like an ordinary python generator
|
| 1578 |
+
but it can buffer multiple items to reduce the number of total iterations.
|
| 1579 |
+
Per default the output is unbuffered which means that for every unbuffered
|
| 1580 |
+
instruction in the template one string is yielded.
|
| 1581 |
+
|
| 1582 |
+
If buffering is enabled with a buffer size of 5, five items are combined
|
| 1583 |
+
into a new string. This is mainly useful if you are streaming
|
| 1584 |
+
big templates to a client via WSGI which flushes after each iteration.
|
| 1585 |
+
"""
|
| 1586 |
+
|
| 1587 |
+
def __init__(self, gen: t.Iterator[str]) -> None:
|
| 1588 |
+
self._gen = gen
|
| 1589 |
+
self.disable_buffering()
|
| 1590 |
+
|
| 1591 |
+
def dump(
|
| 1592 |
+
self,
|
| 1593 |
+
fp: t.Union[str, t.IO[bytes]],
|
| 1594 |
+
encoding: t.Optional[str] = None,
|
| 1595 |
+
errors: t.Optional[str] = "strict",
|
| 1596 |
+
) -> None:
|
| 1597 |
+
"""Dump the complete stream into a file or file-like object.
|
| 1598 |
+
Per default strings are written, if you want to encode
|
| 1599 |
+
before writing specify an `encoding`.
|
| 1600 |
+
|
| 1601 |
+
Example usage::
|
| 1602 |
+
|
| 1603 |
+
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
|
| 1604 |
+
"""
|
| 1605 |
+
close = False
|
| 1606 |
+
|
| 1607 |
+
if isinstance(fp, str):
|
| 1608 |
+
if encoding is None:
|
| 1609 |
+
encoding = "utf-8"
|
| 1610 |
+
|
| 1611 |
+
real_fp: t.IO[bytes] = open(fp, "wb")
|
| 1612 |
+
close = True
|
| 1613 |
+
else:
|
| 1614 |
+
real_fp = fp
|
| 1615 |
+
|
| 1616 |
+
try:
|
| 1617 |
+
if encoding is not None:
|
| 1618 |
+
iterable = (x.encode(encoding, errors) for x in self) # type: ignore
|
| 1619 |
+
else:
|
| 1620 |
+
iterable = self # type: ignore
|
| 1621 |
+
|
| 1622 |
+
if hasattr(real_fp, "writelines"):
|
| 1623 |
+
real_fp.writelines(iterable)
|
| 1624 |
+
else:
|
| 1625 |
+
for item in iterable:
|
| 1626 |
+
real_fp.write(item)
|
| 1627 |
+
finally:
|
| 1628 |
+
if close:
|
| 1629 |
+
real_fp.close()
|
| 1630 |
+
|
| 1631 |
+
def disable_buffering(self) -> None:
|
| 1632 |
+
"""Disable the output buffering."""
|
| 1633 |
+
self._next = partial(next, self._gen)
|
| 1634 |
+
self.buffered = False
|
| 1635 |
+
|
| 1636 |
+
def _buffered_generator(self, size: int) -> t.Iterator[str]:
|
| 1637 |
+
buf: t.List[str] = []
|
| 1638 |
+
c_size = 0
|
| 1639 |
+
push = buf.append
|
| 1640 |
+
|
| 1641 |
+
while True:
|
| 1642 |
+
try:
|
| 1643 |
+
while c_size < size:
|
| 1644 |
+
c = next(self._gen)
|
| 1645 |
+
push(c)
|
| 1646 |
+
if c:
|
| 1647 |
+
c_size += 1
|
| 1648 |
+
except StopIteration:
|
| 1649 |
+
if not c_size:
|
| 1650 |
+
return
|
| 1651 |
+
yield concat(buf)
|
| 1652 |
+
del buf[:]
|
| 1653 |
+
c_size = 0
|
| 1654 |
+
|
| 1655 |
+
def enable_buffering(self, size: int = 5) -> None:
|
| 1656 |
+
"""Enable buffering. Buffer `size` items before yielding them."""
|
| 1657 |
+
if size <= 1:
|
| 1658 |
+
raise ValueError("buffer size too small")
|
| 1659 |
+
|
| 1660 |
+
self.buffered = True
|
| 1661 |
+
self._next = partial(next, self._buffered_generator(size))
|
| 1662 |
+
|
| 1663 |
+
def __iter__(self) -> "TemplateStream":
|
| 1664 |
+
return self
|
| 1665 |
+
|
| 1666 |
+
def __next__(self) -> str:
|
| 1667 |
+
return self._next() # type: ignore
|
| 1668 |
+
|
| 1669 |
+
|
| 1670 |
+
# hook in default template class. if anyone reads this comment: ignore that
|
| 1671 |
+
# it's possible to use custom templates ;-)
|
| 1672 |
+
Environment.template_class = Template
|
wemm/lib/python3.10/site-packages/jinja2/filters.py
ADDED
|
@@ -0,0 +1,1878 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Built-in template filters used with the ``|`` operator."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import random
|
| 5 |
+
import re
|
| 6 |
+
import typing
|
| 7 |
+
import typing as t
|
| 8 |
+
from collections import abc
|
| 9 |
+
from itertools import chain
|
| 10 |
+
from itertools import groupby
|
| 11 |
+
|
| 12 |
+
from markupsafe import escape
|
| 13 |
+
from markupsafe import Markup
|
| 14 |
+
from markupsafe import soft_str
|
| 15 |
+
|
| 16 |
+
from .async_utils import async_variant
|
| 17 |
+
from .async_utils import auto_aiter
|
| 18 |
+
from .async_utils import auto_await
|
| 19 |
+
from .async_utils import auto_to_list
|
| 20 |
+
from .exceptions import FilterArgumentError
|
| 21 |
+
from .runtime import Undefined
|
| 22 |
+
from .utils import htmlsafe_json_dumps
|
| 23 |
+
from .utils import pass_context
|
| 24 |
+
from .utils import pass_environment
|
| 25 |
+
from .utils import pass_eval_context
|
| 26 |
+
from .utils import pformat
|
| 27 |
+
from .utils import url_quote
|
| 28 |
+
from .utils import urlize
|
| 29 |
+
|
| 30 |
+
if t.TYPE_CHECKING:
|
| 31 |
+
import typing_extensions as te
|
| 32 |
+
|
| 33 |
+
from .environment import Environment
|
| 34 |
+
from .nodes import EvalContext
|
| 35 |
+
from .runtime import Context
|
| 36 |
+
from .sandbox import SandboxedEnvironment # noqa: F401
|
| 37 |
+
|
| 38 |
+
class HasHTML(te.Protocol):
|
| 39 |
+
def __html__(self) -> str:
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
| 44 |
+
K = t.TypeVar("K")
|
| 45 |
+
V = t.TypeVar("V")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def ignore_case(value: V) -> V:
|
| 49 |
+
"""For use as a postprocessor for :func:`make_attrgetter`. Converts strings
|
| 50 |
+
to lowercase and returns other types as-is."""
|
| 51 |
+
if isinstance(value, str):
|
| 52 |
+
return t.cast(V, value.lower())
|
| 53 |
+
|
| 54 |
+
return value
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def make_attrgetter(
|
| 58 |
+
environment: "Environment",
|
| 59 |
+
attribute: t.Optional[t.Union[str, int]],
|
| 60 |
+
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
|
| 61 |
+
default: t.Optional[t.Any] = None,
|
| 62 |
+
) -> t.Callable[[t.Any], t.Any]:
|
| 63 |
+
"""Returns a callable that looks up the given attribute from a
|
| 64 |
+
passed object with the rules of the environment. Dots are allowed
|
| 65 |
+
to access attributes of attributes. Integer parts in paths are
|
| 66 |
+
looked up as integers.
|
| 67 |
+
"""
|
| 68 |
+
parts = _prepare_attribute_parts(attribute)
|
| 69 |
+
|
| 70 |
+
def attrgetter(item: t.Any) -> t.Any:
|
| 71 |
+
for part in parts:
|
| 72 |
+
item = environment.getitem(item, part)
|
| 73 |
+
|
| 74 |
+
if default is not None and isinstance(item, Undefined):
|
| 75 |
+
item = default
|
| 76 |
+
|
| 77 |
+
if postprocess is not None:
|
| 78 |
+
item = postprocess(item)
|
| 79 |
+
|
| 80 |
+
return item
|
| 81 |
+
|
| 82 |
+
return attrgetter
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def make_multi_attrgetter(
|
| 86 |
+
environment: "Environment",
|
| 87 |
+
attribute: t.Optional[t.Union[str, int]],
|
| 88 |
+
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
|
| 89 |
+
) -> t.Callable[[t.Any], t.List[t.Any]]:
|
| 90 |
+
"""Returns a callable that looks up the given comma separated
|
| 91 |
+
attributes from a passed object with the rules of the environment.
|
| 92 |
+
Dots are allowed to access attributes of each attribute. Integer
|
| 93 |
+
parts in paths are looked up as integers.
|
| 94 |
+
|
| 95 |
+
The value returned by the returned callable is a list of extracted
|
| 96 |
+
attribute values.
|
| 97 |
+
|
| 98 |
+
Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.
|
| 99 |
+
"""
|
| 100 |
+
if isinstance(attribute, str):
|
| 101 |
+
split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")
|
| 102 |
+
else:
|
| 103 |
+
split = [attribute]
|
| 104 |
+
|
| 105 |
+
parts = [_prepare_attribute_parts(item) for item in split]
|
| 106 |
+
|
| 107 |
+
def attrgetter(item: t.Any) -> t.List[t.Any]:
|
| 108 |
+
items = [None] * len(parts)
|
| 109 |
+
|
| 110 |
+
for i, attribute_part in enumerate(parts):
|
| 111 |
+
item_i = item
|
| 112 |
+
|
| 113 |
+
for part in attribute_part:
|
| 114 |
+
item_i = environment.getitem(item_i, part)
|
| 115 |
+
|
| 116 |
+
if postprocess is not None:
|
| 117 |
+
item_i = postprocess(item_i)
|
| 118 |
+
|
| 119 |
+
items[i] = item_i
|
| 120 |
+
|
| 121 |
+
return items
|
| 122 |
+
|
| 123 |
+
return attrgetter
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _prepare_attribute_parts(
|
| 127 |
+
attr: t.Optional[t.Union[str, int]],
|
| 128 |
+
) -> t.List[t.Union[str, int]]:
|
| 129 |
+
if attr is None:
|
| 130 |
+
return []
|
| 131 |
+
|
| 132 |
+
if isinstance(attr, str):
|
| 133 |
+
return [int(x) if x.isdigit() else x for x in attr.split(".")]
|
| 134 |
+
|
| 135 |
+
return [attr]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:
|
| 139 |
+
"""Enforce HTML escaping. This will probably double escape variables."""
|
| 140 |
+
if hasattr(value, "__html__"):
|
| 141 |
+
value = t.cast("HasHTML", value).__html__()
|
| 142 |
+
|
| 143 |
+
return escape(str(value))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def do_urlencode(
|
| 147 |
+
value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],
|
| 148 |
+
) -> str:
|
| 149 |
+
"""Quote data for use in a URL path or query using UTF-8.
|
| 150 |
+
|
| 151 |
+
Basic wrapper around :func:`urllib.parse.quote` when given a
|
| 152 |
+
string, or :func:`urllib.parse.urlencode` for a dict or iterable.
|
| 153 |
+
|
| 154 |
+
:param value: Data to quote. A string will be quoted directly. A
|
| 155 |
+
dict or iterable of ``(key, value)`` pairs will be joined as a
|
| 156 |
+
query string.
|
| 157 |
+
|
| 158 |
+
When given a string, "/" is not quoted. HTTP servers treat "/" and
|
| 159 |
+
"%2F" equivalently in paths. If you need quoted slashes, use the
|
| 160 |
+
``|replace("/", "%2F")`` filter.
|
| 161 |
+
|
| 162 |
+
.. versionadded:: 2.7
|
| 163 |
+
"""
|
| 164 |
+
if isinstance(value, str) or not isinstance(value, abc.Iterable):
|
| 165 |
+
return url_quote(value)
|
| 166 |
+
|
| 167 |
+
if isinstance(value, dict):
|
| 168 |
+
items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
|
| 169 |
+
else:
|
| 170 |
+
items = value # type: ignore
|
| 171 |
+
|
| 172 |
+
return "&".join(
|
| 173 |
+
f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@pass_eval_context
|
| 178 |
+
def do_replace(
|
| 179 |
+
eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None
|
| 180 |
+
) -> str:
|
| 181 |
+
"""Return a copy of the value with all occurrences of a substring
|
| 182 |
+
replaced with a new one. The first argument is the substring
|
| 183 |
+
that should be replaced, the second is the replacement string.
|
| 184 |
+
If the optional third argument ``count`` is given, only the first
|
| 185 |
+
``count`` occurrences are replaced:
|
| 186 |
+
|
| 187 |
+
.. sourcecode:: jinja
|
| 188 |
+
|
| 189 |
+
{{ "Hello World"|replace("Hello", "Goodbye") }}
|
| 190 |
+
-> Goodbye World
|
| 191 |
+
|
| 192 |
+
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
|
| 193 |
+
-> d'oh, d'oh, aaargh
|
| 194 |
+
"""
|
| 195 |
+
if count is None:
|
| 196 |
+
count = -1
|
| 197 |
+
|
| 198 |
+
if not eval_ctx.autoescape:
|
| 199 |
+
return str(s).replace(str(old), str(new), count)
|
| 200 |
+
|
| 201 |
+
if (
|
| 202 |
+
hasattr(old, "__html__")
|
| 203 |
+
or hasattr(new, "__html__")
|
| 204 |
+
and not hasattr(s, "__html__")
|
| 205 |
+
):
|
| 206 |
+
s = escape(s)
|
| 207 |
+
else:
|
| 208 |
+
s = soft_str(s)
|
| 209 |
+
|
| 210 |
+
return s.replace(soft_str(old), soft_str(new), count)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def do_upper(s: str) -> str:
|
| 214 |
+
"""Convert a value to uppercase."""
|
| 215 |
+
return soft_str(s).upper()
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def do_lower(s: str) -> str:
|
| 219 |
+
"""Convert a value to lowercase."""
|
| 220 |
+
return soft_str(s).lower()
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]:
|
| 224 |
+
"""Return an iterator over the ``(key, value)`` items of a mapping.
|
| 225 |
+
|
| 226 |
+
``x|items`` is the same as ``x.items()``, except if ``x`` is
|
| 227 |
+
undefined an empty iterator is returned.
|
| 228 |
+
|
| 229 |
+
This filter is useful if you expect the template to be rendered with
|
| 230 |
+
an implementation of Jinja in another programming language that does
|
| 231 |
+
not have a ``.items()`` method on its mapping type.
|
| 232 |
+
|
| 233 |
+
.. code-block:: html+jinja
|
| 234 |
+
|
| 235 |
+
<dl>
|
| 236 |
+
{% for key, value in my_dict|items %}
|
| 237 |
+
<dt>{{ key }}
|
| 238 |
+
<dd>{{ value }}
|
| 239 |
+
{% endfor %}
|
| 240 |
+
</dl>
|
| 241 |
+
|
| 242 |
+
.. versionadded:: 3.1
|
| 243 |
+
"""
|
| 244 |
+
if isinstance(value, Undefined):
|
| 245 |
+
return
|
| 246 |
+
|
| 247 |
+
if not isinstance(value, abc.Mapping):
|
| 248 |
+
raise TypeError("Can only get item pairs from a mapping.")
|
| 249 |
+
|
| 250 |
+
yield from value.items()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# Check for characters that would move the parser state from key to value.
|
| 254 |
+
# https://html.spec.whatwg.org/#attribute-name-state
|
| 255 |
+
_attr_key_re = re.compile(r"[\s/>=]", flags=re.ASCII)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@pass_eval_context
|
| 259 |
+
def do_xmlattr(
|
| 260 |
+
eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True
|
| 261 |
+
) -> str:
|
| 262 |
+
"""Create an SGML/XML attribute string based on the items in a dict.
|
| 263 |
+
|
| 264 |
+
**Values** that are neither ``none`` nor ``undefined`` are automatically
|
| 265 |
+
escaped, safely allowing untrusted user input.
|
| 266 |
+
|
| 267 |
+
User input should not be used as **keys** to this filter. If any key
|
| 268 |
+
contains a space, ``/`` solidus, ``>`` greater-than sign, or ``=`` equals
|
| 269 |
+
sign, this fails with a ``ValueError``. Regardless of this, user input
|
| 270 |
+
should never be used as keys to this filter, or must be separately validated
|
| 271 |
+
first.
|
| 272 |
+
|
| 273 |
+
.. sourcecode:: html+jinja
|
| 274 |
+
|
| 275 |
+
<ul{{ {'class': 'my_list', 'missing': none,
|
| 276 |
+
'id': 'list-%d'|format(variable)}|xmlattr }}>
|
| 277 |
+
...
|
| 278 |
+
</ul>
|
| 279 |
+
|
| 280 |
+
Results in something like this:
|
| 281 |
+
|
| 282 |
+
.. sourcecode:: html
|
| 283 |
+
|
| 284 |
+
<ul class="my_list" id="list-42">
|
| 285 |
+
...
|
| 286 |
+
</ul>
|
| 287 |
+
|
| 288 |
+
As you can see it automatically prepends a space in front of the item
|
| 289 |
+
if the filter returned something unless the second parameter is false.
|
| 290 |
+
|
| 291 |
+
.. versionchanged:: 3.1.4
|
| 292 |
+
Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign
|
| 293 |
+
are not allowed.
|
| 294 |
+
|
| 295 |
+
.. versionchanged:: 3.1.3
|
| 296 |
+
Keys with spaces are not allowed.
|
| 297 |
+
"""
|
| 298 |
+
items = []
|
| 299 |
+
|
| 300 |
+
for key, value in d.items():
|
| 301 |
+
if value is None or isinstance(value, Undefined):
|
| 302 |
+
continue
|
| 303 |
+
|
| 304 |
+
if _attr_key_re.search(key) is not None:
|
| 305 |
+
raise ValueError(f"Invalid character in attribute name: {key!r}")
|
| 306 |
+
|
| 307 |
+
items.append(f'{escape(key)}="{escape(value)}"')
|
| 308 |
+
|
| 309 |
+
rv = " ".join(items)
|
| 310 |
+
|
| 311 |
+
if autospace and rv:
|
| 312 |
+
rv = " " + rv
|
| 313 |
+
|
| 314 |
+
if eval_ctx.autoescape:
|
| 315 |
+
rv = Markup(rv)
|
| 316 |
+
|
| 317 |
+
return rv
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def do_capitalize(s: str) -> str:
|
| 321 |
+
"""Capitalize a value. The first character will be uppercase, all others
|
| 322 |
+
lowercase.
|
| 323 |
+
"""
|
| 324 |
+
return soft_str(s).capitalize()
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def do_title(s: str) -> str:
|
| 331 |
+
"""Return a titlecased version of the value. I.e. words will start with
|
| 332 |
+
uppercase letters, all remaining characters are lowercase.
|
| 333 |
+
"""
|
| 334 |
+
return "".join(
|
| 335 |
+
[
|
| 336 |
+
item[0].upper() + item[1:].lower()
|
| 337 |
+
for item in _word_beginning_split_re.split(soft_str(s))
|
| 338 |
+
if item
|
| 339 |
+
]
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def do_dictsort(
|
| 344 |
+
value: t.Mapping[K, V],
|
| 345 |
+
case_sensitive: bool = False,
|
| 346 |
+
by: 'te.Literal["key", "value"]' = "key",
|
| 347 |
+
reverse: bool = False,
|
| 348 |
+
) -> t.List[t.Tuple[K, V]]:
|
| 349 |
+
"""Sort a dict and yield (key, value) pairs. Python dicts may not
|
| 350 |
+
be in the order you want to display them in, so sort them first.
|
| 351 |
+
|
| 352 |
+
.. sourcecode:: jinja
|
| 353 |
+
|
| 354 |
+
{% for key, value in mydict|dictsort %}
|
| 355 |
+
sort the dict by key, case insensitive
|
| 356 |
+
|
| 357 |
+
{% for key, value in mydict|dictsort(reverse=true) %}
|
| 358 |
+
sort the dict by key, case insensitive, reverse order
|
| 359 |
+
|
| 360 |
+
{% for key, value in mydict|dictsort(true) %}
|
| 361 |
+
sort the dict by key, case sensitive
|
| 362 |
+
|
| 363 |
+
{% for key, value in mydict|dictsort(false, 'value') %}
|
| 364 |
+
sort the dict by value, case insensitive
|
| 365 |
+
"""
|
| 366 |
+
if by == "key":
|
| 367 |
+
pos = 0
|
| 368 |
+
elif by == "value":
|
| 369 |
+
pos = 1
|
| 370 |
+
else:
|
| 371 |
+
raise FilterArgumentError('You can only sort by either "key" or "value"')
|
| 372 |
+
|
| 373 |
+
def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:
|
| 374 |
+
value = item[pos]
|
| 375 |
+
|
| 376 |
+
if not case_sensitive:
|
| 377 |
+
value = ignore_case(value)
|
| 378 |
+
|
| 379 |
+
return value
|
| 380 |
+
|
| 381 |
+
return sorted(value.items(), key=sort_func, reverse=reverse)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@pass_environment
|
| 385 |
+
def do_sort(
|
| 386 |
+
environment: "Environment",
|
| 387 |
+
value: "t.Iterable[V]",
|
| 388 |
+
reverse: bool = False,
|
| 389 |
+
case_sensitive: bool = False,
|
| 390 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 391 |
+
) -> "t.List[V]":
|
| 392 |
+
"""Sort an iterable using Python's :func:`sorted`.
|
| 393 |
+
|
| 394 |
+
.. sourcecode:: jinja
|
| 395 |
+
|
| 396 |
+
{% for city in cities|sort %}
|
| 397 |
+
...
|
| 398 |
+
{% endfor %}
|
| 399 |
+
|
| 400 |
+
:param reverse: Sort descending instead of ascending.
|
| 401 |
+
:param case_sensitive: When sorting strings, sort upper and lower
|
| 402 |
+
case separately.
|
| 403 |
+
:param attribute: When sorting objects or dicts, an attribute or
|
| 404 |
+
key to sort by. Can use dot notation like ``"address.city"``.
|
| 405 |
+
Can be a list of attributes like ``"age,name"``.
|
| 406 |
+
|
| 407 |
+
The sort is stable, it does not change the relative order of
|
| 408 |
+
elements that compare equal. This makes it is possible to chain
|
| 409 |
+
sorts on different attributes and ordering.
|
| 410 |
+
|
| 411 |
+
.. sourcecode:: jinja
|
| 412 |
+
|
| 413 |
+
{% for user in users|sort(attribute="name")
|
| 414 |
+
|sort(reverse=true, attribute="age") %}
|
| 415 |
+
...
|
| 416 |
+
{% endfor %}
|
| 417 |
+
|
| 418 |
+
As a shortcut to chaining when the direction is the same for all
|
| 419 |
+
attributes, pass a comma separate list of attributes.
|
| 420 |
+
|
| 421 |
+
.. sourcecode:: jinja
|
| 422 |
+
|
| 423 |
+
{% for user in users|sort(attribute="age,name") %}
|
| 424 |
+
...
|
| 425 |
+
{% endfor %}
|
| 426 |
+
|
| 427 |
+
.. versionchanged:: 2.11.0
|
| 428 |
+
The ``attribute`` parameter can be a comma separated list of
|
| 429 |
+
attributes, e.g. ``"age,name"``.
|
| 430 |
+
|
| 431 |
+
.. versionchanged:: 2.6
|
| 432 |
+
The ``attribute`` parameter was added.
|
| 433 |
+
"""
|
| 434 |
+
key_func = make_multi_attrgetter(
|
| 435 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
| 436 |
+
)
|
| 437 |
+
return sorted(value, key=key_func, reverse=reverse)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@pass_environment
|
| 441 |
+
def sync_do_unique(
|
| 442 |
+
environment: "Environment",
|
| 443 |
+
value: "t.Iterable[V]",
|
| 444 |
+
case_sensitive: bool = False,
|
| 445 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 446 |
+
) -> "t.Iterator[V]":
|
| 447 |
+
"""Returns a list of unique items from the given iterable.
|
| 448 |
+
|
| 449 |
+
.. sourcecode:: jinja
|
| 450 |
+
|
| 451 |
+
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
|
| 452 |
+
-> ['foo', 'bar', 'foobar']
|
| 453 |
+
|
| 454 |
+
The unique items are yielded in the same order as their first occurrence in
|
| 455 |
+
the iterable passed to the filter.
|
| 456 |
+
|
| 457 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
| 458 |
+
:param attribute: Filter objects with unique values for this attribute.
|
| 459 |
+
"""
|
| 460 |
+
getter = make_attrgetter(
|
| 461 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
| 462 |
+
)
|
| 463 |
+
seen = set()
|
| 464 |
+
|
| 465 |
+
for item in value:
|
| 466 |
+
key = getter(item)
|
| 467 |
+
|
| 468 |
+
if key not in seen:
|
| 469 |
+
seen.add(key)
|
| 470 |
+
yield item
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
@async_variant(sync_do_unique) # type: ignore
|
| 474 |
+
async def do_unique(
|
| 475 |
+
environment: "Environment",
|
| 476 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 477 |
+
case_sensitive: bool = False,
|
| 478 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 479 |
+
) -> "t.Iterator[V]":
|
| 480 |
+
return sync_do_unique(
|
| 481 |
+
environment, await auto_to_list(value), case_sensitive, attribute
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _min_or_max(
|
| 486 |
+
environment: "Environment",
|
| 487 |
+
value: "t.Iterable[V]",
|
| 488 |
+
func: "t.Callable[..., V]",
|
| 489 |
+
case_sensitive: bool,
|
| 490 |
+
attribute: t.Optional[t.Union[str, int]],
|
| 491 |
+
) -> "t.Union[V, Undefined]":
|
| 492 |
+
it = iter(value)
|
| 493 |
+
|
| 494 |
+
try:
|
| 495 |
+
first = next(it)
|
| 496 |
+
except StopIteration:
|
| 497 |
+
return environment.undefined("No aggregated item, sequence was empty.")
|
| 498 |
+
|
| 499 |
+
key_func = make_attrgetter(
|
| 500 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
| 501 |
+
)
|
| 502 |
+
return func(chain([first], it), key=key_func)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
@pass_environment
|
| 506 |
+
def do_min(
|
| 507 |
+
environment: "Environment",
|
| 508 |
+
value: "t.Iterable[V]",
|
| 509 |
+
case_sensitive: bool = False,
|
| 510 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 511 |
+
) -> "t.Union[V, Undefined]":
|
| 512 |
+
"""Return the smallest item from the sequence.
|
| 513 |
+
|
| 514 |
+
.. sourcecode:: jinja
|
| 515 |
+
|
| 516 |
+
{{ [1, 2, 3]|min }}
|
| 517 |
+
-> 1
|
| 518 |
+
|
| 519 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
| 520 |
+
:param attribute: Get the object with the min value of this attribute.
|
| 521 |
+
"""
|
| 522 |
+
return _min_or_max(environment, value, min, case_sensitive, attribute)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@pass_environment
|
| 526 |
+
def do_max(
|
| 527 |
+
environment: "Environment",
|
| 528 |
+
value: "t.Iterable[V]",
|
| 529 |
+
case_sensitive: bool = False,
|
| 530 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 531 |
+
) -> "t.Union[V, Undefined]":
|
| 532 |
+
"""Return the largest item from the sequence.
|
| 533 |
+
|
| 534 |
+
.. sourcecode:: jinja
|
| 535 |
+
|
| 536 |
+
{{ [1, 2, 3]|max }}
|
| 537 |
+
-> 3
|
| 538 |
+
|
| 539 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
| 540 |
+
:param attribute: Get the object with the max value of this attribute.
|
| 541 |
+
"""
|
| 542 |
+
return _min_or_max(environment, value, max, case_sensitive, attribute)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def do_default(
|
| 546 |
+
value: V,
|
| 547 |
+
default_value: V = "", # type: ignore
|
| 548 |
+
boolean: bool = False,
|
| 549 |
+
) -> V:
|
| 550 |
+
"""If the value is undefined it will return the passed default value,
|
| 551 |
+
otherwise the value of the variable:
|
| 552 |
+
|
| 553 |
+
.. sourcecode:: jinja
|
| 554 |
+
|
| 555 |
+
{{ my_variable|default('my_variable is not defined') }}
|
| 556 |
+
|
| 557 |
+
This will output the value of ``my_variable`` if the variable was
|
| 558 |
+
defined, otherwise ``'my_variable is not defined'``. If you want
|
| 559 |
+
to use default with variables that evaluate to false you have to
|
| 560 |
+
set the second parameter to `true`:
|
| 561 |
+
|
| 562 |
+
.. sourcecode:: jinja
|
| 563 |
+
|
| 564 |
+
{{ ''|default('the string was empty', true) }}
|
| 565 |
+
|
| 566 |
+
.. versionchanged:: 2.11
|
| 567 |
+
It's now possible to configure the :class:`~jinja2.Environment` with
|
| 568 |
+
:class:`~jinja2.ChainableUndefined` to make the `default` filter work
|
| 569 |
+
on nested elements and attributes that may contain undefined values
|
| 570 |
+
in the chain without getting an :exc:`~jinja2.UndefinedError`.
|
| 571 |
+
"""
|
| 572 |
+
if isinstance(value, Undefined) or (boolean and not value):
|
| 573 |
+
return default_value
|
| 574 |
+
|
| 575 |
+
return value
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
@pass_eval_context
|
| 579 |
+
def sync_do_join(
|
| 580 |
+
eval_ctx: "EvalContext",
|
| 581 |
+
value: t.Iterable[t.Any],
|
| 582 |
+
d: str = "",
|
| 583 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 584 |
+
) -> str:
|
| 585 |
+
"""Return a string which is the concatenation of the strings in the
|
| 586 |
+
sequence. The separator between elements is an empty string per
|
| 587 |
+
default, you can define it with the optional parameter:
|
| 588 |
+
|
| 589 |
+
.. sourcecode:: jinja
|
| 590 |
+
|
| 591 |
+
{{ [1, 2, 3]|join('|') }}
|
| 592 |
+
-> 1|2|3
|
| 593 |
+
|
| 594 |
+
{{ [1, 2, 3]|join }}
|
| 595 |
+
-> 123
|
| 596 |
+
|
| 597 |
+
It is also possible to join certain attributes of an object:
|
| 598 |
+
|
| 599 |
+
.. sourcecode:: jinja
|
| 600 |
+
|
| 601 |
+
{{ users|join(', ', attribute='username') }}
|
| 602 |
+
|
| 603 |
+
.. versionadded:: 2.6
|
| 604 |
+
The `attribute` parameter was added.
|
| 605 |
+
"""
|
| 606 |
+
if attribute is not None:
|
| 607 |
+
value = map(make_attrgetter(eval_ctx.environment, attribute), value)
|
| 608 |
+
|
| 609 |
+
# no automatic escaping? joining is a lot easier then
|
| 610 |
+
if not eval_ctx.autoescape:
|
| 611 |
+
return str(d).join(map(str, value))
|
| 612 |
+
|
| 613 |
+
# if the delimiter doesn't have an html representation we check
|
| 614 |
+
# if any of the items has. If yes we do a coercion to Markup
|
| 615 |
+
if not hasattr(d, "__html__"):
|
| 616 |
+
value = list(value)
|
| 617 |
+
do_escape = False
|
| 618 |
+
|
| 619 |
+
for idx, item in enumerate(value):
|
| 620 |
+
if hasattr(item, "__html__"):
|
| 621 |
+
do_escape = True
|
| 622 |
+
else:
|
| 623 |
+
value[idx] = str(item)
|
| 624 |
+
|
| 625 |
+
if do_escape:
|
| 626 |
+
d = escape(d)
|
| 627 |
+
else:
|
| 628 |
+
d = str(d)
|
| 629 |
+
|
| 630 |
+
return d.join(value)
|
| 631 |
+
|
| 632 |
+
# no html involved, to normal joining
|
| 633 |
+
return soft_str(d).join(map(soft_str, value))
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
@async_variant(sync_do_join) # type: ignore
|
| 637 |
+
async def do_join(
|
| 638 |
+
eval_ctx: "EvalContext",
|
| 639 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 640 |
+
d: str = "",
|
| 641 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 642 |
+
) -> str:
|
| 643 |
+
return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def do_center(value: str, width: int = 80) -> str:
|
| 647 |
+
"""Centers the value in a field of a given width."""
|
| 648 |
+
return soft_str(value).center(width)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
@pass_environment
|
| 652 |
+
def sync_do_first(
|
| 653 |
+
environment: "Environment", seq: "t.Iterable[V]"
|
| 654 |
+
) -> "t.Union[V, Undefined]":
|
| 655 |
+
"""Return the first item of a sequence."""
|
| 656 |
+
try:
|
| 657 |
+
return next(iter(seq))
|
| 658 |
+
except StopIteration:
|
| 659 |
+
return environment.undefined("No first item, sequence was empty.")
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
@async_variant(sync_do_first) # type: ignore
|
| 663 |
+
async def do_first(
|
| 664 |
+
environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"
|
| 665 |
+
) -> "t.Union[V, Undefined]":
|
| 666 |
+
try:
|
| 667 |
+
return await auto_aiter(seq).__anext__()
|
| 668 |
+
except StopAsyncIteration:
|
| 669 |
+
return environment.undefined("No first item, sequence was empty.")
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
@pass_environment
|
| 673 |
+
def do_last(
|
| 674 |
+
environment: "Environment", seq: "t.Reversible[V]"
|
| 675 |
+
) -> "t.Union[V, Undefined]":
|
| 676 |
+
"""Return the last item of a sequence.
|
| 677 |
+
|
| 678 |
+
Note: Does not work with generators. You may want to explicitly
|
| 679 |
+
convert it to a list:
|
| 680 |
+
|
| 681 |
+
.. sourcecode:: jinja
|
| 682 |
+
|
| 683 |
+
{{ data | selectattr('name', '==', 'Jinja') | list | last }}
|
| 684 |
+
"""
|
| 685 |
+
try:
|
| 686 |
+
return next(iter(reversed(seq)))
|
| 687 |
+
except StopIteration:
|
| 688 |
+
return environment.undefined("No last item, sequence was empty.")
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
# No async do_last, it may not be safe in async mode.
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
@pass_context
|
| 695 |
+
def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":
|
| 696 |
+
"""Return a random item from the sequence."""
|
| 697 |
+
try:
|
| 698 |
+
return random.choice(seq)
|
| 699 |
+
except IndexError:
|
| 700 |
+
return context.environment.undefined("No random item, sequence was empty.")
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:
|
| 704 |
+
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
|
| 705 |
+
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
|
| 706 |
+
Giga, etc.), if the second parameter is set to `True` the binary
|
| 707 |
+
prefixes are used (Mebi, Gibi).
|
| 708 |
+
"""
|
| 709 |
+
bytes = float(value)
|
| 710 |
+
base = 1024 if binary else 1000
|
| 711 |
+
prefixes = [
|
| 712 |
+
("KiB" if binary else "kB"),
|
| 713 |
+
("MiB" if binary else "MB"),
|
| 714 |
+
("GiB" if binary else "GB"),
|
| 715 |
+
("TiB" if binary else "TB"),
|
| 716 |
+
("PiB" if binary else "PB"),
|
| 717 |
+
("EiB" if binary else "EB"),
|
| 718 |
+
("ZiB" if binary else "ZB"),
|
| 719 |
+
("YiB" if binary else "YB"),
|
| 720 |
+
]
|
| 721 |
+
|
| 722 |
+
if bytes == 1:
|
| 723 |
+
return "1 Byte"
|
| 724 |
+
elif bytes < base:
|
| 725 |
+
return f"{int(bytes)} Bytes"
|
| 726 |
+
else:
|
| 727 |
+
for i, prefix in enumerate(prefixes):
|
| 728 |
+
unit = base ** (i + 2)
|
| 729 |
+
|
| 730 |
+
if bytes < unit:
|
| 731 |
+
return f"{base * bytes / unit:.1f} {prefix}"
|
| 732 |
+
|
| 733 |
+
return f"{base * bytes / unit:.1f} {prefix}"
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def do_pprint(value: t.Any) -> str:
|
| 737 |
+
"""Pretty print a variable. Useful for debugging."""
|
| 738 |
+
return pformat(value)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
@pass_eval_context
|
| 745 |
+
def do_urlize(
|
| 746 |
+
eval_ctx: "EvalContext",
|
| 747 |
+
value: str,
|
| 748 |
+
trim_url_limit: t.Optional[int] = None,
|
| 749 |
+
nofollow: bool = False,
|
| 750 |
+
target: t.Optional[str] = None,
|
| 751 |
+
rel: t.Optional[str] = None,
|
| 752 |
+
extra_schemes: t.Optional[t.Iterable[str]] = None,
|
| 753 |
+
) -> str:
|
| 754 |
+
"""Convert URLs in text into clickable links.
|
| 755 |
+
|
| 756 |
+
This may not recognize links in some situations. Usually, a more
|
| 757 |
+
comprehensive formatter, such as a Markdown library, is a better
|
| 758 |
+
choice.
|
| 759 |
+
|
| 760 |
+
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
|
| 761 |
+
addresses. Links with trailing punctuation (periods, commas, closing
|
| 762 |
+
parentheses) and leading punctuation (opening parentheses) are
|
| 763 |
+
recognized excluding the punctuation. Email addresses that include
|
| 764 |
+
header fields are not recognized (for example,
|
| 765 |
+
``mailto:address@example.com?cc=copy@example.com``).
|
| 766 |
+
|
| 767 |
+
:param value: Original text containing URLs to link.
|
| 768 |
+
:param trim_url_limit: Shorten displayed URL values to this length.
|
| 769 |
+
:param nofollow: Add the ``rel=nofollow`` attribute to links.
|
| 770 |
+
:param target: Add the ``target`` attribute to links.
|
| 771 |
+
:param rel: Add the ``rel`` attribute to links.
|
| 772 |
+
:param extra_schemes: Recognize URLs that start with these schemes
|
| 773 |
+
in addition to the default behavior. Defaults to
|
| 774 |
+
``env.policies["urlize.extra_schemes"]``, which defaults to no
|
| 775 |
+
extra schemes.
|
| 776 |
+
|
| 777 |
+
.. versionchanged:: 3.0
|
| 778 |
+
The ``extra_schemes`` parameter was added.
|
| 779 |
+
|
| 780 |
+
.. versionchanged:: 3.0
|
| 781 |
+
Generate ``https://`` links for URLs without a scheme.
|
| 782 |
+
|
| 783 |
+
.. versionchanged:: 3.0
|
| 784 |
+
The parsing rules were updated. Recognize email addresses with
|
| 785 |
+
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
|
| 786 |
+
parentheses and brackets in more cases.
|
| 787 |
+
|
| 788 |
+
.. versionchanged:: 2.8
|
| 789 |
+
The ``target`` parameter was added.
|
| 790 |
+
"""
|
| 791 |
+
policies = eval_ctx.environment.policies
|
| 792 |
+
rel_parts = set((rel or "").split())
|
| 793 |
+
|
| 794 |
+
if nofollow:
|
| 795 |
+
rel_parts.add("nofollow")
|
| 796 |
+
|
| 797 |
+
rel_parts.update((policies["urlize.rel"] or "").split())
|
| 798 |
+
rel = " ".join(sorted(rel_parts)) or None
|
| 799 |
+
|
| 800 |
+
if target is None:
|
| 801 |
+
target = policies["urlize.target"]
|
| 802 |
+
|
| 803 |
+
if extra_schemes is None:
|
| 804 |
+
extra_schemes = policies["urlize.extra_schemes"] or ()
|
| 805 |
+
|
| 806 |
+
for scheme in extra_schemes:
|
| 807 |
+
if _uri_scheme_re.fullmatch(scheme) is None:
|
| 808 |
+
raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")
|
| 809 |
+
|
| 810 |
+
rv = urlize(
|
| 811 |
+
value,
|
| 812 |
+
trim_url_limit=trim_url_limit,
|
| 813 |
+
rel=rel,
|
| 814 |
+
target=target,
|
| 815 |
+
extra_schemes=extra_schemes,
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
if eval_ctx.autoescape:
|
| 819 |
+
rv = Markup(rv)
|
| 820 |
+
|
| 821 |
+
return rv
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def do_indent(
|
| 825 |
+
s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False
|
| 826 |
+
) -> str:
|
| 827 |
+
"""Return a copy of the string with each line indented by 4 spaces. The
|
| 828 |
+
first line and blank lines are not indented by default.
|
| 829 |
+
|
| 830 |
+
:param width: Number of spaces, or a string, to indent by.
|
| 831 |
+
:param first: Don't skip indenting the first line.
|
| 832 |
+
:param blank: Don't skip indenting empty lines.
|
| 833 |
+
|
| 834 |
+
.. versionchanged:: 3.0
|
| 835 |
+
``width`` can be a string.
|
| 836 |
+
|
| 837 |
+
.. versionchanged:: 2.10
|
| 838 |
+
Blank lines are not indented by default.
|
| 839 |
+
|
| 840 |
+
Rename the ``indentfirst`` argument to ``first``.
|
| 841 |
+
"""
|
| 842 |
+
if isinstance(width, str):
|
| 843 |
+
indention = width
|
| 844 |
+
else:
|
| 845 |
+
indention = " " * width
|
| 846 |
+
|
| 847 |
+
newline = "\n"
|
| 848 |
+
|
| 849 |
+
if isinstance(s, Markup):
|
| 850 |
+
indention = Markup(indention)
|
| 851 |
+
newline = Markup(newline)
|
| 852 |
+
|
| 853 |
+
s += newline # this quirk is necessary for splitlines method
|
| 854 |
+
|
| 855 |
+
if blank:
|
| 856 |
+
rv = (newline + indention).join(s.splitlines())
|
| 857 |
+
else:
|
| 858 |
+
lines = s.splitlines()
|
| 859 |
+
rv = lines.pop(0)
|
| 860 |
+
|
| 861 |
+
if lines:
|
| 862 |
+
rv += newline + newline.join(
|
| 863 |
+
indention + line if line else line for line in lines
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
if first:
|
| 867 |
+
rv = indention + rv
|
| 868 |
+
|
| 869 |
+
return rv
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
@pass_environment
|
| 873 |
+
def do_truncate(
|
| 874 |
+
env: "Environment",
|
| 875 |
+
s: str,
|
| 876 |
+
length: int = 255,
|
| 877 |
+
killwords: bool = False,
|
| 878 |
+
end: str = "...",
|
| 879 |
+
leeway: t.Optional[int] = None,
|
| 880 |
+
) -> str:
|
| 881 |
+
"""Return a truncated copy of the string. The length is specified
|
| 882 |
+
with the first parameter which defaults to ``255``. If the second
|
| 883 |
+
parameter is ``true`` the filter will cut the text at length. Otherwise
|
| 884 |
+
it will discard the last word. If the text was in fact
|
| 885 |
+
truncated it will append an ellipsis sign (``"..."``). If you want a
|
| 886 |
+
different ellipsis sign than ``"..."`` you can specify it using the
|
| 887 |
+
third parameter. Strings that only exceed the length by the tolerance
|
| 888 |
+
margin given in the fourth parameter will not be truncated.
|
| 889 |
+
|
| 890 |
+
.. sourcecode:: jinja
|
| 891 |
+
|
| 892 |
+
{{ "foo bar baz qux"|truncate(9) }}
|
| 893 |
+
-> "foo..."
|
| 894 |
+
{{ "foo bar baz qux"|truncate(9, True) }}
|
| 895 |
+
-> "foo ba..."
|
| 896 |
+
{{ "foo bar baz qux"|truncate(11) }}
|
| 897 |
+
-> "foo bar baz qux"
|
| 898 |
+
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
|
| 899 |
+
-> "foo bar..."
|
| 900 |
+
|
| 901 |
+
The default leeway on newer Jinja versions is 5 and was 0 before but
|
| 902 |
+
can be reconfigured globally.
|
| 903 |
+
"""
|
| 904 |
+
if leeway is None:
|
| 905 |
+
leeway = env.policies["truncate.leeway"]
|
| 906 |
+
|
| 907 |
+
assert length >= len(end), f"expected length >= {len(end)}, got {length}"
|
| 908 |
+
assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
|
| 909 |
+
|
| 910 |
+
if len(s) <= length + leeway:
|
| 911 |
+
return s
|
| 912 |
+
|
| 913 |
+
if killwords:
|
| 914 |
+
return s[: length - len(end)] + end
|
| 915 |
+
|
| 916 |
+
result = s[: length - len(end)].rsplit(" ", 1)[0]
|
| 917 |
+
return result + end
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
@pass_environment
|
| 921 |
+
def do_wordwrap(
|
| 922 |
+
environment: "Environment",
|
| 923 |
+
s: str,
|
| 924 |
+
width: int = 79,
|
| 925 |
+
break_long_words: bool = True,
|
| 926 |
+
wrapstring: t.Optional[str] = None,
|
| 927 |
+
break_on_hyphens: bool = True,
|
| 928 |
+
) -> str:
|
| 929 |
+
"""Wrap a string to the given width. Existing newlines are treated
|
| 930 |
+
as paragraphs to be wrapped separately.
|
| 931 |
+
|
| 932 |
+
:param s: Original text to wrap.
|
| 933 |
+
:param width: Maximum length of wrapped lines.
|
| 934 |
+
:param break_long_words: If a word is longer than ``width``, break
|
| 935 |
+
it across lines.
|
| 936 |
+
:param break_on_hyphens: If a word contains hyphens, it may be split
|
| 937 |
+
across lines.
|
| 938 |
+
:param wrapstring: String to join each wrapped line. Defaults to
|
| 939 |
+
:attr:`Environment.newline_sequence`.
|
| 940 |
+
|
| 941 |
+
.. versionchanged:: 2.11
|
| 942 |
+
Existing newlines are treated as paragraphs wrapped separately.
|
| 943 |
+
|
| 944 |
+
.. versionchanged:: 2.11
|
| 945 |
+
Added the ``break_on_hyphens`` parameter.
|
| 946 |
+
|
| 947 |
+
.. versionchanged:: 2.7
|
| 948 |
+
Added the ``wrapstring`` parameter.
|
| 949 |
+
"""
|
| 950 |
+
import textwrap
|
| 951 |
+
|
| 952 |
+
if wrapstring is None:
|
| 953 |
+
wrapstring = environment.newline_sequence
|
| 954 |
+
|
| 955 |
+
# textwrap.wrap doesn't consider existing newlines when wrapping.
|
| 956 |
+
# If the string has a newline before width, wrap will still insert
|
| 957 |
+
# a newline at width, resulting in a short line. Instead, split and
|
| 958 |
+
# wrap each paragraph individually.
|
| 959 |
+
return wrapstring.join(
|
| 960 |
+
[
|
| 961 |
+
wrapstring.join(
|
| 962 |
+
textwrap.wrap(
|
| 963 |
+
line,
|
| 964 |
+
width=width,
|
| 965 |
+
expand_tabs=False,
|
| 966 |
+
replace_whitespace=False,
|
| 967 |
+
break_long_words=break_long_words,
|
| 968 |
+
break_on_hyphens=break_on_hyphens,
|
| 969 |
+
)
|
| 970 |
+
)
|
| 971 |
+
for line in s.splitlines()
|
| 972 |
+
]
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
_word_re = re.compile(r"\w+")
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
def do_wordcount(s: str) -> int:
|
| 980 |
+
"""Count the words in that string."""
|
| 981 |
+
return len(_word_re.findall(soft_str(s)))
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:
|
| 985 |
+
"""Convert the value into an integer. If the
|
| 986 |
+
conversion doesn't work it will return ``0``. You can
|
| 987 |
+
override this default using the first parameter. You
|
| 988 |
+
can also override the default base (10) in the second
|
| 989 |
+
parameter, which handles input with prefixes such as
|
| 990 |
+
0b, 0o and 0x for bases 2, 8 and 16 respectively.
|
| 991 |
+
The base is ignored for decimal numbers and non-string values.
|
| 992 |
+
"""
|
| 993 |
+
try:
|
| 994 |
+
if isinstance(value, str):
|
| 995 |
+
return int(value, base)
|
| 996 |
+
|
| 997 |
+
return int(value)
|
| 998 |
+
except (TypeError, ValueError):
|
| 999 |
+
# this quirk is necessary so that "42.23"|int gives 42.
|
| 1000 |
+
try:
|
| 1001 |
+
return int(float(value))
|
| 1002 |
+
except (TypeError, ValueError, OverflowError):
|
| 1003 |
+
return default
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
def do_float(value: t.Any, default: float = 0.0) -> float:
|
| 1007 |
+
"""Convert the value into a floating point number. If the
|
| 1008 |
+
conversion doesn't work it will return ``0.0``. You can
|
| 1009 |
+
override this default using the first parameter.
|
| 1010 |
+
"""
|
| 1011 |
+
try:
|
| 1012 |
+
return float(value)
|
| 1013 |
+
except (TypeError, ValueError):
|
| 1014 |
+
return default
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
|
| 1018 |
+
"""Apply the given values to a `printf-style`_ format string, like
|
| 1019 |
+
``string % values``.
|
| 1020 |
+
|
| 1021 |
+
.. sourcecode:: jinja
|
| 1022 |
+
|
| 1023 |
+
{{ "%s, %s!"|format(greeting, name) }}
|
| 1024 |
+
Hello, World!
|
| 1025 |
+
|
| 1026 |
+
In most cases it should be more convenient and efficient to use the
|
| 1027 |
+
``%`` operator or :meth:`str.format`.
|
| 1028 |
+
|
| 1029 |
+
.. code-block:: text
|
| 1030 |
+
|
| 1031 |
+
{{ "%s, %s!" % (greeting, name) }}
|
| 1032 |
+
{{ "{}, {}!".format(greeting, name) }}
|
| 1033 |
+
|
| 1034 |
+
.. _printf-style: https://docs.python.org/library/stdtypes.html
|
| 1035 |
+
#printf-style-string-formatting
|
| 1036 |
+
"""
|
| 1037 |
+
if args and kwargs:
|
| 1038 |
+
raise FilterArgumentError(
|
| 1039 |
+
"can't handle positional and keyword arguments at the same time"
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
return soft_str(value) % (kwargs or args)
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def do_trim(value: str, chars: t.Optional[str] = None) -> str:
|
| 1046 |
+
"""Strip leading and trailing characters, by default whitespace."""
|
| 1047 |
+
return soft_str(value).strip(chars)
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
def do_striptags(value: "t.Union[str, HasHTML]") -> str:
|
| 1051 |
+
"""Strip SGML/XML tags and replace adjacent whitespace by one space."""
|
| 1052 |
+
if hasattr(value, "__html__"):
|
| 1053 |
+
value = t.cast("HasHTML", value).__html__()
|
| 1054 |
+
|
| 1055 |
+
return Markup(str(value)).striptags()
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
+
def sync_do_slice(
|
| 1059 |
+
value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None
|
| 1060 |
+
) -> "t.Iterator[t.List[V]]":
|
| 1061 |
+
"""Slice an iterator and return a list of lists containing
|
| 1062 |
+
those items. Useful if you want to create a div containing
|
| 1063 |
+
three ul tags that represent columns:
|
| 1064 |
+
|
| 1065 |
+
.. sourcecode:: html+jinja
|
| 1066 |
+
|
| 1067 |
+
<div class="columnwrapper">
|
| 1068 |
+
{%- for column in items|slice(3) %}
|
| 1069 |
+
<ul class="column-{{ loop.index }}">
|
| 1070 |
+
{%- for item in column %}
|
| 1071 |
+
<li>{{ item }}</li>
|
| 1072 |
+
{%- endfor %}
|
| 1073 |
+
</ul>
|
| 1074 |
+
{%- endfor %}
|
| 1075 |
+
</div>
|
| 1076 |
+
|
| 1077 |
+
If you pass it a second argument it's used to fill missing
|
| 1078 |
+
values on the last iteration.
|
| 1079 |
+
"""
|
| 1080 |
+
seq = list(value)
|
| 1081 |
+
length = len(seq)
|
| 1082 |
+
items_per_slice = length // slices
|
| 1083 |
+
slices_with_extra = length % slices
|
| 1084 |
+
offset = 0
|
| 1085 |
+
|
| 1086 |
+
for slice_number in range(slices):
|
| 1087 |
+
start = offset + slice_number * items_per_slice
|
| 1088 |
+
|
| 1089 |
+
if slice_number < slices_with_extra:
|
| 1090 |
+
offset += 1
|
| 1091 |
+
|
| 1092 |
+
end = offset + (slice_number + 1) * items_per_slice
|
| 1093 |
+
tmp = seq[start:end]
|
| 1094 |
+
|
| 1095 |
+
if fill_with is not None and slice_number >= slices_with_extra:
|
| 1096 |
+
tmp.append(fill_with)
|
| 1097 |
+
|
| 1098 |
+
yield tmp
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
@async_variant(sync_do_slice) # type: ignore
|
| 1102 |
+
async def do_slice(
|
| 1103 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1104 |
+
slices: int,
|
| 1105 |
+
fill_with: t.Optional[t.Any] = None,
|
| 1106 |
+
) -> "t.Iterator[t.List[V]]":
|
| 1107 |
+
return sync_do_slice(await auto_to_list(value), slices, fill_with)
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
def do_batch(
|
| 1111 |
+
value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
|
| 1112 |
+
) -> "t.Iterator[t.List[V]]":
|
| 1113 |
+
"""
|
| 1114 |
+
A filter that batches items. It works pretty much like `slice`
|
| 1115 |
+
just the other way round. It returns a list of lists with the
|
| 1116 |
+
given number of items. If you provide a second parameter this
|
| 1117 |
+
is used to fill up missing items. See this example:
|
| 1118 |
+
|
| 1119 |
+
.. sourcecode:: html+jinja
|
| 1120 |
+
|
| 1121 |
+
<table>
|
| 1122 |
+
{%- for row in items|batch(3, ' ') %}
|
| 1123 |
+
<tr>
|
| 1124 |
+
{%- for column in row %}
|
| 1125 |
+
<td>{{ column }}</td>
|
| 1126 |
+
{%- endfor %}
|
| 1127 |
+
</tr>
|
| 1128 |
+
{%- endfor %}
|
| 1129 |
+
</table>
|
| 1130 |
+
"""
|
| 1131 |
+
tmp: t.List[V] = []
|
| 1132 |
+
|
| 1133 |
+
for item in value:
|
| 1134 |
+
if len(tmp) == linecount:
|
| 1135 |
+
yield tmp
|
| 1136 |
+
tmp = []
|
| 1137 |
+
|
| 1138 |
+
tmp.append(item)
|
| 1139 |
+
|
| 1140 |
+
if tmp:
|
| 1141 |
+
if fill_with is not None and len(tmp) < linecount:
|
| 1142 |
+
tmp += [fill_with] * (linecount - len(tmp))
|
| 1143 |
+
|
| 1144 |
+
yield tmp
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
def do_round(
|
| 1148 |
+
value: float,
|
| 1149 |
+
precision: int = 0,
|
| 1150 |
+
method: 'te.Literal["common", "ceil", "floor"]' = "common",
|
| 1151 |
+
) -> float:
|
| 1152 |
+
"""Round the number to a given precision. The first
|
| 1153 |
+
parameter specifies the precision (default is ``0``), the
|
| 1154 |
+
second the rounding method:
|
| 1155 |
+
|
| 1156 |
+
- ``'common'`` rounds either up or down
|
| 1157 |
+
- ``'ceil'`` always rounds up
|
| 1158 |
+
- ``'floor'`` always rounds down
|
| 1159 |
+
|
| 1160 |
+
If you don't specify a method ``'common'`` is used.
|
| 1161 |
+
|
| 1162 |
+
.. sourcecode:: jinja
|
| 1163 |
+
|
| 1164 |
+
{{ 42.55|round }}
|
| 1165 |
+
-> 43.0
|
| 1166 |
+
{{ 42.55|round(1, 'floor') }}
|
| 1167 |
+
-> 42.5
|
| 1168 |
+
|
| 1169 |
+
Note that even if rounded to 0 precision, a float is returned. If
|
| 1170 |
+
you need a real integer, pipe it through `int`:
|
| 1171 |
+
|
| 1172 |
+
.. sourcecode:: jinja
|
| 1173 |
+
|
| 1174 |
+
{{ 42.55|round|int }}
|
| 1175 |
+
-> 43
|
| 1176 |
+
"""
|
| 1177 |
+
if method not in {"common", "ceil", "floor"}:
|
| 1178 |
+
raise FilterArgumentError("method must be common, ceil or floor")
|
| 1179 |
+
|
| 1180 |
+
if method == "common":
|
| 1181 |
+
return round(value, precision)
|
| 1182 |
+
|
| 1183 |
+
func = getattr(math, method)
|
| 1184 |
+
return t.cast(float, func(value * (10**precision)) / (10**precision))
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
class _GroupTuple(t.NamedTuple):
|
| 1188 |
+
grouper: t.Any
|
| 1189 |
+
list: t.List[t.Any]
|
| 1190 |
+
|
| 1191 |
+
# Use the regular tuple repr to hide this subclass if users print
|
| 1192 |
+
# out the value during debugging.
|
| 1193 |
+
def __repr__(self) -> str:
|
| 1194 |
+
return tuple.__repr__(self)
|
| 1195 |
+
|
| 1196 |
+
def __str__(self) -> str:
|
| 1197 |
+
return tuple.__str__(self)
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
@pass_environment
|
| 1201 |
+
def sync_do_groupby(
|
| 1202 |
+
environment: "Environment",
|
| 1203 |
+
value: "t.Iterable[V]",
|
| 1204 |
+
attribute: t.Union[str, int],
|
| 1205 |
+
default: t.Optional[t.Any] = None,
|
| 1206 |
+
case_sensitive: bool = False,
|
| 1207 |
+
) -> "t.List[_GroupTuple]":
|
| 1208 |
+
"""Group a sequence of objects by an attribute using Python's
|
| 1209 |
+
:func:`itertools.groupby`. The attribute can use dot notation for
|
| 1210 |
+
nested access, like ``"address.city"``. Unlike Python's ``groupby``,
|
| 1211 |
+
the values are sorted first so only one group is returned for each
|
| 1212 |
+
unique value.
|
| 1213 |
+
|
| 1214 |
+
For example, a list of ``User`` objects with a ``city`` attribute
|
| 1215 |
+
can be rendered in groups. In this example, ``grouper`` refers to
|
| 1216 |
+
the ``city`` value of the group.
|
| 1217 |
+
|
| 1218 |
+
.. sourcecode:: html+jinja
|
| 1219 |
+
|
| 1220 |
+
<ul>{% for city, items in users|groupby("city") %}
|
| 1221 |
+
<li>{{ city }}
|
| 1222 |
+
<ul>{% for user in items %}
|
| 1223 |
+
<li>{{ user.name }}
|
| 1224 |
+
{% endfor %}</ul>
|
| 1225 |
+
</li>
|
| 1226 |
+
{% endfor %}</ul>
|
| 1227 |
+
|
| 1228 |
+
``groupby`` yields namedtuples of ``(grouper, list)``, which
|
| 1229 |
+
can be used instead of the tuple unpacking above. ``grouper`` is the
|
| 1230 |
+
value of the attribute, and ``list`` is the items with that value.
|
| 1231 |
+
|
| 1232 |
+
.. sourcecode:: html+jinja
|
| 1233 |
+
|
| 1234 |
+
<ul>{% for group in users|groupby("city") %}
|
| 1235 |
+
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
|
| 1236 |
+
{% endfor %}</ul>
|
| 1237 |
+
|
| 1238 |
+
You can specify a ``default`` value to use if an object in the list
|
| 1239 |
+
does not have the given attribute.
|
| 1240 |
+
|
| 1241 |
+
.. sourcecode:: jinja
|
| 1242 |
+
|
| 1243 |
+
<ul>{% for city, items in users|groupby("city", default="NY") %}
|
| 1244 |
+
<li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
|
| 1245 |
+
{% endfor %}</ul>
|
| 1246 |
+
|
| 1247 |
+
Like the :func:`~jinja-filters.sort` filter, sorting and grouping is
|
| 1248 |
+
case-insensitive by default. The ``key`` for each group will have
|
| 1249 |
+
the case of the first item in that group of values. For example, if
|
| 1250 |
+
a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group
|
| 1251 |
+
will have two values. This can be disabled by passing
|
| 1252 |
+
``case_sensitive=True``.
|
| 1253 |
+
|
| 1254 |
+
.. versionchanged:: 3.1
|
| 1255 |
+
Added the ``case_sensitive`` parameter. Sorting and grouping is
|
| 1256 |
+
case-insensitive by default, matching other filters that do
|
| 1257 |
+
comparisons.
|
| 1258 |
+
|
| 1259 |
+
.. versionchanged:: 3.0
|
| 1260 |
+
Added the ``default`` parameter.
|
| 1261 |
+
|
| 1262 |
+
.. versionchanged:: 2.6
|
| 1263 |
+
The attribute supports dot notation for nested access.
|
| 1264 |
+
"""
|
| 1265 |
+
expr = make_attrgetter(
|
| 1266 |
+
environment,
|
| 1267 |
+
attribute,
|
| 1268 |
+
postprocess=ignore_case if not case_sensitive else None,
|
| 1269 |
+
default=default,
|
| 1270 |
+
)
|
| 1271 |
+
out = [
|
| 1272 |
+
_GroupTuple(key, list(values))
|
| 1273 |
+
for key, values in groupby(sorted(value, key=expr), expr)
|
| 1274 |
+
]
|
| 1275 |
+
|
| 1276 |
+
if not case_sensitive:
|
| 1277 |
+
# Return the real key from the first value instead of the lowercase key.
|
| 1278 |
+
output_expr = make_attrgetter(environment, attribute, default=default)
|
| 1279 |
+
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
|
| 1280 |
+
|
| 1281 |
+
return out
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
@async_variant(sync_do_groupby) # type: ignore
|
| 1285 |
+
async def do_groupby(
|
| 1286 |
+
environment: "Environment",
|
| 1287 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1288 |
+
attribute: t.Union[str, int],
|
| 1289 |
+
default: t.Optional[t.Any] = None,
|
| 1290 |
+
case_sensitive: bool = False,
|
| 1291 |
+
) -> "t.List[_GroupTuple]":
|
| 1292 |
+
expr = make_attrgetter(
|
| 1293 |
+
environment,
|
| 1294 |
+
attribute,
|
| 1295 |
+
postprocess=ignore_case if not case_sensitive else None,
|
| 1296 |
+
default=default,
|
| 1297 |
+
)
|
| 1298 |
+
out = [
|
| 1299 |
+
_GroupTuple(key, await auto_to_list(values))
|
| 1300 |
+
for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
|
| 1301 |
+
]
|
| 1302 |
+
|
| 1303 |
+
if not case_sensitive:
|
| 1304 |
+
# Return the real key from the first value instead of the lowercase key.
|
| 1305 |
+
output_expr = make_attrgetter(environment, attribute, default=default)
|
| 1306 |
+
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
|
| 1307 |
+
|
| 1308 |
+
return out
|
| 1309 |
+
|
| 1310 |
+
|
| 1311 |
+
@pass_environment
|
| 1312 |
+
def sync_do_sum(
|
| 1313 |
+
environment: "Environment",
|
| 1314 |
+
iterable: "t.Iterable[V]",
|
| 1315 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 1316 |
+
start: V = 0, # type: ignore
|
| 1317 |
+
) -> V:
|
| 1318 |
+
"""Returns the sum of a sequence of numbers plus the value of parameter
|
| 1319 |
+
'start' (which defaults to 0). When the sequence is empty it returns
|
| 1320 |
+
start.
|
| 1321 |
+
|
| 1322 |
+
It is also possible to sum up only certain attributes:
|
| 1323 |
+
|
| 1324 |
+
.. sourcecode:: jinja
|
| 1325 |
+
|
| 1326 |
+
Total: {{ items|sum(attribute='price') }}
|
| 1327 |
+
|
| 1328 |
+
.. versionchanged:: 2.6
|
| 1329 |
+
The ``attribute`` parameter was added to allow summing up over
|
| 1330 |
+
attributes. Also the ``start`` parameter was moved on to the right.
|
| 1331 |
+
"""
|
| 1332 |
+
if attribute is not None:
|
| 1333 |
+
iterable = map(make_attrgetter(environment, attribute), iterable)
|
| 1334 |
+
|
| 1335 |
+
return sum(iterable, start) # type: ignore[no-any-return, call-overload]
|
| 1336 |
+
|
| 1337 |
+
|
| 1338 |
+
@async_variant(sync_do_sum) # type: ignore
|
| 1339 |
+
async def do_sum(
|
| 1340 |
+
environment: "Environment",
|
| 1341 |
+
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1342 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
| 1343 |
+
start: V = 0, # type: ignore
|
| 1344 |
+
) -> V:
|
| 1345 |
+
rv = start
|
| 1346 |
+
|
| 1347 |
+
if attribute is not None:
|
| 1348 |
+
func = make_attrgetter(environment, attribute)
|
| 1349 |
+
else:
|
| 1350 |
+
|
| 1351 |
+
def func(x: V) -> V:
|
| 1352 |
+
return x
|
| 1353 |
+
|
| 1354 |
+
async for item in auto_aiter(iterable):
|
| 1355 |
+
rv += func(item)
|
| 1356 |
+
|
| 1357 |
+
return rv
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":
|
| 1361 |
+
"""Convert the value into a list. If it was a string the returned list
|
| 1362 |
+
will be a list of characters.
|
| 1363 |
+
"""
|
| 1364 |
+
return list(value)
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
@async_variant(sync_do_list) # type: ignore
|
| 1368 |
+
async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":
|
| 1369 |
+
return await auto_to_list(value)
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def do_mark_safe(value: str) -> Markup:
|
| 1373 |
+
"""Mark the value as safe which means that in an environment with automatic
|
| 1374 |
+
escaping enabled this variable will not be escaped.
|
| 1375 |
+
"""
|
| 1376 |
+
return Markup(value)
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def do_mark_unsafe(value: str) -> str:
|
| 1380 |
+
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
|
| 1381 |
+
return str(value)
|
| 1382 |
+
|
| 1383 |
+
|
| 1384 |
+
@typing.overload
|
| 1385 |
+
def do_reverse(value: str) -> str: ...
|
| 1386 |
+
|
| 1387 |
+
|
| 1388 |
+
@typing.overload
|
| 1389 |
+
def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...
|
| 1390 |
+
|
| 1391 |
+
|
| 1392 |
+
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
|
| 1393 |
+
"""Reverse the object or return an iterator that iterates over it the other
|
| 1394 |
+
way round.
|
| 1395 |
+
"""
|
| 1396 |
+
if isinstance(value, str):
|
| 1397 |
+
return value[::-1]
|
| 1398 |
+
|
| 1399 |
+
try:
|
| 1400 |
+
return reversed(value) # type: ignore
|
| 1401 |
+
except TypeError:
|
| 1402 |
+
try:
|
| 1403 |
+
rv = list(value)
|
| 1404 |
+
rv.reverse()
|
| 1405 |
+
return rv
|
| 1406 |
+
except TypeError as e:
|
| 1407 |
+
raise FilterArgumentError("argument must be iterable") from e
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
@pass_environment
|
| 1411 |
+
def do_attr(
|
| 1412 |
+
environment: "Environment", obj: t.Any, name: str
|
| 1413 |
+
) -> t.Union[Undefined, t.Any]:
|
| 1414 |
+
"""Get an attribute of an object. ``foo|attr("bar")`` works like
|
| 1415 |
+
``foo.bar`` just that always an attribute is returned and items are not
|
| 1416 |
+
looked up.
|
| 1417 |
+
|
| 1418 |
+
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
|
| 1419 |
+
"""
|
| 1420 |
+
try:
|
| 1421 |
+
name = str(name)
|
| 1422 |
+
except UnicodeError:
|
| 1423 |
+
pass
|
| 1424 |
+
else:
|
| 1425 |
+
try:
|
| 1426 |
+
value = getattr(obj, name)
|
| 1427 |
+
except AttributeError:
|
| 1428 |
+
pass
|
| 1429 |
+
else:
|
| 1430 |
+
if environment.sandboxed:
|
| 1431 |
+
environment = t.cast("SandboxedEnvironment", environment)
|
| 1432 |
+
|
| 1433 |
+
if not environment.is_safe_attribute(obj, name, value):
|
| 1434 |
+
return environment.unsafe_undefined(obj, name)
|
| 1435 |
+
|
| 1436 |
+
return value
|
| 1437 |
+
|
| 1438 |
+
return environment.undefined(obj=obj, name=name)
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
@typing.overload
|
| 1442 |
+
def sync_do_map(
|
| 1443 |
+
context: "Context",
|
| 1444 |
+
value: t.Iterable[t.Any],
|
| 1445 |
+
name: str,
|
| 1446 |
+
*args: t.Any,
|
| 1447 |
+
**kwargs: t.Any,
|
| 1448 |
+
) -> t.Iterable[t.Any]: ...
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
@typing.overload
|
| 1452 |
+
def sync_do_map(
|
| 1453 |
+
context: "Context",
|
| 1454 |
+
value: t.Iterable[t.Any],
|
| 1455 |
+
*,
|
| 1456 |
+
attribute: str = ...,
|
| 1457 |
+
default: t.Optional[t.Any] = None,
|
| 1458 |
+
) -> t.Iterable[t.Any]: ...
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
@pass_context
|
| 1462 |
+
def sync_do_map(
|
| 1463 |
+
context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any
|
| 1464 |
+
) -> t.Iterable[t.Any]:
|
| 1465 |
+
"""Applies a filter on a sequence of objects or looks up an attribute.
|
| 1466 |
+
This is useful when dealing with lists of objects but you are really
|
| 1467 |
+
only interested in a certain value of it.
|
| 1468 |
+
|
| 1469 |
+
The basic usage is mapping on an attribute. Imagine you have a list
|
| 1470 |
+
of users but you are only interested in a list of usernames:
|
| 1471 |
+
|
| 1472 |
+
.. sourcecode:: jinja
|
| 1473 |
+
|
| 1474 |
+
Users on this page: {{ users|map(attribute='username')|join(', ') }}
|
| 1475 |
+
|
| 1476 |
+
You can specify a ``default`` value to use if an object in the list
|
| 1477 |
+
does not have the given attribute.
|
| 1478 |
+
|
| 1479 |
+
.. sourcecode:: jinja
|
| 1480 |
+
|
| 1481 |
+
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
|
| 1482 |
+
|
| 1483 |
+
Alternatively you can let it invoke a filter by passing the name of the
|
| 1484 |
+
filter and the arguments afterwards. A good example would be applying a
|
| 1485 |
+
text conversion filter on a sequence:
|
| 1486 |
+
|
| 1487 |
+
.. sourcecode:: jinja
|
| 1488 |
+
|
| 1489 |
+
Users on this page: {{ titles|map('lower')|join(', ') }}
|
| 1490 |
+
|
| 1491 |
+
Similar to a generator comprehension such as:
|
| 1492 |
+
|
| 1493 |
+
.. code-block:: python
|
| 1494 |
+
|
| 1495 |
+
(u.username for u in users)
|
| 1496 |
+
(getattr(u, "username", "Anonymous") for u in users)
|
| 1497 |
+
(do_lower(x) for x in titles)
|
| 1498 |
+
|
| 1499 |
+
.. versionchanged:: 2.11.0
|
| 1500 |
+
Added the ``default`` parameter.
|
| 1501 |
+
|
| 1502 |
+
.. versionadded:: 2.7
|
| 1503 |
+
"""
|
| 1504 |
+
if value:
|
| 1505 |
+
func = prepare_map(context, args, kwargs)
|
| 1506 |
+
|
| 1507 |
+
for item in value:
|
| 1508 |
+
yield func(item)
|
| 1509 |
+
|
| 1510 |
+
|
| 1511 |
+
@typing.overload
|
| 1512 |
+
def do_map(
|
| 1513 |
+
context: "Context",
|
| 1514 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 1515 |
+
name: str,
|
| 1516 |
+
*args: t.Any,
|
| 1517 |
+
**kwargs: t.Any,
|
| 1518 |
+
) -> t.Iterable[t.Any]: ...
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
@typing.overload
|
| 1522 |
+
def do_map(
|
| 1523 |
+
context: "Context",
|
| 1524 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 1525 |
+
*,
|
| 1526 |
+
attribute: str = ...,
|
| 1527 |
+
default: t.Optional[t.Any] = None,
|
| 1528 |
+
) -> t.Iterable[t.Any]: ...
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
@async_variant(sync_do_map) # type: ignore
|
| 1532 |
+
async def do_map(
|
| 1533 |
+
context: "Context",
|
| 1534 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
| 1535 |
+
*args: t.Any,
|
| 1536 |
+
**kwargs: t.Any,
|
| 1537 |
+
) -> t.AsyncIterable[t.Any]:
|
| 1538 |
+
if value:
|
| 1539 |
+
func = prepare_map(context, args, kwargs)
|
| 1540 |
+
|
| 1541 |
+
async for item in auto_aiter(value):
|
| 1542 |
+
yield await auto_await(func(item))
|
| 1543 |
+
|
| 1544 |
+
|
| 1545 |
+
@pass_context
|
| 1546 |
+
def sync_do_select(
|
| 1547 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1548 |
+
) -> "t.Iterator[V]":
|
| 1549 |
+
"""Filters a sequence of objects by applying a test to each object,
|
| 1550 |
+
and only selecting the objects with the test succeeding.
|
| 1551 |
+
|
| 1552 |
+
If no test is specified, each object will be evaluated as a boolean.
|
| 1553 |
+
|
| 1554 |
+
Example usage:
|
| 1555 |
+
|
| 1556 |
+
.. sourcecode:: jinja
|
| 1557 |
+
|
| 1558 |
+
{{ numbers|select("odd") }}
|
| 1559 |
+
{{ numbers|select("odd") }}
|
| 1560 |
+
{{ numbers|select("divisibleby", 3) }}
|
| 1561 |
+
{{ numbers|select("lessthan", 42) }}
|
| 1562 |
+
{{ strings|select("equalto", "mystring") }}
|
| 1563 |
+
|
| 1564 |
+
Similar to a generator comprehension such as:
|
| 1565 |
+
|
| 1566 |
+
.. code-block:: python
|
| 1567 |
+
|
| 1568 |
+
(n for n in numbers if test_odd(n))
|
| 1569 |
+
(n for n in numbers if test_divisibleby(n, 3))
|
| 1570 |
+
|
| 1571 |
+
.. versionadded:: 2.7
|
| 1572 |
+
"""
|
| 1573 |
+
return select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
| 1574 |
+
|
| 1575 |
+
|
| 1576 |
+
@async_variant(sync_do_select) # type: ignore
|
| 1577 |
+
async def do_select(
|
| 1578 |
+
context: "Context",
|
| 1579 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1580 |
+
*args: t.Any,
|
| 1581 |
+
**kwargs: t.Any,
|
| 1582 |
+
) -> "t.AsyncIterator[V]":
|
| 1583 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
@pass_context
|
| 1587 |
+
def sync_do_reject(
|
| 1588 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1589 |
+
) -> "t.Iterator[V]":
|
| 1590 |
+
"""Filters a sequence of objects by applying a test to each object,
|
| 1591 |
+
and rejecting the objects with the test succeeding.
|
| 1592 |
+
|
| 1593 |
+
If no test is specified, each object will be evaluated as a boolean.
|
| 1594 |
+
|
| 1595 |
+
Example usage:
|
| 1596 |
+
|
| 1597 |
+
.. sourcecode:: jinja
|
| 1598 |
+
|
| 1599 |
+
{{ numbers|reject("odd") }}
|
| 1600 |
+
|
| 1601 |
+
Similar to a generator comprehension such as:
|
| 1602 |
+
|
| 1603 |
+
.. code-block:: python
|
| 1604 |
+
|
| 1605 |
+
(n for n in numbers if not test_odd(n))
|
| 1606 |
+
|
| 1607 |
+
.. versionadded:: 2.7
|
| 1608 |
+
"""
|
| 1609 |
+
return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
| 1610 |
+
|
| 1611 |
+
|
| 1612 |
+
@async_variant(sync_do_reject) # type: ignore
|
| 1613 |
+
async def do_reject(
|
| 1614 |
+
context: "Context",
|
| 1615 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1616 |
+
*args: t.Any,
|
| 1617 |
+
**kwargs: t.Any,
|
| 1618 |
+
) -> "t.AsyncIterator[V]":
|
| 1619 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
| 1620 |
+
|
| 1621 |
+
|
| 1622 |
+
@pass_context
|
| 1623 |
+
def sync_do_selectattr(
|
| 1624 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1625 |
+
) -> "t.Iterator[V]":
|
| 1626 |
+
"""Filters a sequence of objects by applying a test to the specified
|
| 1627 |
+
attribute of each object, and only selecting the objects with the
|
| 1628 |
+
test succeeding.
|
| 1629 |
+
|
| 1630 |
+
If no test is specified, the attribute's value will be evaluated as
|
| 1631 |
+
a boolean.
|
| 1632 |
+
|
| 1633 |
+
Example usage:
|
| 1634 |
+
|
| 1635 |
+
.. sourcecode:: jinja
|
| 1636 |
+
|
| 1637 |
+
{{ users|selectattr("is_active") }}
|
| 1638 |
+
{{ users|selectattr("email", "none") }}
|
| 1639 |
+
|
| 1640 |
+
Similar to a generator comprehension such as:
|
| 1641 |
+
|
| 1642 |
+
.. code-block:: python
|
| 1643 |
+
|
| 1644 |
+
(user for user in users if user.is_active)
|
| 1645 |
+
(user for user in users if test_none(user.email))
|
| 1646 |
+
|
| 1647 |
+
.. versionadded:: 2.7
|
| 1648 |
+
"""
|
| 1649 |
+
return select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
| 1650 |
+
|
| 1651 |
+
|
| 1652 |
+
@async_variant(sync_do_selectattr) # type: ignore
|
| 1653 |
+
async def do_selectattr(
|
| 1654 |
+
context: "Context",
|
| 1655 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1656 |
+
*args: t.Any,
|
| 1657 |
+
**kwargs: t.Any,
|
| 1658 |
+
) -> "t.AsyncIterator[V]":
|
| 1659 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
| 1660 |
+
|
| 1661 |
+
|
| 1662 |
+
@pass_context
|
| 1663 |
+
def sync_do_rejectattr(
|
| 1664 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
| 1665 |
+
) -> "t.Iterator[V]":
|
| 1666 |
+
"""Filters a sequence of objects by applying a test to the specified
|
| 1667 |
+
attribute of each object, and rejecting the objects with the test
|
| 1668 |
+
succeeding.
|
| 1669 |
+
|
| 1670 |
+
If no test is specified, the attribute's value will be evaluated as
|
| 1671 |
+
a boolean.
|
| 1672 |
+
|
| 1673 |
+
.. sourcecode:: jinja
|
| 1674 |
+
|
| 1675 |
+
{{ users|rejectattr("is_active") }}
|
| 1676 |
+
{{ users|rejectattr("email", "none") }}
|
| 1677 |
+
|
| 1678 |
+
Similar to a generator comprehension such as:
|
| 1679 |
+
|
| 1680 |
+
.. code-block:: python
|
| 1681 |
+
|
| 1682 |
+
(user for user in users if not user.is_active)
|
| 1683 |
+
(user for user in users if not test_none(user.email))
|
| 1684 |
+
|
| 1685 |
+
.. versionadded:: 2.7
|
| 1686 |
+
"""
|
| 1687 |
+
return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
| 1688 |
+
|
| 1689 |
+
|
| 1690 |
+
@async_variant(sync_do_rejectattr) # type: ignore
|
| 1691 |
+
async def do_rejectattr(
|
| 1692 |
+
context: "Context",
|
| 1693 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1694 |
+
*args: t.Any,
|
| 1695 |
+
**kwargs: t.Any,
|
| 1696 |
+
) -> "t.AsyncIterator[V]":
|
| 1697 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
@pass_eval_context
|
| 1701 |
+
def do_tojson(
|
| 1702 |
+
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
|
| 1703 |
+
) -> Markup:
|
| 1704 |
+
"""Serialize an object to a string of JSON, and mark it safe to
|
| 1705 |
+
render in HTML. This filter is only for use in HTML documents.
|
| 1706 |
+
|
| 1707 |
+
The returned string is safe to render in HTML documents and
|
| 1708 |
+
``<script>`` tags. The exception is in HTML attributes that are
|
| 1709 |
+
double quoted; either use single quotes or the ``|forceescape``
|
| 1710 |
+
filter.
|
| 1711 |
+
|
| 1712 |
+
:param value: The object to serialize to JSON.
|
| 1713 |
+
:param indent: The ``indent`` parameter passed to ``dumps``, for
|
| 1714 |
+
pretty-printing the value.
|
| 1715 |
+
|
| 1716 |
+
.. versionadded:: 2.9
|
| 1717 |
+
"""
|
| 1718 |
+
policies = eval_ctx.environment.policies
|
| 1719 |
+
dumps = policies["json.dumps_function"]
|
| 1720 |
+
kwargs = policies["json.dumps_kwargs"]
|
| 1721 |
+
|
| 1722 |
+
if indent is not None:
|
| 1723 |
+
kwargs = kwargs.copy()
|
| 1724 |
+
kwargs["indent"] = indent
|
| 1725 |
+
|
| 1726 |
+
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
|
| 1727 |
+
|
| 1728 |
+
|
| 1729 |
+
def prepare_map(
|
| 1730 |
+
context: "Context", args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]
|
| 1731 |
+
) -> t.Callable[[t.Any], t.Any]:
|
| 1732 |
+
if not args and "attribute" in kwargs:
|
| 1733 |
+
attribute = kwargs.pop("attribute")
|
| 1734 |
+
default = kwargs.pop("default", None)
|
| 1735 |
+
|
| 1736 |
+
if kwargs:
|
| 1737 |
+
raise FilterArgumentError(
|
| 1738 |
+
f"Unexpected keyword argument {next(iter(kwargs))!r}"
|
| 1739 |
+
)
|
| 1740 |
+
|
| 1741 |
+
func = make_attrgetter(context.environment, attribute, default=default)
|
| 1742 |
+
else:
|
| 1743 |
+
try:
|
| 1744 |
+
name = args[0]
|
| 1745 |
+
args = args[1:]
|
| 1746 |
+
except LookupError:
|
| 1747 |
+
raise FilterArgumentError("map requires a filter argument") from None
|
| 1748 |
+
|
| 1749 |
+
def func(item: t.Any) -> t.Any:
|
| 1750 |
+
return context.environment.call_filter(
|
| 1751 |
+
name, item, args, kwargs, context=context
|
| 1752 |
+
)
|
| 1753 |
+
|
| 1754 |
+
return func
|
| 1755 |
+
|
| 1756 |
+
|
| 1757 |
+
def prepare_select_or_reject(
|
| 1758 |
+
context: "Context",
|
| 1759 |
+
args: t.Tuple[t.Any, ...],
|
| 1760 |
+
kwargs: t.Dict[str, t.Any],
|
| 1761 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
| 1762 |
+
lookup_attr: bool,
|
| 1763 |
+
) -> t.Callable[[t.Any], t.Any]:
|
| 1764 |
+
if lookup_attr:
|
| 1765 |
+
try:
|
| 1766 |
+
attr = args[0]
|
| 1767 |
+
except LookupError:
|
| 1768 |
+
raise FilterArgumentError("Missing parameter for attribute name") from None
|
| 1769 |
+
|
| 1770 |
+
transfunc = make_attrgetter(context.environment, attr)
|
| 1771 |
+
off = 1
|
| 1772 |
+
else:
|
| 1773 |
+
off = 0
|
| 1774 |
+
|
| 1775 |
+
def transfunc(x: V) -> V:
|
| 1776 |
+
return x
|
| 1777 |
+
|
| 1778 |
+
try:
|
| 1779 |
+
name = args[off]
|
| 1780 |
+
args = args[1 + off :]
|
| 1781 |
+
|
| 1782 |
+
def func(item: t.Any) -> t.Any:
|
| 1783 |
+
return context.environment.call_test(name, item, args, kwargs, context)
|
| 1784 |
+
|
| 1785 |
+
except LookupError:
|
| 1786 |
+
func = bool # type: ignore
|
| 1787 |
+
|
| 1788 |
+
return lambda item: modfunc(func(transfunc(item)))
|
| 1789 |
+
|
| 1790 |
+
|
| 1791 |
+
def select_or_reject(
|
| 1792 |
+
context: "Context",
|
| 1793 |
+
value: "t.Iterable[V]",
|
| 1794 |
+
args: t.Tuple[t.Any, ...],
|
| 1795 |
+
kwargs: t.Dict[str, t.Any],
|
| 1796 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
| 1797 |
+
lookup_attr: bool,
|
| 1798 |
+
) -> "t.Iterator[V]":
|
| 1799 |
+
if value:
|
| 1800 |
+
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
|
| 1801 |
+
|
| 1802 |
+
for item in value:
|
| 1803 |
+
if func(item):
|
| 1804 |
+
yield item
|
| 1805 |
+
|
| 1806 |
+
|
| 1807 |
+
async def async_select_or_reject(
|
| 1808 |
+
context: "Context",
|
| 1809 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
| 1810 |
+
args: t.Tuple[t.Any, ...],
|
| 1811 |
+
kwargs: t.Dict[str, t.Any],
|
| 1812 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
| 1813 |
+
lookup_attr: bool,
|
| 1814 |
+
) -> "t.AsyncIterator[V]":
|
| 1815 |
+
if value:
|
| 1816 |
+
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
|
| 1817 |
+
|
| 1818 |
+
async for item in auto_aiter(value):
|
| 1819 |
+
if func(item):
|
| 1820 |
+
yield item
|
| 1821 |
+
|
| 1822 |
+
|
| 1823 |
+
FILTERS = {
|
| 1824 |
+
"abs": abs,
|
| 1825 |
+
"attr": do_attr,
|
| 1826 |
+
"batch": do_batch,
|
| 1827 |
+
"capitalize": do_capitalize,
|
| 1828 |
+
"center": do_center,
|
| 1829 |
+
"count": len,
|
| 1830 |
+
"d": do_default,
|
| 1831 |
+
"default": do_default,
|
| 1832 |
+
"dictsort": do_dictsort,
|
| 1833 |
+
"e": escape,
|
| 1834 |
+
"escape": escape,
|
| 1835 |
+
"filesizeformat": do_filesizeformat,
|
| 1836 |
+
"first": do_first,
|
| 1837 |
+
"float": do_float,
|
| 1838 |
+
"forceescape": do_forceescape,
|
| 1839 |
+
"format": do_format,
|
| 1840 |
+
"groupby": do_groupby,
|
| 1841 |
+
"indent": do_indent,
|
| 1842 |
+
"int": do_int,
|
| 1843 |
+
"join": do_join,
|
| 1844 |
+
"last": do_last,
|
| 1845 |
+
"length": len,
|
| 1846 |
+
"list": do_list,
|
| 1847 |
+
"lower": do_lower,
|
| 1848 |
+
"items": do_items,
|
| 1849 |
+
"map": do_map,
|
| 1850 |
+
"min": do_min,
|
| 1851 |
+
"max": do_max,
|
| 1852 |
+
"pprint": do_pprint,
|
| 1853 |
+
"random": do_random,
|
| 1854 |
+
"reject": do_reject,
|
| 1855 |
+
"rejectattr": do_rejectattr,
|
| 1856 |
+
"replace": do_replace,
|
| 1857 |
+
"reverse": do_reverse,
|
| 1858 |
+
"round": do_round,
|
| 1859 |
+
"safe": do_mark_safe,
|
| 1860 |
+
"select": do_select,
|
| 1861 |
+
"selectattr": do_selectattr,
|
| 1862 |
+
"slice": do_slice,
|
| 1863 |
+
"sort": do_sort,
|
| 1864 |
+
"string": soft_str,
|
| 1865 |
+
"striptags": do_striptags,
|
| 1866 |
+
"sum": do_sum,
|
| 1867 |
+
"title": do_title,
|
| 1868 |
+
"trim": do_trim,
|
| 1869 |
+
"truncate": do_truncate,
|
| 1870 |
+
"unique": do_unique,
|
| 1871 |
+
"upper": do_upper,
|
| 1872 |
+
"urlencode": do_urlencode,
|
| 1873 |
+
"urlize": do_urlize,
|
| 1874 |
+
"wordcount": do_wordcount,
|
| 1875 |
+
"wordwrap": do_wordwrap,
|
| 1876 |
+
"xmlattr": do_xmlattr,
|
| 1877 |
+
"tojson": do_tojson,
|
| 1878 |
+
}
|
wemm/lib/python3.10/site-packages/jinja2/idtracking.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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FINED = "undefined"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def find_symbols(
|
| 16 |
+
nodes: t.Iterable[nodes.Node], parent_symbols: t.Optional["Symbols"] = None
|
| 17 |
+
) -> "Symbols":
|
| 18 |
+
sym = Symbols(parent=parent_symbols)
|
| 19 |
+
visitor = FrameSymbolVisitor(sym)
|
| 20 |
+
for node in nodes:
|
| 21 |
+
visitor.visit(node)
|
| 22 |
+
return sym
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def symbols_for_node(
|
| 26 |
+
node: nodes.Node, parent_symbols: t.Optional["Symbols"] = None
|
| 27 |
+
) -> "Symbols":
|
| 28 |
+
sym = Symbols(parent=parent_symbols)
|
| 29 |
+
sym.analyze_node(node)
|
| 30 |
+
return sym
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Symbols:
|
| 34 |
+
def __init__(
|
| 35 |
+
self, parent: t.Optional["Symbols"] = None, level: t.Optional[int] = None
|
| 36 |
+
) -> None:
|
| 37 |
+
if level is None:
|
| 38 |
+
if parent is None:
|
| 39 |
+
level = 0
|
| 40 |
+
else:
|
| 41 |
+
level = parent.level + 1
|
| 42 |
+
|
| 43 |
+
self.level: int = level
|
| 44 |
+
self.parent = parent
|
| 45 |
+
self.refs: t.Dict[str, str] = {}
|
| 46 |
+
self.loads: t.Dict[str, t.Any] = {}
|
| 47 |
+
self.stores: t.Set[str] = set()
|
| 48 |
+
|
| 49 |
+
def analyze_node(self, node: nodes.Node, **kwargs: t.Any) -> None:
|
| 50 |
+
visitor = RootVisitor(self)
|
| 51 |
+
visitor.visit(node, **kwargs)
|
| 52 |
+
|
| 53 |
+
def _define_ref(
|
| 54 |
+
self, name: str, load: t.Optional[t.Tuple[str, t.Optional[str]]] = None
|
| 55 |
+
) -> str:
|
| 56 |
+
ident = f"l_{self.level}_{name}"
|
| 57 |
+
self.refs[name] = ident
|
| 58 |
+
if load is not None:
|
| 59 |
+
self.loads[ident] = load
|
| 60 |
+
return ident
|
| 61 |
+
|
| 62 |
+
def find_load(self, target: str) -> t.Optional[t.Any]:
|
| 63 |
+
if target in self.loads:
|
| 64 |
+
return self.loads[target]
|
| 65 |
+
|
| 66 |
+
if self.parent is not None:
|
| 67 |
+
return self.parent.find_load(target)
|
| 68 |
+
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
def find_ref(self, name: str) -> t.Optional[str]:
|
| 72 |
+
if name in self.refs:
|
| 73 |
+
return self.refs[name]
|
| 74 |
+
|
| 75 |
+
if self.parent is not None:
|
| 76 |
+
return self.parent.find_ref(name)
|
| 77 |
+
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
def ref(self, name: str) -> str:
|
| 81 |
+
rv = self.find_ref(name)
|
| 82 |
+
if rv is None:
|
| 83 |
+
raise AssertionError(
|
| 84 |
+
"Tried to resolve a name to a reference that was"
|
| 85 |
+
f" unknown to the frame ({name!r})"
|
| 86 |
+
)
|
| 87 |
+
return rv
|
| 88 |
+
|
| 89 |
+
def copy(self) -> "te.Self":
|
| 90 |
+
rv = object.__new__(self.__class__)
|
| 91 |
+
rv.__dict__.update(self.__dict__)
|
| 92 |
+
rv.refs = self.refs.copy()
|
| 93 |
+
rv.loads = self.loads.copy()
|
| 94 |
+
rv.stores = self.stores.copy()
|
| 95 |
+
return rv
|
| 96 |
+
|
| 97 |
+
def store(self, name: str) -> None:
|
| 98 |
+
self.stores.add(name)
|
| 99 |
+
|
| 100 |
+
# If we have not see the name referenced yet, we need to figure
|
| 101 |
+
# out what to set it to.
|
| 102 |
+
if name not in self.refs:
|
| 103 |
+
# If there is a parent scope we check if the name has a
|
| 104 |
+
# reference there. If it does it means we might have to alias
|
| 105 |
+
# to a variable there.
|
| 106 |
+
if self.parent is not None:
|
| 107 |
+
outer_ref = self.parent.find_ref(name)
|
| 108 |
+
if outer_ref is not None:
|
| 109 |
+
self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
# Otherwise we can just set it to undefined.
|
| 113 |
+
self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))
|
| 114 |
+
|
| 115 |
+
def declare_parameter(self, name: str) -> str:
|
| 116 |
+
self.stores.add(name)
|
| 117 |
+
return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))
|
| 118 |
+
|
| 119 |
+
def load(self, name: str) -> None:
|
| 120 |
+
if self.find_ref(name) is None:
|
| 121 |
+
self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))
|
| 122 |
+
|
| 123 |
+
def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:
|
| 124 |
+
stores: t.Set[str] = set()
|
| 125 |
+
|
| 126 |
+
for branch in branch_symbols:
|
| 127 |
+
stores.update(branch.stores)
|
| 128 |
+
|
| 129 |
+
stores.difference_update(self.stores)
|
| 130 |
+
|
| 131 |
+
for sym in branch_symbols:
|
| 132 |
+
self.refs.update(sym.refs)
|
| 133 |
+
self.loads.update(sym.loads)
|
| 134 |
+
self.stores.update(sym.stores)
|
| 135 |
+
|
| 136 |
+
for name in stores:
|
| 137 |
+
target = self.find_ref(name)
|
| 138 |
+
assert target is not None, "should not happen"
|
| 139 |
+
|
| 140 |
+
if self.parent is not None:
|
| 141 |
+
outer_target = self.parent.find_ref(name)
|
| 142 |
+
if outer_target is not None:
|
| 143 |
+
self.loads[target] = (VAR_LOAD_ALIAS, outer_target)
|
| 144 |
+
continue
|
| 145 |
+
self.loads[target] = (VAR_LOAD_RESOLVE, name)
|
| 146 |
+
|
| 147 |
+
def dump_stores(self) -> t.Dict[str, str]:
|
| 148 |
+
rv: t.Dict[str, str] = {}
|
| 149 |
+
node: t.Optional[Symbols] = self
|
| 150 |
+
|
| 151 |
+
while node is not None:
|
| 152 |
+
for name in sorted(node.stores):
|
| 153 |
+
if name not in rv:
|
| 154 |
+
rv[name] = self.find_ref(name) # type: ignore
|
| 155 |
+
|
| 156 |
+
node = node.parent
|
| 157 |
+
|
| 158 |
+
return rv
|
| 159 |
+
|
| 160 |
+
def dump_param_targets(self) -> t.Set[str]:
|
| 161 |
+
rv = set()
|
| 162 |
+
node: t.Optional[Symbols] = self
|
| 163 |
+
|
| 164 |
+
while node is not None:
|
| 165 |
+
for target, (instr, _) in self.loads.items():
|
| 166 |
+
if instr == VAR_LOAD_PARAMETER:
|
| 167 |
+
rv.add(target)
|
| 168 |
+
|
| 169 |
+
node = node.parent
|
| 170 |
+
|
| 171 |
+
return rv
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class RootVisitor(NodeVisitor):
|
| 175 |
+
def __init__(self, symbols: "Symbols") -> None:
|
| 176 |
+
self.sym_visitor = FrameSymbolVisitor(symbols)
|
| 177 |
+
|
| 178 |
+
def _simple_visit(self, node: nodes.Node, **kwargs: t.Any) -> None:
|
| 179 |
+
for child in node.iter_child_nodes():
|
| 180 |
+
self.sym_visitor.visit(child)
|
| 181 |
+
|
| 182 |
+
visit_Template = _simple_visit
|
| 183 |
+
visit_Block = _simple_visit
|
| 184 |
+
visit_Macro = _simple_visit
|
| 185 |
+
visit_FilterBlock = _simple_visit
|
| 186 |
+
visit_Scope = _simple_visit
|
| 187 |
+
visit_If = _simple_visit
|
| 188 |
+
visit_ScopedEvalContextModifier = _simple_visit
|
| 189 |
+
|
| 190 |
+
def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:
|
| 191 |
+
for child in node.body:
|
| 192 |
+
self.sym_visitor.visit(child)
|
| 193 |
+
|
| 194 |
+
def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:
|
| 195 |
+
for child in node.iter_child_nodes(exclude=("call",)):
|
| 196 |
+
self.sym_visitor.visit(child)
|
| 197 |
+
|
| 198 |
+
def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:
|
| 199 |
+
for child in node.body:
|
| 200 |
+
self.sym_visitor.visit(child)
|
| 201 |
+
|
| 202 |
+
def visit_For(
|
| 203 |
+
self, node: nodes.For, for_branch: str = "body", **kwargs: t.Any
|
| 204 |
+
) -> None:
|
| 205 |
+
if for_branch == "body":
|
| 206 |
+
self.sym_visitor.visit(node.target, store_as_param=True)
|
| 207 |
+
branch = node.body
|
| 208 |
+
elif for_branch == "else":
|
| 209 |
+
branch = node.else_
|
| 210 |
+
elif for_branch == "test":
|
| 211 |
+
self.sym_visitor.visit(node.target, store_as_param=True)
|
| 212 |
+
if node.test is not None:
|
| 213 |
+
self.sym_visitor.visit(node.test)
|
| 214 |
+
return
|
| 215 |
+
else:
|
| 216 |
+
raise RuntimeError("Unknown for branch")
|
| 217 |
+
|
| 218 |
+
if branch:
|
| 219 |
+
for item in branch:
|
| 220 |
+
self.sym_visitor.visit(item)
|
| 221 |
+
|
| 222 |
+
def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:
|
| 223 |
+
for target in node.targets:
|
| 224 |
+
self.sym_visitor.visit(target)
|
| 225 |
+
for child in node.body:
|
| 226 |
+
self.sym_visitor.visit(child)
|
| 227 |
+
|
| 228 |
+
def generic_visit(self, node: nodes.Node, *args: t.Any, **kwargs: t.Any) -> None:
|
| 229 |
+
raise NotImplementedError(f"Cannot find symbols for {type(node).__name__!r}")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class FrameSymbolVisitor(NodeVisitor):
|
| 233 |
+
"""A visitor for `Frame.inspect`."""
|
| 234 |
+
|
| 235 |
+
def __init__(self, symbols: "Symbols") -> None:
|
| 236 |
+
self.symbols = symbols
|
| 237 |
+
|
| 238 |
+
def visit_Name(
|
| 239 |
+
self, node: nodes.Name, store_as_param: bool = False, **kwargs: t.Any
|
| 240 |
+
) -> None:
|
| 241 |
+
"""All assignments to names go through this function."""
|
| 242 |
+
if store_as_param or node.ctx == "param":
|
| 243 |
+
self.symbols.declare_parameter(node.name)
|
| 244 |
+
elif node.ctx == "store":
|
| 245 |
+
self.symbols.store(node.name)
|
| 246 |
+
elif node.ctx == "load":
|
| 247 |
+
self.symbols.load(node.name)
|
| 248 |
+
|
| 249 |
+
def visit_NSRef(self, node: nodes.NSRef, **kwargs: t.Any) -> None:
|
| 250 |
+
self.symbols.load(node.name)
|
| 251 |
+
|
| 252 |
+
def visit_If(self, node: nodes.If, **kwargs: t.Any) -> None:
|
| 253 |
+
self.visit(node.test, **kwargs)
|
| 254 |
+
original_symbols = self.symbols
|
| 255 |
+
|
| 256 |
+
def inner_visit(nodes: t.Iterable[nodes.Node]) -> "Symbols":
|
| 257 |
+
self.symbols = rv = original_symbols.copy()
|
| 258 |
+
|
| 259 |
+
for subnode in nodes:
|
| 260 |
+
self.visit(subnode, **kwargs)
|
| 261 |
+
|
| 262 |
+
self.symbols = original_symbols
|
| 263 |
+
return rv
|
| 264 |
+
|
| 265 |
+
body_symbols = inner_visit(node.body)
|
| 266 |
+
elif_symbols = inner_visit(node.elif_)
|
| 267 |
+
else_symbols = inner_visit(node.else_ or ())
|
| 268 |
+
self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])
|
| 269 |
+
|
| 270 |
+
def visit_Macro(self, node: nodes.Macro, **kwargs: t.Any) -> None:
|
| 271 |
+
self.symbols.store(node.name)
|
| 272 |
+
|
| 273 |
+
def visit_Import(self, node: nodes.Import, **kwargs: t.Any) -> None:
|
| 274 |
+
self.generic_visit(node, **kwargs)
|
| 275 |
+
self.symbols.store(node.target)
|
| 276 |
+
|
| 277 |
+
def visit_FromImport(self, node: nodes.FromImport, **kwargs: t.Any) -> None:
|
| 278 |
+
self.generic_visit(node, **kwargs)
|
| 279 |
+
|
| 280 |
+
for name in node.names:
|
| 281 |
+
if isinstance(name, tuple):
|
| 282 |
+
self.symbols.store(name[1])
|
| 283 |
+
else:
|
| 284 |
+
self.symbols.store(name)
|
| 285 |
+
|
| 286 |
+
def visit_Assign(self, node: nodes.Assign, **kwargs: t.Any) -> None:
|
| 287 |
+
"""Visit assignments in the correct order."""
|
| 288 |
+
self.visit(node.node, **kwargs)
|
| 289 |
+
self.visit(node.target, **kwargs)
|
| 290 |
+
|
| 291 |
+
def visit_For(self, node: nodes.For, **kwargs: t.Any) -> None:
|
| 292 |
+
"""Visiting stops at for blocks. However the block sequence
|
| 293 |
+
is visited as part of the outer scope.
|
| 294 |
+
"""
|
| 295 |
+
self.visit(node.iter, **kwargs)
|
| 296 |
+
|
| 297 |
+
def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:
|
| 298 |
+
self.visit(node.call, **kwargs)
|
| 299 |
+
|
| 300 |
+
def visit_FilterBlock(self, node: nodes.FilterBlock, **kwargs: t.Any) -> None:
|
| 301 |
+
self.visit(node.filter, **kwargs)
|
| 302 |
+
|
| 303 |
+
def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:
|
| 304 |
+
for target in node.values:
|
| 305 |
+
self.visit(target)
|
| 306 |
+
|
| 307 |
+
def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:
|
| 308 |
+
"""Stop visiting at block assigns."""
|
| 309 |
+
self.visit(node.target, **kwargs)
|
| 310 |
+
|
| 311 |
+
def visit_Scope(self, node: nodes.Scope, **kwargs: t.Any) -> None:
|
| 312 |
+
"""Stop visiting at scopes."""
|
| 313 |
+
|
| 314 |
+
def visit_Block(self, node: nodes.Block, **kwargs: t.Any) -> None:
|
| 315 |
+
"""Stop visiting at blocks."""
|
| 316 |
+
|
| 317 |
+
def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:
|
| 318 |
+
"""Do not visit into overlay scopes."""
|
wemm/lib/python3.10/site-packages/jinja2/loaders.py
ADDED
|
@@ -0,0 +1,693 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""API and implementations for loading templates from different data
|
| 2 |
+
sources.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import importlib.util
|
| 6 |
+
import os
|
| 7 |
+
import posixpath
|
| 8 |
+
import sys
|
| 9 |
+
import typing as t
|
| 10 |
+
import weakref
|
| 11 |
+
import zipimport
|
| 12 |
+
from collections import abc
|
| 13 |
+
from hashlib import sha1
|
| 14 |
+
from importlib import import_module
|
| 15 |
+
from types import ModuleType
|
| 16 |
+
|
| 17 |
+
from .exceptions import TemplateNotFound
|
| 18 |
+
from .utils import internalcode
|
| 19 |
+
|
| 20 |
+
if t.TYPE_CHECKING:
|
| 21 |
+
from .environment import Environment
|
| 22 |
+
from .environment import Template
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def split_template_path(template: str) -> t.List[str]:
|
| 26 |
+
"""Split a path into segments and perform a sanity check. If it detects
|
| 27 |
+
'..' in the path it will raise a `TemplateNotFound` error.
|
| 28 |
+
"""
|
| 29 |
+
pieces = []
|
| 30 |
+
for piece in template.split("/"):
|
| 31 |
+
if (
|
| 32 |
+
os.path.sep in piece
|
| 33 |
+
or (os.path.altsep and os.path.altsep in piece)
|
| 34 |
+
or piece == os.path.pardir
|
| 35 |
+
):
|
| 36 |
+
raise TemplateNotFound(template)
|
| 37 |
+
elif piece and piece != ".":
|
| 38 |
+
pieces.append(piece)
|
| 39 |
+
return pieces
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BaseLoader:
|
| 43 |
+
"""Baseclass for all loaders. Subclass this and override `get_source` to
|
| 44 |
+
implement a custom loading mechanism. The environment provides a
|
| 45 |
+
`get_template` method that calls the loader's `load` method to get the
|
| 46 |
+
:class:`Template` object.
|
| 47 |
+
|
| 48 |
+
A very basic example for a loader that looks up templates on the file
|
| 49 |
+
system could look like this::
|
| 50 |
+
|
| 51 |
+
from jinja2 import BaseLoader, TemplateNotFound
|
| 52 |
+
from os.path import join, exists, getmtime
|
| 53 |
+
|
| 54 |
+
class MyLoader(BaseLoader):
|
| 55 |
+
|
| 56 |
+
def __init__(self, path):
|
| 57 |
+
self.path = path
|
| 58 |
+
|
| 59 |
+
def get_source(self, environment, template):
|
| 60 |
+
path = join(self.path, template)
|
| 61 |
+
if not exists(path):
|
| 62 |
+
raise TemplateNotFound(template)
|
| 63 |
+
mtime = getmtime(path)
|
| 64 |
+
with open(path) as f:
|
| 65 |
+
source = f.read()
|
| 66 |
+
return source, path, lambda: mtime == getmtime(path)
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
#: if set to `False` it indicates that the loader cannot provide access
|
| 70 |
+
#: to the source of templates.
|
| 71 |
+
#:
|
| 72 |
+
#: .. versionadded:: 2.4
|
| 73 |
+
has_source_access = True
|
| 74 |
+
|
| 75 |
+
def get_source(
|
| 76 |
+
self, environment: "Environment", template: str
|
| 77 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 78 |
+
"""Get the template source, filename and reload helper for a template.
|
| 79 |
+
It's passed the environment and template name and has to return a
|
| 80 |
+
tuple in the form ``(source, filename, uptodate)`` or raise a
|
| 81 |
+
`TemplateNotFound` error if it can't locate the template.
|
| 82 |
+
|
| 83 |
+
The source part of the returned tuple must be the source of the
|
| 84 |
+
template as a string. The filename should be the name of the
|
| 85 |
+
file on the filesystem if it was loaded from there, otherwise
|
| 86 |
+
``None``. The filename is used by Python for the tracebacks
|
| 87 |
+
if no loader extension is used.
|
| 88 |
+
|
| 89 |
+
The last item in the tuple is the `uptodate` function. If auto
|
| 90 |
+
reloading is enabled it's always called to check if the template
|
| 91 |
+
changed. No arguments are passed so the function must store the
|
| 92 |
+
old state somewhere (for example in a closure). If it returns `False`
|
| 93 |
+
the template will be reloaded.
|
| 94 |
+
"""
|
| 95 |
+
if not self.has_source_access:
|
| 96 |
+
raise RuntimeError(
|
| 97 |
+
f"{type(self).__name__} cannot provide access to the source"
|
| 98 |
+
)
|
| 99 |
+
raise TemplateNotFound(template)
|
| 100 |
+
|
| 101 |
+
def list_templates(self) -> t.List[str]:
|
| 102 |
+
"""Iterates over all templates. If the loader does not support that
|
| 103 |
+
it should raise a :exc:`TypeError` which is the default behavior.
|
| 104 |
+
"""
|
| 105 |
+
raise TypeError("this loader cannot iterate over all templates")
|
| 106 |
+
|
| 107 |
+
@internalcode
|
| 108 |
+
def load(
|
| 109 |
+
self,
|
| 110 |
+
environment: "Environment",
|
| 111 |
+
name: str,
|
| 112 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 113 |
+
) -> "Template":
|
| 114 |
+
"""Loads a template. This method looks up the template in the cache
|
| 115 |
+
or loads one by calling :meth:`get_source`. Subclasses should not
|
| 116 |
+
override this method as loaders working on collections of other
|
| 117 |
+
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
|
| 118 |
+
will not call this method but `get_source` directly.
|
| 119 |
+
"""
|
| 120 |
+
code = None
|
| 121 |
+
if globals is None:
|
| 122 |
+
globals = {}
|
| 123 |
+
|
| 124 |
+
# first we try to get the source for this template together
|
| 125 |
+
# with the filename and the uptodate function.
|
| 126 |
+
source, filename, uptodate = self.get_source(environment, name)
|
| 127 |
+
|
| 128 |
+
# try to load the code from the bytecode cache if there is a
|
| 129 |
+
# bytecode cache configured.
|
| 130 |
+
bcc = environment.bytecode_cache
|
| 131 |
+
if bcc is not None:
|
| 132 |
+
bucket = bcc.get_bucket(environment, name, filename, source)
|
| 133 |
+
code = bucket.code
|
| 134 |
+
|
| 135 |
+
# if we don't have code so far (not cached, no longer up to
|
| 136 |
+
# date) etc. we compile the template
|
| 137 |
+
if code is None:
|
| 138 |
+
code = environment.compile(source, name, filename)
|
| 139 |
+
|
| 140 |
+
# if the bytecode cache is available and the bucket doesn't
|
| 141 |
+
# have a code so far, we give the bucket the new code and put
|
| 142 |
+
# it back to the bytecode cache.
|
| 143 |
+
if bcc is not None and bucket.code is None:
|
| 144 |
+
bucket.code = code
|
| 145 |
+
bcc.set_bucket(bucket)
|
| 146 |
+
|
| 147 |
+
return environment.template_class.from_code(
|
| 148 |
+
environment, code, globals, uptodate
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class FileSystemLoader(BaseLoader):
|
| 153 |
+
"""Load templates from a directory in the file system.
|
| 154 |
+
|
| 155 |
+
The path can be relative or absolute. Relative paths are relative to
|
| 156 |
+
the current working directory.
|
| 157 |
+
|
| 158 |
+
.. code-block:: python
|
| 159 |
+
|
| 160 |
+
loader = FileSystemLoader("templates")
|
| 161 |
+
|
| 162 |
+
A list of paths can be given. The directories will be searched in
|
| 163 |
+
order, stopping at the first matching template.
|
| 164 |
+
|
| 165 |
+
.. code-block:: python
|
| 166 |
+
|
| 167 |
+
loader = FileSystemLoader(["/override/templates", "/default/templates"])
|
| 168 |
+
|
| 169 |
+
:param searchpath: A path, or list of paths, to the directory that
|
| 170 |
+
contains the templates.
|
| 171 |
+
:param encoding: Use this encoding to read the text from template
|
| 172 |
+
files.
|
| 173 |
+
:param followlinks: Follow symbolic links in the path.
|
| 174 |
+
|
| 175 |
+
.. versionchanged:: 2.8
|
| 176 |
+
Added the ``followlinks`` parameter.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
searchpath: t.Union[
|
| 182 |
+
str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
|
| 183 |
+
],
|
| 184 |
+
encoding: str = "utf-8",
|
| 185 |
+
followlinks: bool = False,
|
| 186 |
+
) -> None:
|
| 187 |
+
if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
|
| 188 |
+
searchpath = [searchpath]
|
| 189 |
+
|
| 190 |
+
self.searchpath = [os.fspath(p) for p in searchpath]
|
| 191 |
+
self.encoding = encoding
|
| 192 |
+
self.followlinks = followlinks
|
| 193 |
+
|
| 194 |
+
def get_source(
|
| 195 |
+
self, environment: "Environment", template: str
|
| 196 |
+
) -> t.Tuple[str, str, t.Callable[[], bool]]:
|
| 197 |
+
pieces = split_template_path(template)
|
| 198 |
+
|
| 199 |
+
for searchpath in self.searchpath:
|
| 200 |
+
# Use posixpath even on Windows to avoid "drive:" or UNC
|
| 201 |
+
# segments breaking out of the search directory.
|
| 202 |
+
filename = posixpath.join(searchpath, *pieces)
|
| 203 |
+
|
| 204 |
+
if os.path.isfile(filename):
|
| 205 |
+
break
|
| 206 |
+
else:
|
| 207 |
+
plural = "path" if len(self.searchpath) == 1 else "paths"
|
| 208 |
+
paths_str = ", ".join(repr(p) for p in self.searchpath)
|
| 209 |
+
raise TemplateNotFound(
|
| 210 |
+
template,
|
| 211 |
+
f"{template!r} not found in search {plural}: {paths_str}",
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
with open(filename, encoding=self.encoding) as f:
|
| 215 |
+
contents = f.read()
|
| 216 |
+
|
| 217 |
+
mtime = os.path.getmtime(filename)
|
| 218 |
+
|
| 219 |
+
def uptodate() -> bool:
|
| 220 |
+
try:
|
| 221 |
+
return os.path.getmtime(filename) == mtime
|
| 222 |
+
except OSError:
|
| 223 |
+
return False
|
| 224 |
+
|
| 225 |
+
# Use normpath to convert Windows altsep to sep.
|
| 226 |
+
return contents, os.path.normpath(filename), uptodate
|
| 227 |
+
|
| 228 |
+
def list_templates(self) -> t.List[str]:
|
| 229 |
+
found = set()
|
| 230 |
+
for searchpath in self.searchpath:
|
| 231 |
+
walk_dir = os.walk(searchpath, followlinks=self.followlinks)
|
| 232 |
+
for dirpath, _, filenames in walk_dir:
|
| 233 |
+
for filename in filenames:
|
| 234 |
+
template = (
|
| 235 |
+
os.path.join(dirpath, filename)[len(searchpath) :]
|
| 236 |
+
.strip(os.path.sep)
|
| 237 |
+
.replace(os.path.sep, "/")
|
| 238 |
+
)
|
| 239 |
+
if template[:2] == "./":
|
| 240 |
+
template = template[2:]
|
| 241 |
+
if template not in found:
|
| 242 |
+
found.add(template)
|
| 243 |
+
return sorted(found)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if sys.version_info >= (3, 13):
|
| 247 |
+
|
| 248 |
+
def _get_zipimporter_files(z: t.Any) -> t.Dict[str, object]:
|
| 249 |
+
try:
|
| 250 |
+
get_files = z._get_files
|
| 251 |
+
except AttributeError as e:
|
| 252 |
+
raise TypeError(
|
| 253 |
+
"This zip import does not have the required"
|
| 254 |
+
" metadata to list templates."
|
| 255 |
+
) from e
|
| 256 |
+
return get_files()
|
| 257 |
+
else:
|
| 258 |
+
|
| 259 |
+
def _get_zipimporter_files(z: t.Any) -> t.Dict[str, object]:
|
| 260 |
+
try:
|
| 261 |
+
files = z._files
|
| 262 |
+
except AttributeError as e:
|
| 263 |
+
raise TypeError(
|
| 264 |
+
"This zip import does not have the required"
|
| 265 |
+
" metadata to list templates."
|
| 266 |
+
) from e
|
| 267 |
+
return files # type: ignore[no-any-return]
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class PackageLoader(BaseLoader):
|
| 271 |
+
"""Load templates from a directory in a Python package.
|
| 272 |
+
|
| 273 |
+
:param package_name: Import name of the package that contains the
|
| 274 |
+
template directory.
|
| 275 |
+
:param package_path: Directory within the imported package that
|
| 276 |
+
contains the templates.
|
| 277 |
+
:param encoding: Encoding of template files.
|
| 278 |
+
|
| 279 |
+
The following example looks up templates in the ``pages`` directory
|
| 280 |
+
within the ``project.ui`` package.
|
| 281 |
+
|
| 282 |
+
.. code-block:: python
|
| 283 |
+
|
| 284 |
+
loader = PackageLoader("project.ui", "pages")
|
| 285 |
+
|
| 286 |
+
Only packages installed as directories (standard pip behavior) or
|
| 287 |
+
zip/egg files (less common) are supported. The Python API for
|
| 288 |
+
introspecting data in packages is too limited to support other
|
| 289 |
+
installation methods the way this loader requires.
|
| 290 |
+
|
| 291 |
+
There is limited support for :pep:`420` namespace packages. The
|
| 292 |
+
template directory is assumed to only be in one namespace
|
| 293 |
+
contributor. Zip files contributing to a namespace are not
|
| 294 |
+
supported.
|
| 295 |
+
|
| 296 |
+
.. versionchanged:: 3.0
|
| 297 |
+
No longer uses ``setuptools`` as a dependency.
|
| 298 |
+
|
| 299 |
+
.. versionchanged:: 3.0
|
| 300 |
+
Limited PEP 420 namespace package support.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
def __init__(
|
| 304 |
+
self,
|
| 305 |
+
package_name: str,
|
| 306 |
+
package_path: "str" = "templates",
|
| 307 |
+
encoding: str = "utf-8",
|
| 308 |
+
) -> None:
|
| 309 |
+
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
|
| 310 |
+
|
| 311 |
+
# normpath preserves ".", which isn't valid in zip paths.
|
| 312 |
+
if package_path == os.path.curdir:
|
| 313 |
+
package_path = ""
|
| 314 |
+
elif package_path[:2] == os.path.curdir + os.path.sep:
|
| 315 |
+
package_path = package_path[2:]
|
| 316 |
+
|
| 317 |
+
self.package_path = package_path
|
| 318 |
+
self.package_name = package_name
|
| 319 |
+
self.encoding = encoding
|
| 320 |
+
|
| 321 |
+
# Make sure the package exists. This also makes namespace
|
| 322 |
+
# packages work, otherwise get_loader returns None.
|
| 323 |
+
import_module(package_name)
|
| 324 |
+
spec = importlib.util.find_spec(package_name)
|
| 325 |
+
assert spec is not None, "An import spec was not found for the package."
|
| 326 |
+
loader = spec.loader
|
| 327 |
+
assert loader is not None, "A loader was not found for the package."
|
| 328 |
+
self._loader = loader
|
| 329 |
+
self._archive = None
|
| 330 |
+
|
| 331 |
+
if isinstance(loader, zipimport.zipimporter):
|
| 332 |
+
self._archive = loader.archive
|
| 333 |
+
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
|
| 334 |
+
template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
|
| 335 |
+
else:
|
| 336 |
+
roots: t.List[str] = []
|
| 337 |
+
|
| 338 |
+
# One element for regular packages, multiple for namespace
|
| 339 |
+
# packages, or None for single module file.
|
| 340 |
+
if spec.submodule_search_locations:
|
| 341 |
+
roots.extend(spec.submodule_search_locations)
|
| 342 |
+
# A single module file, use the parent directory instead.
|
| 343 |
+
elif spec.origin is not None:
|
| 344 |
+
roots.append(os.path.dirname(spec.origin))
|
| 345 |
+
|
| 346 |
+
if not roots:
|
| 347 |
+
raise ValueError(
|
| 348 |
+
f"The {package_name!r} package was not installed in a"
|
| 349 |
+
" way that PackageLoader understands."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
for root in roots:
|
| 353 |
+
root = os.path.join(root, package_path)
|
| 354 |
+
|
| 355 |
+
if os.path.isdir(root):
|
| 356 |
+
template_root = root
|
| 357 |
+
break
|
| 358 |
+
else:
|
| 359 |
+
raise ValueError(
|
| 360 |
+
f"PackageLoader could not find a {package_path!r} directory"
|
| 361 |
+
f" in the {package_name!r} package."
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
self._template_root = template_root
|
| 365 |
+
|
| 366 |
+
def get_source(
|
| 367 |
+
self, environment: "Environment", template: str
|
| 368 |
+
) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
|
| 369 |
+
# Use posixpath even on Windows to avoid "drive:" or UNC
|
| 370 |
+
# segments breaking out of the search directory. Use normpath to
|
| 371 |
+
# convert Windows altsep to sep.
|
| 372 |
+
p = os.path.normpath(
|
| 373 |
+
posixpath.join(self._template_root, *split_template_path(template))
|
| 374 |
+
)
|
| 375 |
+
up_to_date: t.Optional[t.Callable[[], bool]]
|
| 376 |
+
|
| 377 |
+
if self._archive is None:
|
| 378 |
+
# Package is a directory.
|
| 379 |
+
if not os.path.isfile(p):
|
| 380 |
+
raise TemplateNotFound(template)
|
| 381 |
+
|
| 382 |
+
with open(p, "rb") as f:
|
| 383 |
+
source = f.read()
|
| 384 |
+
|
| 385 |
+
mtime = os.path.getmtime(p)
|
| 386 |
+
|
| 387 |
+
def up_to_date() -> bool:
|
| 388 |
+
return os.path.isfile(p) and os.path.getmtime(p) == mtime
|
| 389 |
+
|
| 390 |
+
else:
|
| 391 |
+
# Package is a zip file.
|
| 392 |
+
try:
|
| 393 |
+
source = self._loader.get_data(p) # type: ignore
|
| 394 |
+
except OSError as e:
|
| 395 |
+
raise TemplateNotFound(template) from e
|
| 396 |
+
|
| 397 |
+
# Could use the zip's mtime for all template mtimes, but
|
| 398 |
+
# would need to safely reload the module if it's out of
|
| 399 |
+
# date, so just report it as always current.
|
| 400 |
+
up_to_date = None
|
| 401 |
+
|
| 402 |
+
return source.decode(self.encoding), p, up_to_date
|
| 403 |
+
|
| 404 |
+
def list_templates(self) -> t.List[str]:
|
| 405 |
+
results: t.List[str] = []
|
| 406 |
+
|
| 407 |
+
if self._archive is None:
|
| 408 |
+
# Package is a directory.
|
| 409 |
+
offset = len(self._template_root)
|
| 410 |
+
|
| 411 |
+
for dirpath, _, filenames in os.walk(self._template_root):
|
| 412 |
+
dirpath = dirpath[offset:].lstrip(os.path.sep)
|
| 413 |
+
results.extend(
|
| 414 |
+
os.path.join(dirpath, name).replace(os.path.sep, "/")
|
| 415 |
+
for name in filenames
|
| 416 |
+
)
|
| 417 |
+
else:
|
| 418 |
+
files = _get_zipimporter_files(self._loader)
|
| 419 |
+
|
| 420 |
+
# Package is a zip file.
|
| 421 |
+
prefix = (
|
| 422 |
+
self._template_root[len(self._archive) :].lstrip(os.path.sep)
|
| 423 |
+
+ os.path.sep
|
| 424 |
+
)
|
| 425 |
+
offset = len(prefix)
|
| 426 |
+
|
| 427 |
+
for name in files:
|
| 428 |
+
# Find names under the templates directory that aren't directories.
|
| 429 |
+
if name.startswith(prefix) and name[-1] != os.path.sep:
|
| 430 |
+
results.append(name[offset:].replace(os.path.sep, "/"))
|
| 431 |
+
|
| 432 |
+
results.sort()
|
| 433 |
+
return results
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class DictLoader(BaseLoader):
|
| 437 |
+
"""Loads a template from a Python dict mapping template names to
|
| 438 |
+
template source. This loader is useful for unittesting:
|
| 439 |
+
|
| 440 |
+
>>> loader = DictLoader({'index.html': 'source here'})
|
| 441 |
+
|
| 442 |
+
Because auto reloading is rarely useful this is disabled by default.
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
def __init__(self, mapping: t.Mapping[str, str]) -> None:
|
| 446 |
+
self.mapping = mapping
|
| 447 |
+
|
| 448 |
+
def get_source(
|
| 449 |
+
self, environment: "Environment", template: str
|
| 450 |
+
) -> t.Tuple[str, None, t.Callable[[], bool]]:
|
| 451 |
+
if template in self.mapping:
|
| 452 |
+
source = self.mapping[template]
|
| 453 |
+
return source, None, lambda: source == self.mapping.get(template)
|
| 454 |
+
raise TemplateNotFound(template)
|
| 455 |
+
|
| 456 |
+
def list_templates(self) -> t.List[str]:
|
| 457 |
+
return sorted(self.mapping)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class FunctionLoader(BaseLoader):
|
| 461 |
+
"""A loader that is passed a function which does the loading. The
|
| 462 |
+
function receives the name of the template and has to return either
|
| 463 |
+
a string with the template source, a tuple in the form ``(source,
|
| 464 |
+
filename, uptodatefunc)`` or `None` if the template does not exist.
|
| 465 |
+
|
| 466 |
+
>>> def load_template(name):
|
| 467 |
+
... if name == 'index.html':
|
| 468 |
+
... return '...'
|
| 469 |
+
...
|
| 470 |
+
>>> loader = FunctionLoader(load_template)
|
| 471 |
+
|
| 472 |
+
The `uptodatefunc` is a function that is called if autoreload is enabled
|
| 473 |
+
and has to return `True` if the template is still up to date. For more
|
| 474 |
+
details have a look at :meth:`BaseLoader.get_source` which has the same
|
| 475 |
+
return value.
|
| 476 |
+
"""
|
| 477 |
+
|
| 478 |
+
def __init__(
|
| 479 |
+
self,
|
| 480 |
+
load_func: t.Callable[
|
| 481 |
+
[str],
|
| 482 |
+
t.Optional[
|
| 483 |
+
t.Union[
|
| 484 |
+
str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
|
| 485 |
+
]
|
| 486 |
+
],
|
| 487 |
+
],
|
| 488 |
+
) -> None:
|
| 489 |
+
self.load_func = load_func
|
| 490 |
+
|
| 491 |
+
def get_source(
|
| 492 |
+
self, environment: "Environment", template: str
|
| 493 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 494 |
+
rv = self.load_func(template)
|
| 495 |
+
|
| 496 |
+
if rv is None:
|
| 497 |
+
raise TemplateNotFound(template)
|
| 498 |
+
|
| 499 |
+
if isinstance(rv, str):
|
| 500 |
+
return rv, None, None
|
| 501 |
+
|
| 502 |
+
return rv
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
class PrefixLoader(BaseLoader):
|
| 506 |
+
"""A loader that is passed a dict of loaders where each loader is bound
|
| 507 |
+
to a prefix. The prefix is delimited from the template by a slash per
|
| 508 |
+
default, which can be changed by setting the `delimiter` argument to
|
| 509 |
+
something else::
|
| 510 |
+
|
| 511 |
+
loader = PrefixLoader({
|
| 512 |
+
'app1': PackageLoader('mypackage.app1'),
|
| 513 |
+
'app2': PackageLoader('mypackage.app2')
|
| 514 |
+
})
|
| 515 |
+
|
| 516 |
+
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
|
| 517 |
+
by loading ``'app2/index.html'`` the file from the second.
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
def __init__(
|
| 521 |
+
self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
|
| 522 |
+
) -> None:
|
| 523 |
+
self.mapping = mapping
|
| 524 |
+
self.delimiter = delimiter
|
| 525 |
+
|
| 526 |
+
def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
|
| 527 |
+
try:
|
| 528 |
+
prefix, name = template.split(self.delimiter, 1)
|
| 529 |
+
loader = self.mapping[prefix]
|
| 530 |
+
except (ValueError, KeyError) as e:
|
| 531 |
+
raise TemplateNotFound(template) from e
|
| 532 |
+
return loader, name
|
| 533 |
+
|
| 534 |
+
def get_source(
|
| 535 |
+
self, environment: "Environment", template: str
|
| 536 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 537 |
+
loader, name = self.get_loader(template)
|
| 538 |
+
try:
|
| 539 |
+
return loader.get_source(environment, name)
|
| 540 |
+
except TemplateNotFound as e:
|
| 541 |
+
# re-raise the exception with the correct filename here.
|
| 542 |
+
# (the one that includes the prefix)
|
| 543 |
+
raise TemplateNotFound(template) from e
|
| 544 |
+
|
| 545 |
+
@internalcode
|
| 546 |
+
def load(
|
| 547 |
+
self,
|
| 548 |
+
environment: "Environment",
|
| 549 |
+
name: str,
|
| 550 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 551 |
+
) -> "Template":
|
| 552 |
+
loader, local_name = self.get_loader(name)
|
| 553 |
+
try:
|
| 554 |
+
return loader.load(environment, local_name, globals)
|
| 555 |
+
except TemplateNotFound as e:
|
| 556 |
+
# re-raise the exception with the correct filename here.
|
| 557 |
+
# (the one that includes the prefix)
|
| 558 |
+
raise TemplateNotFound(name) from e
|
| 559 |
+
|
| 560 |
+
def list_templates(self) -> t.List[str]:
|
| 561 |
+
result = []
|
| 562 |
+
for prefix, loader in self.mapping.items():
|
| 563 |
+
for template in loader.list_templates():
|
| 564 |
+
result.append(prefix + self.delimiter + template)
|
| 565 |
+
return result
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class ChoiceLoader(BaseLoader):
|
| 569 |
+
"""This loader works like the `PrefixLoader` just that no prefix is
|
| 570 |
+
specified. If a template could not be found by one loader the next one
|
| 571 |
+
is tried.
|
| 572 |
+
|
| 573 |
+
>>> loader = ChoiceLoader([
|
| 574 |
+
... FileSystemLoader('/path/to/user/templates'),
|
| 575 |
+
... FileSystemLoader('/path/to/system/templates')
|
| 576 |
+
... ])
|
| 577 |
+
|
| 578 |
+
This is useful if you want to allow users to override builtin templates
|
| 579 |
+
from a different location.
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
|
| 583 |
+
self.loaders = loaders
|
| 584 |
+
|
| 585 |
+
def get_source(
|
| 586 |
+
self, environment: "Environment", template: str
|
| 587 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
| 588 |
+
for loader in self.loaders:
|
| 589 |
+
try:
|
| 590 |
+
return loader.get_source(environment, template)
|
| 591 |
+
except TemplateNotFound:
|
| 592 |
+
pass
|
| 593 |
+
raise TemplateNotFound(template)
|
| 594 |
+
|
| 595 |
+
@internalcode
|
| 596 |
+
def load(
|
| 597 |
+
self,
|
| 598 |
+
environment: "Environment",
|
| 599 |
+
name: str,
|
| 600 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 601 |
+
) -> "Template":
|
| 602 |
+
for loader in self.loaders:
|
| 603 |
+
try:
|
| 604 |
+
return loader.load(environment, name, globals)
|
| 605 |
+
except TemplateNotFound:
|
| 606 |
+
pass
|
| 607 |
+
raise TemplateNotFound(name)
|
| 608 |
+
|
| 609 |
+
def list_templates(self) -> t.List[str]:
|
| 610 |
+
found = set()
|
| 611 |
+
for loader in self.loaders:
|
| 612 |
+
found.update(loader.list_templates())
|
| 613 |
+
return sorted(found)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class _TemplateModule(ModuleType):
|
| 617 |
+
"""Like a normal module but with support for weak references"""
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class ModuleLoader(BaseLoader):
|
| 621 |
+
"""This loader loads templates from precompiled templates.
|
| 622 |
+
|
| 623 |
+
Example usage:
|
| 624 |
+
|
| 625 |
+
>>> loader = ModuleLoader('/path/to/compiled/templates')
|
| 626 |
+
|
| 627 |
+
Templates can be precompiled with :meth:`Environment.compile_templates`.
|
| 628 |
+
"""
|
| 629 |
+
|
| 630 |
+
has_source_access = False
|
| 631 |
+
|
| 632 |
+
def __init__(
|
| 633 |
+
self,
|
| 634 |
+
path: t.Union[
|
| 635 |
+
str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
|
| 636 |
+
],
|
| 637 |
+
) -> None:
|
| 638 |
+
package_name = f"_jinja2_module_templates_{id(self):x}"
|
| 639 |
+
|
| 640 |
+
# create a fake module that looks for the templates in the
|
| 641 |
+
# path given.
|
| 642 |
+
mod = _TemplateModule(package_name)
|
| 643 |
+
|
| 644 |
+
if not isinstance(path, abc.Iterable) or isinstance(path, str):
|
| 645 |
+
path = [path]
|
| 646 |
+
|
| 647 |
+
mod.__path__ = [os.fspath(p) for p in path]
|
| 648 |
+
|
| 649 |
+
sys.modules[package_name] = weakref.proxy(
|
| 650 |
+
mod, lambda x: sys.modules.pop(package_name, None)
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
# the only strong reference, the sys.modules entry is weak
|
| 654 |
+
# so that the garbage collector can remove it once the
|
| 655 |
+
# loader that created it goes out of business.
|
| 656 |
+
self.module = mod
|
| 657 |
+
self.package_name = package_name
|
| 658 |
+
|
| 659 |
+
@staticmethod
|
| 660 |
+
def get_template_key(name: str) -> str:
|
| 661 |
+
return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
|
| 662 |
+
|
| 663 |
+
@staticmethod
|
| 664 |
+
def get_module_filename(name: str) -> str:
|
| 665 |
+
return ModuleLoader.get_template_key(name) + ".py"
|
| 666 |
+
|
| 667 |
+
@internalcode
|
| 668 |
+
def load(
|
| 669 |
+
self,
|
| 670 |
+
environment: "Environment",
|
| 671 |
+
name: str,
|
| 672 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 673 |
+
) -> "Template":
|
| 674 |
+
key = self.get_template_key(name)
|
| 675 |
+
module = f"{self.package_name}.{key}"
|
| 676 |
+
mod = getattr(self.module, module, None)
|
| 677 |
+
|
| 678 |
+
if mod is None:
|
| 679 |
+
try:
|
| 680 |
+
mod = __import__(module, None, None, ["root"])
|
| 681 |
+
except ImportError as e:
|
| 682 |
+
raise TemplateNotFound(name) from e
|
| 683 |
+
|
| 684 |
+
# remove the entry from sys.modules, we only want the attribute
|
| 685 |
+
# on the module object we have stored on the loader.
|
| 686 |
+
sys.modules.pop(module, None)
|
| 687 |
+
|
| 688 |
+
if globals is None:
|
| 689 |
+
globals = {}
|
| 690 |
+
|
| 691 |
+
return environment.template_class.from_module_dict(
|
| 692 |
+
environment, mod.__dict__, globals
|
| 693 |
+
)
|
wemm/lib/python3.10/site-packages/jinja2/nodes.py
ADDED
|
@@ -0,0 +1,1206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ated by the parser for the compiler. Also provides
|
| 2 |
+
some node tree helper functions used by the parser and compiler in order
|
| 3 |
+
to normalize nodes.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import inspect
|
| 7 |
+
import operator
|
| 8 |
+
import typing as t
|
| 9 |
+
from collections import deque
|
| 10 |
+
|
| 11 |
+
from markupsafe import Markup
|
| 12 |
+
|
| 13 |
+
from .utils import _PassArg
|
| 14 |
+
|
| 15 |
+
if t.TYPE_CHECKING:
|
| 16 |
+
import typing_extensions as te
|
| 17 |
+
|
| 18 |
+
from .environment import Environment
|
| 19 |
+
|
| 20 |
+
_NodeBound = t.TypeVar("_NodeBound", bound="Node")
|
| 21 |
+
|
| 22 |
+
_binop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
|
| 23 |
+
"*": operator.mul,
|
| 24 |
+
"/": operator.truediv,
|
| 25 |
+
"//": operator.floordiv,
|
| 26 |
+
"**": operator.pow,
|
| 27 |
+
"%": operator.mod,
|
| 28 |
+
"+": operator.add,
|
| 29 |
+
"-": operator.sub,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
_uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] = {
|
| 33 |
+
"not": operator.not_,
|
| 34 |
+
"+": operator.pos,
|
| 35 |
+
"-": operator.neg,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
_cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
|
| 39 |
+
"eq": operator.eq,
|
| 40 |
+
"ne": operator.ne,
|
| 41 |
+
"gt": operator.gt,
|
| 42 |
+
"gteq": operator.ge,
|
| 43 |
+
"lt": operator.lt,
|
| 44 |
+
"lteq": operator.le,
|
| 45 |
+
"in": lambda a, b: a in b,
|
| 46 |
+
"notin": lambda a, b: a not in b,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Impossible(Exception):
|
| 51 |
+
"""Raised if the node could not perform a requested action."""
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class NodeType(type):
|
| 55 |
+
"""A metaclass for nodes that handles the field and attribute
|
| 56 |
+
inheritance. fields and attributes from the parent class are
|
| 57 |
+
automatically forwarded to the child."""
|
| 58 |
+
|
| 59 |
+
def __new__(mcs, name, bases, d): # type: ignore
|
| 60 |
+
for attr in "fields", "attributes":
|
| 61 |
+
storage: t.List[t.Tuple[str, ...]] = []
|
| 62 |
+
storage.extend(getattr(bases[0] if bases else object, attr, ()))
|
| 63 |
+
storage.extend(d.get(attr, ()))
|
| 64 |
+
assert len(bases) <= 1, "multiple inheritance not allowed"
|
| 65 |
+
assert len(storage) == len(set(storage)), "layout conflict"
|
| 66 |
+
d[attr] = tuple(storage)
|
| 67 |
+
d.setdefault("abstract", False)
|
| 68 |
+
return type.__new__(mcs, name, bases, d)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class EvalContext:
|
| 72 |
+
"""Holds evaluation time information. Custom attributes can be attached
|
| 73 |
+
to it in extensions.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self, environment: "Environment", template_name: t.Optional[str] = None
|
| 78 |
+
) -> None:
|
| 79 |
+
self.environment = environment
|
| 80 |
+
if callable(environment.autoescape):
|
| 81 |
+
self.autoescape = environment.autoescape(template_name)
|
| 82 |
+
else:
|
| 83 |
+
self.autoescape = environment.autoescape
|
| 84 |
+
self.volatile = False
|
| 85 |
+
|
| 86 |
+
def save(self) -> t.Mapping[str, t.Any]:
|
| 87 |
+
return self.__dict__.copy()
|
| 88 |
+
|
| 89 |
+
def revert(self, old: t.Mapping[str, t.Any]) -> None:
|
| 90 |
+
self.__dict__.clear()
|
| 91 |
+
self.__dict__.update(old)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:
|
| 95 |
+
if ctx is None:
|
| 96 |
+
if node.environment is None:
|
| 97 |
+
raise RuntimeError(
|
| 98 |
+
"if no eval context is passed, the node must have an"
|
| 99 |
+
" attached environment."
|
| 100 |
+
)
|
| 101 |
+
return EvalContext(node.environment)
|
| 102 |
+
return ctx
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class Node(metaclass=NodeType):
|
| 106 |
+
"""Baseclass for all Jinja nodes. There are a number of nodes available
|
| 107 |
+
of different types. There are four major types:
|
| 108 |
+
|
| 109 |
+
- :class:`Stmt`: statements
|
| 110 |
+
- :class:`Expr`: expressions
|
| 111 |
+
- :class:`Helper`: helper nodes
|
| 112 |
+
- :class:`Template`: the outermost wrapper node
|
| 113 |
+
|
| 114 |
+
All nodes have fields and attributes. Fields may be other nodes, lists,
|
| 115 |
+
or arbitrary values. Fields are passed to the constructor as regular
|
| 116 |
+
positional arguments, attributes as keyword arguments. Each node has
|
| 117 |
+
two attributes: `lineno` (the line number of the node) and `environment`.
|
| 118 |
+
The `environment` attribute is set at the end of the parsing process for
|
| 119 |
+
all nodes automatically.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
fields: t.Tuple[str, ...] = ()
|
| 123 |
+
attributes: t.Tuple[str, ...] = ("lineno", "environment")
|
| 124 |
+
abstract = True
|
| 125 |
+
|
| 126 |
+
lineno: int
|
| 127 |
+
environment: t.Optional["Environment"]
|
| 128 |
+
|
| 129 |
+
def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
|
| 130 |
+
if self.abstract:
|
| 131 |
+
raise TypeError("abstract nodes are not instantiable")
|
| 132 |
+
if fields:
|
| 133 |
+
if len(fields) != len(self.fields):
|
| 134 |
+
if not self.fields:
|
| 135 |
+
raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
|
| 136 |
+
raise TypeError(
|
| 137 |
+
f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
|
| 138 |
+
f" argument{'s' if len(self.fields) != 1 else ''}"
|
| 139 |
+
)
|
| 140 |
+
for name, arg in zip(self.fields, fields):
|
| 141 |
+
setattr(self, name, arg)
|
| 142 |
+
for attr in self.attributes:
|
| 143 |
+
setattr(self, attr, attributes.pop(attr, None))
|
| 144 |
+
if attributes:
|
| 145 |
+
raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
|
| 146 |
+
|
| 147 |
+
def iter_fields(
|
| 148 |
+
self,
|
| 149 |
+
exclude: t.Optional[t.Container[str]] = None,
|
| 150 |
+
only: t.Optional[t.Container[str]] = None,
|
| 151 |
+
) -> t.Iterator[t.Tuple[str, t.Any]]:
|
| 152 |
+
"""This method iterates over all fields that are defined and yields
|
| 153 |
+
``(key, value)`` tuples. Per default all fields are returned, but
|
| 154 |
+
it's possible to limit that to some fields by providing the `only`
|
| 155 |
+
parameter or to exclude some using the `exclude` parameter. Both
|
| 156 |
+
should be sets or tuples of field names.
|
| 157 |
+
"""
|
| 158 |
+
for name in self.fields:
|
| 159 |
+
if (
|
| 160 |
+
(exclude is None and only is None)
|
| 161 |
+
or (exclude is not None and name not in exclude)
|
| 162 |
+
or (only is not None and name in only)
|
| 163 |
+
):
|
| 164 |
+
try:
|
| 165 |
+
yield name, getattr(self, name)
|
| 166 |
+
except AttributeError:
|
| 167 |
+
pass
|
| 168 |
+
|
| 169 |
+
def iter_child_nodes(
|
| 170 |
+
self,
|
| 171 |
+
exclude: t.Optional[t.Container[str]] = None,
|
| 172 |
+
only: t.Optional[t.Container[str]] = None,
|
| 173 |
+
) -> t.Iterator["Node"]:
|
| 174 |
+
"""Iterates over all direct child nodes of the node. This iterates
|
| 175 |
+
over all fields and yields the values of they are nodes. If the value
|
| 176 |
+
of a field is a list all the nodes in that list are returned.
|
| 177 |
+
"""
|
| 178 |
+
for _, item in self.iter_fields(exclude, only):
|
| 179 |
+
if isinstance(item, list):
|
| 180 |
+
for n in item:
|
| 181 |
+
if isinstance(n, Node):
|
| 182 |
+
yield n
|
| 183 |
+
elif isinstance(item, Node):
|
| 184 |
+
yield item
|
| 185 |
+
|
| 186 |
+
def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
|
| 187 |
+
"""Find the first node of a given type. If no such node exists the
|
| 188 |
+
return value is `None`.
|
| 189 |
+
"""
|
| 190 |
+
for result in self.find_all(node_type):
|
| 191 |
+
return result
|
| 192 |
+
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
def find_all(
|
| 196 |
+
self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
|
| 197 |
+
) -> t.Iterator[_NodeBound]:
|
| 198 |
+
"""Find all the nodes of a given type. If the type is a tuple,
|
| 199 |
+
the check is performed for any of the tuple items.
|
| 200 |
+
"""
|
| 201 |
+
for child in self.iter_child_nodes():
|
| 202 |
+
if isinstance(child, node_type):
|
| 203 |
+
yield child # type: ignore
|
| 204 |
+
yield from child.find_all(node_type)
|
| 205 |
+
|
| 206 |
+
def set_ctx(self, ctx: str) -> "Node":
|
| 207 |
+
"""Reset the context of a node and all child nodes. Per default the
|
| 208 |
+
parser will all generate nodes that have a 'load' context as it's the
|
| 209 |
+
most common one. This method is used in the parser to set assignment
|
| 210 |
+
targets and other nodes to a store context.
|
| 211 |
+
"""
|
| 212 |
+
todo = deque([self])
|
| 213 |
+
while todo:
|
| 214 |
+
node = todo.popleft()
|
| 215 |
+
if "ctx" in node.fields:
|
| 216 |
+
node.ctx = ctx # type: ignore
|
| 217 |
+
todo.extend(node.iter_child_nodes())
|
| 218 |
+
return self
|
| 219 |
+
|
| 220 |
+
def set_lineno(self, lineno: int, override: bool = False) -> "Node":
|
| 221 |
+
"""Set the line numbers of the node and children."""
|
| 222 |
+
todo = deque([self])
|
| 223 |
+
while todo:
|
| 224 |
+
node = todo.popleft()
|
| 225 |
+
if "lineno" in node.attributes:
|
| 226 |
+
if node.lineno is None or override:
|
| 227 |
+
node.lineno = lineno
|
| 228 |
+
todo.extend(node.iter_child_nodes())
|
| 229 |
+
return self
|
| 230 |
+
|
| 231 |
+
def set_environment(self, environment: "Environment") -> "Node":
|
| 232 |
+
"""Set the environment for all nodes."""
|
| 233 |
+
todo = deque([self])
|
| 234 |
+
while todo:
|
| 235 |
+
node = todo.popleft()
|
| 236 |
+
node.environment = environment
|
| 237 |
+
todo.extend(node.iter_child_nodes())
|
| 238 |
+
return self
|
| 239 |
+
|
| 240 |
+
def __eq__(self, other: t.Any) -> bool:
|
| 241 |
+
if type(self) is not type(other):
|
| 242 |
+
return NotImplemented
|
| 243 |
+
|
| 244 |
+
return tuple(self.iter_fields()) == tuple(other.iter_fields())
|
| 245 |
+
|
| 246 |
+
__hash__ = object.__hash__
|
| 247 |
+
|
| 248 |
+
def __repr__(self) -> str:
|
| 249 |
+
args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
|
| 250 |
+
return f"{type(self).__name__}({args_str})"
|
| 251 |
+
|
| 252 |
+
def dump(self) -> str:
|
| 253 |
+
def _dump(node: t.Union[Node, t.Any]) -> None:
|
| 254 |
+
if not isinstance(node, Node):
|
| 255 |
+
buf.append(repr(node))
|
| 256 |
+
return
|
| 257 |
+
|
| 258 |
+
buf.append(f"nodes.{type(node).__name__}(")
|
| 259 |
+
if not node.fields:
|
| 260 |
+
buf.append(")")
|
| 261 |
+
return
|
| 262 |
+
for idx, field in enumerate(node.fields):
|
| 263 |
+
if idx:
|
| 264 |
+
buf.append(", ")
|
| 265 |
+
value = getattr(node, field)
|
| 266 |
+
if isinstance(value, list):
|
| 267 |
+
buf.append("[")
|
| 268 |
+
for idx, item in enumerate(value):
|
| 269 |
+
if idx:
|
| 270 |
+
buf.append(", ")
|
| 271 |
+
_dump(item)
|
| 272 |
+
buf.append("]")
|
| 273 |
+
else:
|
| 274 |
+
_dump(value)
|
| 275 |
+
buf.append(")")
|
| 276 |
+
|
| 277 |
+
buf: t.List[str] = []
|
| 278 |
+
_dump(self)
|
| 279 |
+
return "".join(buf)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class Stmt(Node):
|
| 283 |
+
"""Base node for all statements."""
|
| 284 |
+
|
| 285 |
+
abstract = True
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class Helper(Node):
|
| 289 |
+
"""Nodes that exist in a specific context only."""
|
| 290 |
+
|
| 291 |
+
abstract = True
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class Template(Node):
|
| 295 |
+
"""Node that represents a template. This must be the outermost node that
|
| 296 |
+
is passed to the compiler.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
fields = ("body",)
|
| 300 |
+
body: t.List[Node]
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class Output(Stmt):
|
| 304 |
+
"""A node that holds multiple expressions which are then printed out.
|
| 305 |
+
This is used both for the `print` statement and the regular template data.
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
fields = ("nodes",)
|
| 309 |
+
nodes: t.List["Expr"]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class Extends(Stmt):
|
| 313 |
+
"""Represents an extends statement."""
|
| 314 |
+
|
| 315 |
+
fields = ("template",)
|
| 316 |
+
template: "Expr"
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class For(Stmt):
|
| 320 |
+
"""The for loop. `target` is the target for the iteration (usually a
|
| 321 |
+
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
|
| 322 |
+
of nodes that are used as loop-body, and `else_` a list of nodes for the
|
| 323 |
+
`else` block. If no else node exists it has to be an empty list.
|
| 324 |
+
|
| 325 |
+
For filtered nodes an expression can be stored as `test`, otherwise `None`.
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
fields = ("target", "iter", "body", "else_", "test", "recursive")
|
| 329 |
+
target: Node
|
| 330 |
+
iter: Node
|
| 331 |
+
body: t.List[Node]
|
| 332 |
+
else_: t.List[Node]
|
| 333 |
+
test: t.Optional[Node]
|
| 334 |
+
recursive: bool
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class If(Stmt):
|
| 338 |
+
"""If `test` is true, `body` is rendered, else `else_`."""
|
| 339 |
+
|
| 340 |
+
fields = ("test", "body", "elif_", "else_")
|
| 341 |
+
test: Node
|
| 342 |
+
body: t.List[Node]
|
| 343 |
+
elif_: t.List["If"]
|
| 344 |
+
else_: t.List[Node]
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class Macro(Stmt):
|
| 348 |
+
"""A macro definition. `name` is the name of the macro, `args` a list of
|
| 349 |
+
arguments and `defaults` a list of defaults if there are any. `body` is
|
| 350 |
+
a list of nodes for the macro body.
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
fields = ("name", "args", "defaults", "body")
|
| 354 |
+
name: str
|
| 355 |
+
args: t.List["Name"]
|
| 356 |
+
defaults: t.List["Expr"]
|
| 357 |
+
body: t.List[Node]
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class CallBlock(Stmt):
|
| 361 |
+
"""Like a macro without a name but a call instead. `call` is called with
|
| 362 |
+
the unnamed macro as `caller` argument this node holds.
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
fields = ("call", "args", "defaults", "body")
|
| 366 |
+
call: "Call"
|
| 367 |
+
args: t.List["Name"]
|
| 368 |
+
defaults: t.List["Expr"]
|
| 369 |
+
body: t.List[Node]
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class FilterBlock(Stmt):
|
| 373 |
+
"""Node for filter sections."""
|
| 374 |
+
|
| 375 |
+
fields = ("body", "filter")
|
| 376 |
+
body: t.List[Node]
|
| 377 |
+
filter: "Filter"
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class With(Stmt):
|
| 381 |
+
"""Specific node for with statements. In older versions of Jinja the
|
| 382 |
+
with statement was implemented on the base of the `Scope` node instead.
|
| 383 |
+
|
| 384 |
+
.. versionadded:: 2.9.3
|
| 385 |
+
"""
|
| 386 |
+
|
| 387 |
+
fields = ("targets", "values", "body")
|
| 388 |
+
targets: t.List["Expr"]
|
| 389 |
+
values: t.List["Expr"]
|
| 390 |
+
body: t.List[Node]
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class Block(Stmt):
|
| 394 |
+
"""A node that represents a block.
|
| 395 |
+
|
| 396 |
+
.. versionchanged:: 3.0.0
|
| 397 |
+
the `required` field was added.
|
| 398 |
+
"""
|
| 399 |
+
|
| 400 |
+
fields = ("name", "body", "scoped", "required")
|
| 401 |
+
name: str
|
| 402 |
+
body: t.List[Node]
|
| 403 |
+
scoped: bool
|
| 404 |
+
required: bool
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class Include(Stmt):
|
| 408 |
+
"""A node that represents the include tag."""
|
| 409 |
+
|
| 410 |
+
fields = ("template", "with_context", "ignore_missing")
|
| 411 |
+
template: "Expr"
|
| 412 |
+
with_context: bool
|
| 413 |
+
ignore_missing: bool
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
class Import(Stmt):
|
| 417 |
+
"""A node that represents the import tag."""
|
| 418 |
+
|
| 419 |
+
fields = ("template", "target", "with_context")
|
| 420 |
+
template: "Expr"
|
| 421 |
+
target: str
|
| 422 |
+
with_context: bool
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class FromImport(Stmt):
|
| 426 |
+
"""A node that represents the from import tag. It's important to not
|
| 427 |
+
pass unsafe names to the name attribute. The compiler translates the
|
| 428 |
+
attribute lookups directly into getattr calls and does *not* use the
|
| 429 |
+
subscript callback of the interface. As exported variables may not
|
| 430 |
+
start with double underscores (which the parser asserts) this is not a
|
| 431 |
+
problem for regular Jinja code, but if this node is used in an extension
|
| 432 |
+
extra care must be taken.
|
| 433 |
+
|
| 434 |
+
The list of names may contain tuples if aliases are wanted.
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
fields = ("template", "names", "with_context")
|
| 438 |
+
template: "Expr"
|
| 439 |
+
names: t.List[t.Union[str, t.Tuple[str, str]]]
|
| 440 |
+
with_context: bool
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class ExprStmt(Stmt):
|
| 444 |
+
"""A statement that evaluates an expression and discards the result."""
|
| 445 |
+
|
| 446 |
+
fields = ("node",)
|
| 447 |
+
node: Node
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class Assign(Stmt):
|
| 451 |
+
"""Assigns an expression to a target."""
|
| 452 |
+
|
| 453 |
+
fields = ("target", "node")
|
| 454 |
+
target: "Expr"
|
| 455 |
+
node: Node
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class AssignBlock(Stmt):
|
| 459 |
+
"""Assigns a block to a target."""
|
| 460 |
+
|
| 461 |
+
fields = ("target", "filter", "body")
|
| 462 |
+
target: "Expr"
|
| 463 |
+
filter: t.Optional["Filter"]
|
| 464 |
+
body: t.List[Node]
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Expr(Node):
|
| 468 |
+
"""Baseclass for all expressions."""
|
| 469 |
+
|
| 470 |
+
abstract = True
|
| 471 |
+
|
| 472 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 473 |
+
"""Return the value of the expression as constant or raise
|
| 474 |
+
:exc:`Impossible` if this was not possible.
|
| 475 |
+
|
| 476 |
+
An :class:`EvalContext` can be provided, if none is given
|
| 477 |
+
a default context is created which requires the nodes to have
|
| 478 |
+
an attached environment.
|
| 479 |
+
|
| 480 |
+
.. versionchanged:: 2.4
|
| 481 |
+
the `eval_ctx` parameter was added.
|
| 482 |
+
"""
|
| 483 |
+
raise Impossible()
|
| 484 |
+
|
| 485 |
+
def can_assign(self) -> bool:
|
| 486 |
+
"""Check if it's possible to assign something to this node."""
|
| 487 |
+
return False
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class BinExpr(Expr):
|
| 491 |
+
"""Baseclass for all binary expressions."""
|
| 492 |
+
|
| 493 |
+
fields = ("left", "right")
|
| 494 |
+
left: Expr
|
| 495 |
+
right: Expr
|
| 496 |
+
operator: str
|
| 497 |
+
abstract = True
|
| 498 |
+
|
| 499 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 500 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 501 |
+
|
| 502 |
+
# intercepted operators cannot be folded at compile time
|
| 503 |
+
if (
|
| 504 |
+
eval_ctx.environment.sandboxed
|
| 505 |
+
and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
|
| 506 |
+
):
|
| 507 |
+
raise Impossible()
|
| 508 |
+
f = _binop_to_func[self.operator]
|
| 509 |
+
try:
|
| 510 |
+
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
|
| 511 |
+
except Exception as e:
|
| 512 |
+
raise Impossible() from e
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class UnaryExpr(Expr):
|
| 516 |
+
"""Baseclass for all unary expressions."""
|
| 517 |
+
|
| 518 |
+
fields = ("node",)
|
| 519 |
+
node: Expr
|
| 520 |
+
operator: str
|
| 521 |
+
abstract = True
|
| 522 |
+
|
| 523 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 524 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 525 |
+
|
| 526 |
+
# intercepted operators cannot be folded at compile time
|
| 527 |
+
if (
|
| 528 |
+
eval_ctx.environment.sandboxed
|
| 529 |
+
and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
|
| 530 |
+
):
|
| 531 |
+
raise Impossible()
|
| 532 |
+
f = _uaop_to_func[self.operator]
|
| 533 |
+
try:
|
| 534 |
+
return f(self.node.as_const(eval_ctx))
|
| 535 |
+
except Exception as e:
|
| 536 |
+
raise Impossible() from e
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
class Name(Expr):
|
| 540 |
+
"""Looks up a name or stores a value in a name.
|
| 541 |
+
The `ctx` of the node can be one of the following values:
|
| 542 |
+
|
| 543 |
+
- `store`: store a value in the name
|
| 544 |
+
- `load`: load that name
|
| 545 |
+
- `param`: like `store` but if the name was defined as function parameter.
|
| 546 |
+
"""
|
| 547 |
+
|
| 548 |
+
fields = ("name", "ctx")
|
| 549 |
+
name: str
|
| 550 |
+
ctx: str
|
| 551 |
+
|
| 552 |
+
def can_assign(self) -> bool:
|
| 553 |
+
return self.name not in {"true", "false", "none", "True", "False", "None"}
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class NSRef(Expr):
|
| 557 |
+
"""Reference to a namespace value assignment"""
|
| 558 |
+
|
| 559 |
+
fields = ("name", "attr")
|
| 560 |
+
name: str
|
| 561 |
+
attr: str
|
| 562 |
+
|
| 563 |
+
def can_assign(self) -> bool:
|
| 564 |
+
# We don't need any special checks here; NSRef assignments have a
|
| 565 |
+
# runtime check to ensure the target is a namespace object which will
|
| 566 |
+
# have been checked already as it is created using a normal assignment
|
| 567 |
+
# which goes through a `Name` node.
|
| 568 |
+
return True
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
class Literal(Expr):
|
| 572 |
+
"""Baseclass for literals."""
|
| 573 |
+
|
| 574 |
+
abstract = True
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class Const(Literal):
|
| 578 |
+
"""All constant values. The parser will return this node for simple
|
| 579 |
+
constants such as ``42`` or ``"foo"`` but it can be used to store more
|
| 580 |
+
complex values such as lists too. Only constants with a safe
|
| 581 |
+
representation (objects where ``eval(repr(x)) == x`` is true).
|
| 582 |
+
"""
|
| 583 |
+
|
| 584 |
+
fields = ("value",)
|
| 585 |
+
value: t.Any
|
| 586 |
+
|
| 587 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 588 |
+
return self.value
|
| 589 |
+
|
| 590 |
+
@classmethod
|
| 591 |
+
def from_untrusted(
|
| 592 |
+
cls,
|
| 593 |
+
value: t.Any,
|
| 594 |
+
lineno: t.Optional[int] = None,
|
| 595 |
+
environment: "t.Optional[Environment]" = None,
|
| 596 |
+
) -> "Const":
|
| 597 |
+
"""Return a const object if the value is representable as
|
| 598 |
+
constant value in the generated code, otherwise it will raise
|
| 599 |
+
an `Impossible` exception.
|
| 600 |
+
"""
|
| 601 |
+
from .compiler import has_safe_repr
|
| 602 |
+
|
| 603 |
+
if not has_safe_repr(value):
|
| 604 |
+
raise Impossible()
|
| 605 |
+
return cls(value, lineno=lineno, environment=environment)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class TemplateData(Literal):
|
| 609 |
+
"""A constant template string."""
|
| 610 |
+
|
| 611 |
+
fields = ("data",)
|
| 612 |
+
data: str
|
| 613 |
+
|
| 614 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
|
| 615 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 616 |
+
if eval_ctx.volatile:
|
| 617 |
+
raise Impossible()
|
| 618 |
+
if eval_ctx.autoescape:
|
| 619 |
+
return Markup(self.data)
|
| 620 |
+
return self.data
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class Tuple(Literal):
|
| 624 |
+
"""For loop unpacking and some other things like multiple arguments
|
| 625 |
+
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
|
| 626 |
+
is used for loading the names or storing.
|
| 627 |
+
"""
|
| 628 |
+
|
| 629 |
+
fields = ("items", "ctx")
|
| 630 |
+
items: t.List[Expr]
|
| 631 |
+
ctx: str
|
| 632 |
+
|
| 633 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:
|
| 634 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 635 |
+
return tuple(x.as_const(eval_ctx) for x in self.items)
|
| 636 |
+
|
| 637 |
+
def can_assign(self) -> bool:
|
| 638 |
+
for item in self.items:
|
| 639 |
+
if not item.can_assign():
|
| 640 |
+
return False
|
| 641 |
+
return True
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
class List(Literal):
|
| 645 |
+
"""Any list literal such as ``[1, 2, 3]``"""
|
| 646 |
+
|
| 647 |
+
fields = ("items",)
|
| 648 |
+
items: t.List[Expr]
|
| 649 |
+
|
| 650 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:
|
| 651 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 652 |
+
return [x.as_const(eval_ctx) for x in self.items]
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class Dict(Literal):
|
| 656 |
+
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
|
| 657 |
+
:class:`Pair` nodes.
|
| 658 |
+
"""
|
| 659 |
+
|
| 660 |
+
fields = ("items",)
|
| 661 |
+
items: t.List["Pair"]
|
| 662 |
+
|
| 663 |
+
def as_const(
|
| 664 |
+
self, eval_ctx: t.Optional[EvalContext] = None
|
| 665 |
+
) -> t.Dict[t.Any, t.Any]:
|
| 666 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 667 |
+
return dict(x.as_const(eval_ctx) for x in self.items)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
class Pair(Helper):
|
| 671 |
+
"""A key, value pair for dicts."""
|
| 672 |
+
|
| 673 |
+
fields = ("key", "value")
|
| 674 |
+
key: Expr
|
| 675 |
+
value: Expr
|
| 676 |
+
|
| 677 |
+
def as_const(
|
| 678 |
+
self, eval_ctx: t.Optional[EvalContext] = None
|
| 679 |
+
) -> t.Tuple[t.Any, t.Any]:
|
| 680 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 681 |
+
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
class Keyword(Helper):
|
| 685 |
+
"""A key, value pair for keyword arguments where key is a string."""
|
| 686 |
+
|
| 687 |
+
fields = ("key", "value")
|
| 688 |
+
key: str
|
| 689 |
+
value: Expr
|
| 690 |
+
|
| 691 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
|
| 692 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 693 |
+
return self.key, self.value.as_const(eval_ctx)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class CondExpr(Expr):
|
| 697 |
+
"""A conditional expression (inline if expression). (``{{
|
| 698 |
+
foo if bar else baz }}``)
|
| 699 |
+
"""
|
| 700 |
+
|
| 701 |
+
fields = ("test", "expr1", "expr2")
|
| 702 |
+
test: Expr
|
| 703 |
+
expr1: Expr
|
| 704 |
+
expr2: t.Optional[Expr]
|
| 705 |
+
|
| 706 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 707 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 708 |
+
if self.test.as_const(eval_ctx):
|
| 709 |
+
return self.expr1.as_const(eval_ctx)
|
| 710 |
+
|
| 711 |
+
# if we evaluate to an undefined object, we better do that at runtime
|
| 712 |
+
if self.expr2 is None:
|
| 713 |
+
raise Impossible()
|
| 714 |
+
|
| 715 |
+
return self.expr2.as_const(eval_ctx)
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def args_as_const(
|
| 719 |
+
node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
|
| 720 |
+
) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
|
| 721 |
+
args = [x.as_const(eval_ctx) for x in node.args]
|
| 722 |
+
kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
|
| 723 |
+
|
| 724 |
+
if node.dyn_args is not None:
|
| 725 |
+
try:
|
| 726 |
+
args.extend(node.dyn_args.as_const(eval_ctx))
|
| 727 |
+
except Exception as e:
|
| 728 |
+
raise Impossible() from e
|
| 729 |
+
|
| 730 |
+
if node.dyn_kwargs is not None:
|
| 731 |
+
try:
|
| 732 |
+
kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
|
| 733 |
+
except Exception as e:
|
| 734 |
+
raise Impossible() from e
|
| 735 |
+
|
| 736 |
+
return args, kwargs
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
class _FilterTestCommon(Expr):
|
| 740 |
+
fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
|
| 741 |
+
node: Expr
|
| 742 |
+
name: str
|
| 743 |
+
args: t.List[Expr]
|
| 744 |
+
kwargs: t.List[Pair]
|
| 745 |
+
dyn_args: t.Optional[Expr]
|
| 746 |
+
dyn_kwargs: t.Optional[Expr]
|
| 747 |
+
abstract = True
|
| 748 |
+
_is_filter = True
|
| 749 |
+
|
| 750 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 751 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 752 |
+
|
| 753 |
+
if eval_ctx.volatile:
|
| 754 |
+
raise Impossible()
|
| 755 |
+
|
| 756 |
+
if self._is_filter:
|
| 757 |
+
env_map = eval_ctx.environment.filters
|
| 758 |
+
else:
|
| 759 |
+
env_map = eval_ctx.environment.tests
|
| 760 |
+
|
| 761 |
+
func = env_map.get(self.name)
|
| 762 |
+
pass_arg = _PassArg.from_obj(func) # type: ignore
|
| 763 |
+
|
| 764 |
+
if func is None or pass_arg is _PassArg.context:
|
| 765 |
+
raise Impossible()
|
| 766 |
+
|
| 767 |
+
if eval_ctx.environment.is_async and (
|
| 768 |
+
getattr(func, "jinja_async_variant", False) is True
|
| 769 |
+
or inspect.iscoroutinefunction(func)
|
| 770 |
+
):
|
| 771 |
+
raise Impossible()
|
| 772 |
+
|
| 773 |
+
args, kwargs = args_as_const(self, eval_ctx)
|
| 774 |
+
args.insert(0, self.node.as_const(eval_ctx))
|
| 775 |
+
|
| 776 |
+
if pass_arg is _PassArg.eval_context:
|
| 777 |
+
args.insert(0, eval_ctx)
|
| 778 |
+
elif pass_arg is _PassArg.environment:
|
| 779 |
+
args.insert(0, eval_ctx.environment)
|
| 780 |
+
|
| 781 |
+
try:
|
| 782 |
+
return func(*args, **kwargs)
|
| 783 |
+
except Exception as e:
|
| 784 |
+
raise Impossible() from e
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
class Filter(_FilterTestCommon):
|
| 788 |
+
"""Apply a filter to an expression. ``name`` is the name of the
|
| 789 |
+
filter, the other fields are the same as :class:`Call`.
|
| 790 |
+
|
| 791 |
+
If ``node`` is ``None``, the filter is being used in a filter block
|
| 792 |
+
and is applied to the content of the block.
|
| 793 |
+
"""
|
| 794 |
+
|
| 795 |
+
node: t.Optional[Expr] # type: ignore
|
| 796 |
+
|
| 797 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 798 |
+
if self.node is None:
|
| 799 |
+
raise Impossible()
|
| 800 |
+
|
| 801 |
+
return super().as_const(eval_ctx=eval_ctx)
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
class Test(_FilterTestCommon):
|
| 805 |
+
"""Apply a test to an expression. ``name`` is the name of the test,
|
| 806 |
+
the other field are the same as :class:`Call`.
|
| 807 |
+
|
| 808 |
+
.. versionchanged:: 3.0
|
| 809 |
+
``as_const`` shares the same logic for filters and tests. Tests
|
| 810 |
+
check for volatile, async, and ``@pass_context`` etc.
|
| 811 |
+
decorators.
|
| 812 |
+
"""
|
| 813 |
+
|
| 814 |
+
_is_filter = False
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
class Call(Expr):
|
| 818 |
+
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
|
| 819 |
+
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
|
| 820 |
+
and `dyn_kwargs` has to be either `None` or a node that is used as
|
| 821 |
+
node for dynamic positional (``*args``) or keyword (``**kwargs``)
|
| 822 |
+
arguments.
|
| 823 |
+
"""
|
| 824 |
+
|
| 825 |
+
fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")
|
| 826 |
+
node: Expr
|
| 827 |
+
args: t.List[Expr]
|
| 828 |
+
kwargs: t.List[Keyword]
|
| 829 |
+
dyn_args: t.Optional[Expr]
|
| 830 |
+
dyn_kwargs: t.Optional[Expr]
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
class Getitem(Expr):
|
| 834 |
+
"""Get an attribute or item from an expression and prefer the item."""
|
| 835 |
+
|
| 836 |
+
fields = ("node", "arg", "ctx")
|
| 837 |
+
node: Expr
|
| 838 |
+
arg: Expr
|
| 839 |
+
ctx: str
|
| 840 |
+
|
| 841 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 842 |
+
if self.ctx != "load":
|
| 843 |
+
raise Impossible()
|
| 844 |
+
|
| 845 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 846 |
+
|
| 847 |
+
try:
|
| 848 |
+
return eval_ctx.environment.getitem(
|
| 849 |
+
self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
|
| 850 |
+
)
|
| 851 |
+
except Exception as e:
|
| 852 |
+
raise Impossible() from e
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
class Getattr(Expr):
|
| 856 |
+
"""Get an attribute or item from an expression that is a ascii-only
|
| 857 |
+
bytestring and prefer the attribute.
|
| 858 |
+
"""
|
| 859 |
+
|
| 860 |
+
fields = ("node", "attr", "ctx")
|
| 861 |
+
node: Expr
|
| 862 |
+
attr: str
|
| 863 |
+
ctx: str
|
| 864 |
+
|
| 865 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 866 |
+
if self.ctx != "load":
|
| 867 |
+
raise Impossible()
|
| 868 |
+
|
| 869 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 870 |
+
|
| 871 |
+
try:
|
| 872 |
+
return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
|
| 873 |
+
except Exception as e:
|
| 874 |
+
raise Impossible() from e
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class Slice(Expr):
|
| 878 |
+
"""Represents a slice object. This must only be used as argument for
|
| 879 |
+
:class:`Subscript`.
|
| 880 |
+
"""
|
| 881 |
+
|
| 882 |
+
fields = ("start", "stop", "step")
|
| 883 |
+
start: t.Optional[Expr]
|
| 884 |
+
stop: t.Optional[Expr]
|
| 885 |
+
step: t.Optional[Expr]
|
| 886 |
+
|
| 887 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
|
| 888 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 889 |
+
|
| 890 |
+
def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
|
| 891 |
+
if obj is None:
|
| 892 |
+
return None
|
| 893 |
+
return obj.as_const(eval_ctx)
|
| 894 |
+
|
| 895 |
+
return slice(const(self.start), const(self.stop), const(self.step))
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class Concat(Expr):
|
| 899 |
+
"""Concatenates the list of expressions provided after converting
|
| 900 |
+
them to strings.
|
| 901 |
+
"""
|
| 902 |
+
|
| 903 |
+
fields = ("nodes",)
|
| 904 |
+
nodes: t.List[Expr]
|
| 905 |
+
|
| 906 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
|
| 907 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 908 |
+
return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
class Compare(Expr):
|
| 912 |
+
"""Compares an expression with some other expressions. `ops` must be a
|
| 913 |
+
list of :class:`Operand`\\s.
|
| 914 |
+
"""
|
| 915 |
+
|
| 916 |
+
fields = ("expr", "ops")
|
| 917 |
+
expr: Expr
|
| 918 |
+
ops: t.List["Operand"]
|
| 919 |
+
|
| 920 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 921 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 922 |
+
result = value = self.expr.as_const(eval_ctx)
|
| 923 |
+
|
| 924 |
+
try:
|
| 925 |
+
for op in self.ops:
|
| 926 |
+
new_value = op.expr.as_const(eval_ctx)
|
| 927 |
+
result = _cmpop_to_func[op.op](value, new_value)
|
| 928 |
+
|
| 929 |
+
if not result:
|
| 930 |
+
return False
|
| 931 |
+
|
| 932 |
+
value = new_value
|
| 933 |
+
except Exception as e:
|
| 934 |
+
raise Impossible() from e
|
| 935 |
+
|
| 936 |
+
return result
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
class Operand(Helper):
|
| 940 |
+
"""Holds an operator and an expression."""
|
| 941 |
+
|
| 942 |
+
fields = ("op", "expr")
|
| 943 |
+
op: str
|
| 944 |
+
expr: Expr
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
class Mul(BinExpr):
|
| 948 |
+
"""Multiplies the left with the right node."""
|
| 949 |
+
|
| 950 |
+
operator = "*"
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class Div(BinExpr):
|
| 954 |
+
"""Divides the left by the right node."""
|
| 955 |
+
|
| 956 |
+
operator = "/"
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
class FloorDiv(BinExpr):
|
| 960 |
+
"""Divides the left by the right node and converts the
|
| 961 |
+
result into an integer by truncating.
|
| 962 |
+
"""
|
| 963 |
+
|
| 964 |
+
operator = "//"
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
class Add(BinExpr):
|
| 968 |
+
"""Add the left to the right node."""
|
| 969 |
+
|
| 970 |
+
operator = "+"
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
class Sub(BinExpr):
|
| 974 |
+
"""Subtract the right from the left node."""
|
| 975 |
+
|
| 976 |
+
operator = "-"
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
class Mod(BinExpr):
|
| 980 |
+
"""Left modulo right."""
|
| 981 |
+
|
| 982 |
+
operator = "%"
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
class Pow(BinExpr):
|
| 986 |
+
"""Left to the power of right."""
|
| 987 |
+
|
| 988 |
+
operator = "**"
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
class And(BinExpr):
|
| 992 |
+
"""Short circuited AND."""
|
| 993 |
+
|
| 994 |
+
operator = "and"
|
| 995 |
+
|
| 996 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 997 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 998 |
+
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
class Or(BinExpr):
|
| 1002 |
+
"""Short circuited OR."""
|
| 1003 |
+
|
| 1004 |
+
operator = "or"
|
| 1005 |
+
|
| 1006 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
| 1007 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 1008 |
+
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
class Not(UnaryExpr):
|
| 1012 |
+
"""Negate the expression."""
|
| 1013 |
+
|
| 1014 |
+
operator = "not"
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
class Neg(UnaryExpr):
|
| 1018 |
+
"""Make the expression negative."""
|
| 1019 |
+
|
| 1020 |
+
operator = "-"
|
| 1021 |
+
|
| 1022 |
+
|
| 1023 |
+
class Pos(UnaryExpr):
|
| 1024 |
+
"""Make the expression positive (noop for most expressions)"""
|
| 1025 |
+
|
| 1026 |
+
operator = "+"
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
# Helpers for extensions
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
class EnvironmentAttribute(Expr):
|
| 1033 |
+
"""Loads an attribute from the environment object. This is useful for
|
| 1034 |
+
extensions that want to call a callback stored on the environment.
|
| 1035 |
+
"""
|
| 1036 |
+
|
| 1037 |
+
fields = ("name",)
|
| 1038 |
+
name: str
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
class ExtensionAttribute(Expr):
|
| 1042 |
+
"""Returns the attribute of an extension bound to the environment.
|
| 1043 |
+
The identifier is the identifier of the :class:`Extension`.
|
| 1044 |
+
|
| 1045 |
+
This node is usually constructed by calling the
|
| 1046 |
+
:meth:`~jinja2.ext.Extension.attr` method on an extension.
|
| 1047 |
+
"""
|
| 1048 |
+
|
| 1049 |
+
fields = ("identifier", "name")
|
| 1050 |
+
identifier: str
|
| 1051 |
+
name: str
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
class ImportedName(Expr):
|
| 1055 |
+
"""If created with an import name the import name is returned on node
|
| 1056 |
+
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
|
| 1057 |
+
function from the cgi module on evaluation. Imports are optimized by the
|
| 1058 |
+
compiler so there is no need to assign them to local variables.
|
| 1059 |
+
"""
|
| 1060 |
+
|
| 1061 |
+
fields = ("importname",)
|
| 1062 |
+
importname: str
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
class InternalName(Expr):
|
| 1066 |
+
"""An internal name in the compiler. You cannot create these nodes
|
| 1067 |
+
yourself but the parser provides a
|
| 1068 |
+
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
|
| 1069 |
+
a new identifier for you. This identifier is not available from the
|
| 1070 |
+
template and is not treated specially by the compiler.
|
| 1071 |
+
"""
|
| 1072 |
+
|
| 1073 |
+
fields = ("name",)
|
| 1074 |
+
name: str
|
| 1075 |
+
|
| 1076 |
+
def __init__(self) -> None:
|
| 1077 |
+
raise TypeError(
|
| 1078 |
+
"Can't create internal names. Use the "
|
| 1079 |
+
"`free_identifier` method on a parser."
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
|
| 1083 |
+
class MarkSafe(Expr):
|
| 1084 |
+
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
|
| 1085 |
+
|
| 1086 |
+
fields = ("expr",)
|
| 1087 |
+
expr: Expr
|
| 1088 |
+
|
| 1089 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
|
| 1090 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 1091 |
+
return Markup(self.expr.as_const(eval_ctx))
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
class MarkSafeIfAutoescape(Expr):
|
| 1095 |
+
"""Mark the wrapped expression as safe (wrap it as `Markup`) but
|
| 1096 |
+
only if autoescaping is active.
|
| 1097 |
+
|
| 1098 |
+
.. versionadded:: 2.5
|
| 1099 |
+
"""
|
| 1100 |
+
|
| 1101 |
+
fields = ("expr",)
|
| 1102 |
+
expr: Expr
|
| 1103 |
+
|
| 1104 |
+
def as_const(
|
| 1105 |
+
self, eval_ctx: t.Optional[EvalContext] = None
|
| 1106 |
+
) -> t.Union[Markup, t.Any]:
|
| 1107 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
| 1108 |
+
if eval_ctx.volatile:
|
| 1109 |
+
raise Impossible()
|
| 1110 |
+
expr = self.expr.as_const(eval_ctx)
|
| 1111 |
+
if eval_ctx.autoescape:
|
| 1112 |
+
return Markup(expr)
|
| 1113 |
+
return expr
|
| 1114 |
+
|
| 1115 |
+
|
| 1116 |
+
class ContextReference(Expr):
|
| 1117 |
+
"""Returns the current template context. It can be used like a
|
| 1118 |
+
:class:`Name` node, with a ``'load'`` ctx and will return the
|
| 1119 |
+
current :class:`~jinja2.runtime.Context` object.
|
| 1120 |
+
|
| 1121 |
+
Here an example that assigns the current template name to a
|
| 1122 |
+
variable named `foo`::
|
| 1123 |
+
|
| 1124 |
+
Assign(Name('foo', ctx='store'),
|
| 1125 |
+
Getattr(ContextReference(), 'name'))
|
| 1126 |
+
|
| 1127 |
+
This is basically equivalent to using the
|
| 1128 |
+
:func:`~jinja2.pass_context` decorator when using the high-level
|
| 1129 |
+
API, which causes a reference to the context to be passed as the
|
| 1130 |
+
first argument to a function.
|
| 1131 |
+
"""
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
class DerivedContextReference(Expr):
|
| 1135 |
+
"""Return the current template context including locals. Behaves
|
| 1136 |
+
exactly like :class:`ContextReference`, but includes local
|
| 1137 |
+
variables, such as from a ``for`` loop.
|
| 1138 |
+
|
| 1139 |
+
.. versionadded:: 2.11
|
| 1140 |
+
"""
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
class Continue(Stmt):
|
| 1144 |
+
"""Continue a loop."""
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
class Break(Stmt):
|
| 1148 |
+
"""Break a loop."""
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
class Scope(Stmt):
|
| 1152 |
+
"""An artificial scope."""
|
| 1153 |
+
|
| 1154 |
+
fields = ("body",)
|
| 1155 |
+
body: t.List[Node]
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
class OverlayScope(Stmt):
|
| 1159 |
+
"""An overlay scope for extensions. This is a largely unoptimized scope
|
| 1160 |
+
that however can be used to introduce completely arbitrary variables into
|
| 1161 |
+
a sub scope from a dictionary or dictionary like object. The `context`
|
| 1162 |
+
field has to evaluate to a dictionary object.
|
| 1163 |
+
|
| 1164 |
+
Example usage::
|
| 1165 |
+
|
| 1166 |
+
OverlayScope(context=self.call_method('get_context'),
|
| 1167 |
+
body=[...])
|
| 1168 |
+
|
| 1169 |
+
.. versionadded:: 2.10
|
| 1170 |
+
"""
|
| 1171 |
+
|
| 1172 |
+
fields = ("context", "body")
|
| 1173 |
+
context: Expr
|
| 1174 |
+
body: t.List[Node]
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
class EvalContextModifier(Stmt):
|
| 1178 |
+
"""Modifies the eval context. For each option that should be modified,
|
| 1179 |
+
a :class:`Keyword` has to be added to the :attr:`options` list.
|
| 1180 |
+
|
| 1181 |
+
Example to change the `autoescape` setting::
|
| 1182 |
+
|
| 1183 |
+
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
|
| 1184 |
+
"""
|
| 1185 |
+
|
| 1186 |
+
fields = ("options",)
|
| 1187 |
+
options: t.List[Keyword]
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
class ScopedEvalContextModifier(EvalContextModifier):
|
| 1191 |
+
"""Modifies the eval context and reverts it later. Works exactly like
|
| 1192 |
+
:class:`EvalContextModifier` but will only modify the
|
| 1193 |
+
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
|
| 1194 |
+
"""
|
| 1195 |
+
|
| 1196 |
+
fields = ("body",)
|
| 1197 |
+
body: t.List[Node]
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
# make sure nobody creates custom nodes
|
| 1201 |
+
def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
|
| 1202 |
+
raise TypeError("can't create custom node types")
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
NodeType.__new__ = staticmethod(_failing_new) # type: ignore
|
| 1206 |
+
del _failing_new
|
wemm/lib/python3.10/site-packages/jinja2/parser.py
ADDED
|
@@ -0,0 +1,1049 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parse tokens from the lexer into nodes for the compiler."""
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
import typing as t
|
| 5 |
+
|
| 6 |
+
from . import nodes
|
| 7 |
+
from .exceptions import TemplateAssertionError
|
| 8 |
+
from .exceptions import TemplateSyntaxError
|
| 9 |
+
from .lexer import describe_token
|
| 10 |
+
from .lexer import describe_token_expr
|
| 11 |
+
|
| 12 |
+
if t.TYPE_CHECKING:
|
| 13 |
+
import typing_extensions as te
|
| 14 |
+
|
| 15 |
+
from .environment import Environment
|
| 16 |
+
|
| 17 |
+
_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)
|
| 18 |
+
_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)
|
| 19 |
+
|
| 20 |
+
_statement_keywords = frozenset(
|
| 21 |
+
[
|
| 22 |
+
"for",
|
| 23 |
+
"if",
|
| 24 |
+
"block",
|
| 25 |
+
"extends",
|
| 26 |
+
"print",
|
| 27 |
+
"macro",
|
| 28 |
+
"include",
|
| 29 |
+
"from",
|
| 30 |
+
"import",
|
| 31 |
+
"set",
|
| 32 |
+
"with",
|
| 33 |
+
"autoescape",
|
| 34 |
+
]
|
| 35 |
+
)
|
| 36 |
+
_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])
|
| 37 |
+
|
| 38 |
+
_math_nodes: t.Dict[str, t.Type[nodes.Expr]] = {
|
| 39 |
+
"add": nodes.Add,
|
| 40 |
+
"sub": nodes.Sub,
|
| 41 |
+
"mul": nodes.Mul,
|
| 42 |
+
"div": nodes.Div,
|
| 43 |
+
"floordiv": nodes.FloorDiv,
|
| 44 |
+
"mod": nodes.Mod,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Parser:
|
| 49 |
+
"""This is the central parsing class Jinja uses. It's passed to
|
| 50 |
+
extensions and can be used to parse expressions or statements.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
environment: "Environment",
|
| 56 |
+
source: str,
|
| 57 |
+
name: t.Optional[str] = None,
|
| 58 |
+
filename: t.Optional[str] = None,
|
| 59 |
+
state: t.Optional[str] = None,
|
| 60 |
+
) -> None:
|
| 61 |
+
self.environment = environment
|
| 62 |
+
self.stream = environment._tokenize(source, name, filename, state)
|
| 63 |
+
self.name = name
|
| 64 |
+
self.filename = filename
|
| 65 |
+
self.closed = False
|
| 66 |
+
self.extensions: t.Dict[
|
| 67 |
+
str, t.Callable[[Parser], t.Union[nodes.Node, t.List[nodes.Node]]]
|
| 68 |
+
] = {}
|
| 69 |
+
for extension in environment.iter_extensions():
|
| 70 |
+
for tag in extension.tags:
|
| 71 |
+
self.extensions[tag] = extension.parse
|
| 72 |
+
self._last_identifier = 0
|
| 73 |
+
self._tag_stack: t.List[str] = []
|
| 74 |
+
self._end_token_stack: t.List[t.Tuple[str, ...]] = []
|
| 75 |
+
|
| 76 |
+
def fail(
|
| 77 |
+
self,
|
| 78 |
+
msg: str,
|
| 79 |
+
lineno: t.Optional[int] = None,
|
| 80 |
+
exc: t.Type[TemplateSyntaxError] = TemplateSyntaxError,
|
| 81 |
+
) -> "te.NoReturn":
|
| 82 |
+
"""Convenience method that raises `exc` with the message, passed
|
| 83 |
+
line number or last line number as well as the current name and
|
| 84 |
+
filename.
|
| 85 |
+
"""
|
| 86 |
+
if lineno is None:
|
| 87 |
+
lineno = self.stream.current.lineno
|
| 88 |
+
raise exc(msg, lineno, self.name, self.filename)
|
| 89 |
+
|
| 90 |
+
def _fail_ut_eof(
|
| 91 |
+
self,
|
| 92 |
+
name: t.Optional[str],
|
| 93 |
+
end_token_stack: t.List[t.Tuple[str, ...]],
|
| 94 |
+
lineno: t.Optional[int],
|
| 95 |
+
) -> "te.NoReturn":
|
| 96 |
+
expected: t.Set[str] = set()
|
| 97 |
+
for exprs in end_token_stack:
|
| 98 |
+
expected.update(map(describe_token_expr, exprs))
|
| 99 |
+
if end_token_stack:
|
| 100 |
+
currently_looking: t.Optional[str] = " or ".join(
|
| 101 |
+
map(repr, map(describe_token_expr, end_token_stack[-1]))
|
| 102 |
+
)
|
| 103 |
+
else:
|
| 104 |
+
currently_looking = None
|
| 105 |
+
|
| 106 |
+
if name is None:
|
| 107 |
+
message = ["Unexpected end of template."]
|
| 108 |
+
else:
|
| 109 |
+
message = [f"Encountered unknown tag {name!r}."]
|
| 110 |
+
|
| 111 |
+
if currently_looking:
|
| 112 |
+
if name is not None and name in expected:
|
| 113 |
+
message.append(
|
| 114 |
+
"You probably made a nesting mistake. Jinja is expecting this tag,"
|
| 115 |
+
f" but currently looking for {currently_looking}."
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
message.append(
|
| 119 |
+
f"Jinja was looking for the following tags: {currently_looking}."
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
if self._tag_stack:
|
| 123 |
+
message.append(
|
| 124 |
+
"The innermost block that needs to be closed is"
|
| 125 |
+
f" {self._tag_stack[-1]!r}."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.fail(" ".join(message), lineno)
|
| 129 |
+
|
| 130 |
+
def fail_unknown_tag(
|
| 131 |
+
self, name: str, lineno: t.Optional[int] = None
|
| 132 |
+
) -> "te.NoReturn":
|
| 133 |
+
"""Called if the parser encounters an unknown tag. Tries to fail
|
| 134 |
+
with a human readable error message that could help to identify
|
| 135 |
+
the problem.
|
| 136 |
+
"""
|
| 137 |
+
self._fail_ut_eof(name, self._end_token_stack, lineno)
|
| 138 |
+
|
| 139 |
+
def fail_eof(
|
| 140 |
+
self,
|
| 141 |
+
end_tokens: t.Optional[t.Tuple[str, ...]] = None,
|
| 142 |
+
lineno: t.Optional[int] = None,
|
| 143 |
+
) -> "te.NoReturn":
|
| 144 |
+
"""Like fail_unknown_tag but for end of template situations."""
|
| 145 |
+
stack = list(self._end_token_stack)
|
| 146 |
+
if end_tokens is not None:
|
| 147 |
+
stack.append(end_tokens)
|
| 148 |
+
self._fail_ut_eof(None, stack, lineno)
|
| 149 |
+
|
| 150 |
+
def is_tuple_end(
|
| 151 |
+
self, extra_end_rules: t.Optional[t.Tuple[str, ...]] = None
|
| 152 |
+
) -> bool:
|
| 153 |
+
"""Are we at the end of a tuple?"""
|
| 154 |
+
if self.stream.current.type in ("variable_end", "block_end", "rparen"):
|
| 155 |
+
return True
|
| 156 |
+
elif extra_end_rules is not None:
|
| 157 |
+
return self.stream.current.test_any(extra_end_rules) # type: ignore
|
| 158 |
+
return False
|
| 159 |
+
|
| 160 |
+
def free_identifier(self, lineno: t.Optional[int] = None) -> nodes.InternalName:
|
| 161 |
+
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
|
| 162 |
+
self._last_identifier += 1
|
| 163 |
+
rv = object.__new__(nodes.InternalName)
|
| 164 |
+
nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)
|
| 165 |
+
return rv
|
| 166 |
+
|
| 167 |
+
def parse_statement(self) -> t.Union[nodes.Node, t.List[nodes.Node]]:
|
| 168 |
+
"""Parse a single statement."""
|
| 169 |
+
token = self.stream.current
|
| 170 |
+
if token.type != "name":
|
| 171 |
+
self.fail("tag name expected", token.lineno)
|
| 172 |
+
self._tag_stack.append(token.value)
|
| 173 |
+
pop_tag = True
|
| 174 |
+
try:
|
| 175 |
+
if token.value in _statement_keywords:
|
| 176 |
+
f = getattr(self, f"parse_{self.stream.current.value}")
|
| 177 |
+
return f() # type: ignore
|
| 178 |
+
if token.value == "call":
|
| 179 |
+
return self.parse_call_block()
|
| 180 |
+
if token.value == "filter":
|
| 181 |
+
return self.parse_filter_block()
|
| 182 |
+
ext = self.extensions.get(token.value)
|
| 183 |
+
if ext is not None:
|
| 184 |
+
return ext(self)
|
| 185 |
+
|
| 186 |
+
# did not work out, remove the token we pushed by accident
|
| 187 |
+
# from the stack so that the unknown tag fail function can
|
| 188 |
+
# produce a proper error message.
|
| 189 |
+
self._tag_stack.pop()
|
| 190 |
+
pop_tag = False
|
| 191 |
+
self.fail_unknown_tag(token.value, token.lineno)
|
| 192 |
+
finally:
|
| 193 |
+
if pop_tag:
|
| 194 |
+
self._tag_stack.pop()
|
| 195 |
+
|
| 196 |
+
def parse_statements(
|
| 197 |
+
self, end_tokens: t.Tuple[str, ...], drop_needle: bool = False
|
| 198 |
+
) -> t.List[nodes.Node]:
|
| 199 |
+
"""Parse multiple statements into a list until one of the end tokens
|
| 200 |
+
is reached. This is used to parse the body of statements as it also
|
| 201 |
+
parses template data if appropriate. The parser checks first if the
|
| 202 |
+
current token is a colon and skips it if there is one. Then it checks
|
| 203 |
+
for the block end and parses until if one of the `end_tokens` is
|
| 204 |
+
reached. Per default the active token in the stream at the end of
|
| 205 |
+
the call is the matched end token. If this is not wanted `drop_needle`
|
| 206 |
+
can be set to `True` and the end token is removed.
|
| 207 |
+
"""
|
| 208 |
+
# the first token may be a colon for python compatibility
|
| 209 |
+
self.stream.skip_if("colon")
|
| 210 |
+
|
| 211 |
+
# in the future it would be possible to add whole code sections
|
| 212 |
+
# by adding some sort of end of statement token and parsing those here.
|
| 213 |
+
self.stream.expect("block_end")
|
| 214 |
+
result = self.subparse(end_tokens)
|
| 215 |
+
|
| 216 |
+
# we reached the end of the template too early, the subparser
|
| 217 |
+
# does not check for this, so we do that now
|
| 218 |
+
if self.stream.current.type == "eof":
|
| 219 |
+
self.fail_eof(end_tokens)
|
| 220 |
+
|
| 221 |
+
if drop_needle:
|
| 222 |
+
next(self.stream)
|
| 223 |
+
return result
|
| 224 |
+
|
| 225 |
+
def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:
|
| 226 |
+
"""Parse an assign statement."""
|
| 227 |
+
lineno = next(self.stream).lineno
|
| 228 |
+
target = self.parse_assign_target(with_namespace=True)
|
| 229 |
+
if self.stream.skip_if("assign"):
|
| 230 |
+
expr = self.parse_tuple()
|
| 231 |
+
return nodes.Assign(target, expr, lineno=lineno)
|
| 232 |
+
filter_node = self.parse_filter(None)
|
| 233 |
+
body = self.parse_statements(("name:endset",), drop_needle=True)
|
| 234 |
+
return nodes.AssignBlock(target, filter_node, body, lineno=lineno)
|
| 235 |
+
|
| 236 |
+
def parse_for(self) -> nodes.For:
|
| 237 |
+
"""Parse a for loop."""
|
| 238 |
+
lineno = self.stream.expect("name:for").lineno
|
| 239 |
+
target = self.parse_assign_target(extra_end_rules=("name:in",))
|
| 240 |
+
self.stream.expect("name:in")
|
| 241 |
+
iter = self.parse_tuple(
|
| 242 |
+
with_condexpr=False, extra_end_rules=("name:recursive",)
|
| 243 |
+
)
|
| 244 |
+
test = None
|
| 245 |
+
if self.stream.skip_if("name:if"):
|
| 246 |
+
test = self.parse_expression()
|
| 247 |
+
recursive = self.stream.skip_if("name:recursive")
|
| 248 |
+
body = self.parse_statements(("name:endfor", "name:else"))
|
| 249 |
+
if next(self.stream).value == "endfor":
|
| 250 |
+
else_ = []
|
| 251 |
+
else:
|
| 252 |
+
else_ = self.parse_statements(("name:endfor",), drop_needle=True)
|
| 253 |
+
return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)
|
| 254 |
+
|
| 255 |
+
def parse_if(self) -> nodes.If:
|
| 256 |
+
"""Parse an if construct."""
|
| 257 |
+
node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)
|
| 258 |
+
while True:
|
| 259 |
+
node.test = self.parse_tuple(with_condexpr=False)
|
| 260 |
+
node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))
|
| 261 |
+
node.elif_ = []
|
| 262 |
+
node.else_ = []
|
| 263 |
+
token = next(self.stream)
|
| 264 |
+
if token.test("name:elif"):
|
| 265 |
+
node = nodes.If(lineno=self.stream.current.lineno)
|
| 266 |
+
result.elif_.append(node)
|
| 267 |
+
continue
|
| 268 |
+
elif token.test("name:else"):
|
| 269 |
+
result.else_ = self.parse_statements(("name:endif",), drop_needle=True)
|
| 270 |
+
break
|
| 271 |
+
return result
|
| 272 |
+
|
| 273 |
+
def parse_with(self) -> nodes.With:
|
| 274 |
+
node = nodes.With(lineno=next(self.stream).lineno)
|
| 275 |
+
targets: t.List[nodes.Expr] = []
|
| 276 |
+
values: t.List[nodes.Expr] = []
|
| 277 |
+
while self.stream.current.type != "block_end":
|
| 278 |
+
if targets:
|
| 279 |
+
self.stream.expect("comma")
|
| 280 |
+
target = self.parse_assign_target()
|
| 281 |
+
target.set_ctx("param")
|
| 282 |
+
targets.append(target)
|
| 283 |
+
self.stream.expect("assign")
|
| 284 |
+
values.append(self.parse_expression())
|
| 285 |
+
node.targets = targets
|
| 286 |
+
node.values = values
|
| 287 |
+
node.body = self.parse_statements(("name:endwith",), drop_needle=True)
|
| 288 |
+
return node
|
| 289 |
+
|
| 290 |
+
def parse_autoescape(self) -> nodes.Scope:
|
| 291 |
+
node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)
|
| 292 |
+
node.options = [nodes.Keyword("autoescape", self.parse_expression())]
|
| 293 |
+
node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)
|
| 294 |
+
return nodes.Scope([node])
|
| 295 |
+
|
| 296 |
+
def parse_block(self) -> nodes.Block:
|
| 297 |
+
node = nodes.Block(lineno=next(self.stream).lineno)
|
| 298 |
+
node.name = self.stream.expect("name").value
|
| 299 |
+
node.scoped = self.stream.skip_if("name:scoped")
|
| 300 |
+
node.required = self.stream.skip_if("name:required")
|
| 301 |
+
|
| 302 |
+
# common problem people encounter when switching from django
|
| 303 |
+
# to jinja. we do not support hyphens in block names, so let's
|
| 304 |
+
# raise a nicer error message in that case.
|
| 305 |
+
if self.stream.current.type == "sub":
|
| 306 |
+
self.fail(
|
| 307 |
+
"Block names in Jinja have to be valid Python identifiers and may not"
|
| 308 |
+
" contain hyphens, use an underscore instead."
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
node.body = self.parse_statements(("name:endblock",), drop_needle=True)
|
| 312 |
+
|
| 313 |
+
# enforce that required blocks only contain whitespace or comments
|
| 314 |
+
# by asserting that the body, if not empty, is just TemplateData nodes
|
| 315 |
+
# with whitespace data
|
| 316 |
+
if node.required:
|
| 317 |
+
for body_node in node.body:
|
| 318 |
+
if not isinstance(body_node, nodes.Output) or any(
|
| 319 |
+
not isinstance(output_node, nodes.TemplateData)
|
| 320 |
+
or not output_node.data.isspace()
|
| 321 |
+
for output_node in body_node.nodes
|
| 322 |
+
):
|
| 323 |
+
self.fail("Required blocks can only contain comments or whitespace")
|
| 324 |
+
|
| 325 |
+
self.stream.skip_if("name:" + node.name)
|
| 326 |
+
return node
|
| 327 |
+
|
| 328 |
+
def parse_extends(self) -> nodes.Extends:
|
| 329 |
+
node = nodes.Extends(lineno=next(self.stream).lineno)
|
| 330 |
+
node.template = self.parse_expression()
|
| 331 |
+
return node
|
| 332 |
+
|
| 333 |
+
def parse_import_context(
|
| 334 |
+
self, node: _ImportInclude, default: bool
|
| 335 |
+
) -> _ImportInclude:
|
| 336 |
+
if self.stream.current.test_any(
|
| 337 |
+
"name:with", "name:without"
|
| 338 |
+
) and self.stream.look().test("name:context"):
|
| 339 |
+
node.with_context = next(self.stream).value == "with"
|
| 340 |
+
self.stream.skip()
|
| 341 |
+
else:
|
| 342 |
+
node.with_context = default
|
| 343 |
+
return node
|
| 344 |
+
|
| 345 |
+
def parse_include(self) -> nodes.Include:
|
| 346 |
+
node = nodes.Include(lineno=next(self.stream).lineno)
|
| 347 |
+
node.template = self.parse_expression()
|
| 348 |
+
if self.stream.current.test("name:ignore") and self.stream.look().test(
|
| 349 |
+
"name:missing"
|
| 350 |
+
):
|
| 351 |
+
node.ignore_missing = True
|
| 352 |
+
self.stream.skip(2)
|
| 353 |
+
else:
|
| 354 |
+
node.ignore_missing = False
|
| 355 |
+
return self.parse_import_context(node, True)
|
| 356 |
+
|
| 357 |
+
def parse_import(self) -> nodes.Import:
|
| 358 |
+
node = nodes.Import(lineno=next(self.stream).lineno)
|
| 359 |
+
node.template = self.parse_expression()
|
| 360 |
+
self.stream.expect("name:as")
|
| 361 |
+
node.target = self.parse_assign_target(name_only=True).name
|
| 362 |
+
return self.parse_import_context(node, False)
|
| 363 |
+
|
| 364 |
+
def parse_from(self) -> nodes.FromImport:
|
| 365 |
+
node = nodes.FromImport(lineno=next(self.stream).lineno)
|
| 366 |
+
node.template = self.parse_expression()
|
| 367 |
+
self.stream.expect("name:import")
|
| 368 |
+
node.names = []
|
| 369 |
+
|
| 370 |
+
def parse_context() -> bool:
|
| 371 |
+
if self.stream.current.value in {
|
| 372 |
+
"with",
|
| 373 |
+
"without",
|
| 374 |
+
} and self.stream.look().test("name:context"):
|
| 375 |
+
node.with_context = next(self.stream).value == "with"
|
| 376 |
+
self.stream.skip()
|
| 377 |
+
return True
|
| 378 |
+
return False
|
| 379 |
+
|
| 380 |
+
while True:
|
| 381 |
+
if node.names:
|
| 382 |
+
self.stream.expect("comma")
|
| 383 |
+
if self.stream.current.type == "name":
|
| 384 |
+
if parse_context():
|
| 385 |
+
break
|
| 386 |
+
target = self.parse_assign_target(name_only=True)
|
| 387 |
+
if target.name.startswith("_"):
|
| 388 |
+
self.fail(
|
| 389 |
+
"names starting with an underline can not be imported",
|
| 390 |
+
target.lineno,
|
| 391 |
+
exc=TemplateAssertionError,
|
| 392 |
+
)
|
| 393 |
+
if self.stream.skip_if("name:as"):
|
| 394 |
+
alias = self.parse_assign_target(name_only=True)
|
| 395 |
+
node.names.append((target.name, alias.name))
|
| 396 |
+
else:
|
| 397 |
+
node.names.append(target.name)
|
| 398 |
+
if parse_context() or self.stream.current.type != "comma":
|
| 399 |
+
break
|
| 400 |
+
else:
|
| 401 |
+
self.stream.expect("name")
|
| 402 |
+
if not hasattr(node, "with_context"):
|
| 403 |
+
node.with_context = False
|
| 404 |
+
return node
|
| 405 |
+
|
| 406 |
+
def parse_signature(self, node: _MacroCall) -> None:
|
| 407 |
+
args = node.args = []
|
| 408 |
+
defaults = node.defaults = []
|
| 409 |
+
self.stream.expect("lparen")
|
| 410 |
+
while self.stream.current.type != "rparen":
|
| 411 |
+
if args:
|
| 412 |
+
self.stream.expect("comma")
|
| 413 |
+
arg = self.parse_assign_target(name_only=True)
|
| 414 |
+
arg.set_ctx("param")
|
| 415 |
+
if self.stream.skip_if("assign"):
|
| 416 |
+
defaults.append(self.parse_expression())
|
| 417 |
+
elif defaults:
|
| 418 |
+
self.fail("non-default argument follows default argument")
|
| 419 |
+
args.append(arg)
|
| 420 |
+
self.stream.expect("rparen")
|
| 421 |
+
|
| 422 |
+
def parse_call_block(self) -> nodes.CallBlock:
|
| 423 |
+
node = nodes.CallBlock(lineno=next(self.stream).lineno)
|
| 424 |
+
if self.stream.current.type == "lparen":
|
| 425 |
+
self.parse_signature(node)
|
| 426 |
+
else:
|
| 427 |
+
node.args = []
|
| 428 |
+
node.defaults = []
|
| 429 |
+
|
| 430 |
+
call_node = self.parse_expression()
|
| 431 |
+
if not isinstance(call_node, nodes.Call):
|
| 432 |
+
self.fail("expected call", node.lineno)
|
| 433 |
+
node.call = call_node
|
| 434 |
+
node.body = self.parse_statements(("name:endcall",), drop_needle=True)
|
| 435 |
+
return node
|
| 436 |
+
|
| 437 |
+
def parse_filter_block(self) -> nodes.FilterBlock:
|
| 438 |
+
node = nodes.FilterBlock(lineno=next(self.stream).lineno)
|
| 439 |
+
node.filter = self.parse_filter(None, start_inline=True) # type: ignore
|
| 440 |
+
node.body = self.parse_statements(("name:endfilter",), drop_needle=True)
|
| 441 |
+
return node
|
| 442 |
+
|
| 443 |
+
def parse_macro(self) -> nodes.Macro:
|
| 444 |
+
node = nodes.Macro(lineno=next(self.stream).lineno)
|
| 445 |
+
node.name = self.parse_assign_target(name_only=True).name
|
| 446 |
+
self.parse_signature(node)
|
| 447 |
+
node.body = self.parse_statements(("name:endmacro",), drop_needle=True)
|
| 448 |
+
return node
|
| 449 |
+
|
| 450 |
+
def parse_print(self) -> nodes.Output:
|
| 451 |
+
node = nodes.Output(lineno=next(self.stream).lineno)
|
| 452 |
+
node.nodes = []
|
| 453 |
+
while self.stream.current.type != "block_end":
|
| 454 |
+
if node.nodes:
|
| 455 |
+
self.stream.expect("comma")
|
| 456 |
+
node.nodes.append(self.parse_expression())
|
| 457 |
+
return node
|
| 458 |
+
|
| 459 |
+
@typing.overload
|
| 460 |
+
def parse_assign_target(
|
| 461 |
+
self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...
|
| 462 |
+
) -> nodes.Name: ...
|
| 463 |
+
|
| 464 |
+
@typing.overload
|
| 465 |
+
def parse_assign_target(
|
| 466 |
+
self,
|
| 467 |
+
with_tuple: bool = True,
|
| 468 |
+
name_only: bool = False,
|
| 469 |
+
extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,
|
| 470 |
+
with_namespace: bool = False,
|
| 471 |
+
) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...
|
| 472 |
+
|
| 473 |
+
def parse_assign_target(
|
| 474 |
+
self,
|
| 475 |
+
with_tuple: bool = True,
|
| 476 |
+
name_only: bool = False,
|
| 477 |
+
extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,
|
| 478 |
+
with_namespace: bool = False,
|
| 479 |
+
) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:
|
| 480 |
+
"""Parse an assignment target. As Jinja allows assignments to
|
| 481 |
+
tuples, this function can parse all allowed assignment targets. Per
|
| 482 |
+
default assignments to tuples are parsed, that can be disable however
|
| 483 |
+
by setting `with_tuple` to `False`. If only assignments to names are
|
| 484 |
+
wanted `name_only` can be set to `True`. The `extra_end_rules`
|
| 485 |
+
parameter is forwarded to the tuple parsing function. If
|
| 486 |
+
`with_namespace` is enabled, a namespace assignment may be parsed.
|
| 487 |
+
"""
|
| 488 |
+
target: nodes.Expr
|
| 489 |
+
|
| 490 |
+
if name_only:
|
| 491 |
+
token = self.stream.expect("name")
|
| 492 |
+
target = nodes.Name(token.value, "store", lineno=token.lineno)
|
| 493 |
+
else:
|
| 494 |
+
if with_tuple:
|
| 495 |
+
target = self.parse_tuple(
|
| 496 |
+
simplified=True,
|
| 497 |
+
extra_end_rules=extra_end_rules,
|
| 498 |
+
with_namespace=with_namespace,
|
| 499 |
+
)
|
| 500 |
+
else:
|
| 501 |
+
target = self.parse_primary(with_namespace=with_namespace)
|
| 502 |
+
|
| 503 |
+
target.set_ctx("store")
|
| 504 |
+
|
| 505 |
+
if not target.can_assign():
|
| 506 |
+
self.fail(
|
| 507 |
+
f"can't assign to {type(target).__name__.lower()!r}", target.lineno
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
return target # type: ignore
|
| 511 |
+
|
| 512 |
+
def parse_expression(self, with_condexpr: bool = True) -> nodes.Expr:
|
| 513 |
+
"""Parse an expression. Per default all expressions are parsed, if
|
| 514 |
+
the optional `with_condexpr` parameter is set to `False` conditional
|
| 515 |
+
expressions are not parsed.
|
| 516 |
+
"""
|
| 517 |
+
if with_condexpr:
|
| 518 |
+
return self.parse_condexpr()
|
| 519 |
+
return self.parse_or()
|
| 520 |
+
|
| 521 |
+
def parse_condexpr(self) -> nodes.Expr:
|
| 522 |
+
lineno = self.stream.current.lineno
|
| 523 |
+
expr1 = self.parse_or()
|
| 524 |
+
expr3: t.Optional[nodes.Expr]
|
| 525 |
+
|
| 526 |
+
while self.stream.skip_if("name:if"):
|
| 527 |
+
expr2 = self.parse_or()
|
| 528 |
+
if self.stream.skip_if("name:else"):
|
| 529 |
+
expr3 = self.parse_condexpr()
|
| 530 |
+
else:
|
| 531 |
+
expr3 = None
|
| 532 |
+
expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
|
| 533 |
+
lineno = self.stream.current.lineno
|
| 534 |
+
return expr1
|
| 535 |
+
|
| 536 |
+
def parse_or(self) -> nodes.Expr:
|
| 537 |
+
lineno = self.stream.current.lineno
|
| 538 |
+
left = self.parse_and()
|
| 539 |
+
while self.stream.skip_if("name:or"):
|
| 540 |
+
right = self.parse_and()
|
| 541 |
+
left = nodes.Or(left, right, lineno=lineno)
|
| 542 |
+
lineno = self.stream.current.lineno
|
| 543 |
+
return left
|
| 544 |
+
|
| 545 |
+
def parse_and(self) -> nodes.Expr:
|
| 546 |
+
lineno = self.stream.current.lineno
|
| 547 |
+
left = self.parse_not()
|
| 548 |
+
while self.stream.skip_if("name:and"):
|
| 549 |
+
right = self.parse_not()
|
| 550 |
+
left = nodes.And(left, right, lineno=lineno)
|
| 551 |
+
lineno = self.stream.current.lineno
|
| 552 |
+
return left
|
| 553 |
+
|
| 554 |
+
def parse_not(self) -> nodes.Expr:
|
| 555 |
+
if self.stream.current.test("name:not"):
|
| 556 |
+
lineno = next(self.stream).lineno
|
| 557 |
+
return nodes.Not(self.parse_not(), lineno=lineno)
|
| 558 |
+
return self.parse_compare()
|
| 559 |
+
|
| 560 |
+
def parse_compare(self) -> nodes.Expr:
|
| 561 |
+
lineno = self.stream.current.lineno
|
| 562 |
+
expr = self.parse_math1()
|
| 563 |
+
ops = []
|
| 564 |
+
while True:
|
| 565 |
+
token_type = self.stream.current.type
|
| 566 |
+
if token_type in _compare_operators:
|
| 567 |
+
next(self.stream)
|
| 568 |
+
ops.append(nodes.Operand(token_type, self.parse_math1()))
|
| 569 |
+
elif self.stream.skip_if("name:in"):
|
| 570 |
+
ops.append(nodes.Operand("in", self.parse_math1()))
|
| 571 |
+
elif self.stream.current.test("name:not") and self.stream.look().test(
|
| 572 |
+
"name:in"
|
| 573 |
+
):
|
| 574 |
+
self.stream.skip(2)
|
| 575 |
+
ops.append(nodes.Operand("notin", self.parse_math1()))
|
| 576 |
+
else:
|
| 577 |
+
break
|
| 578 |
+
lineno = self.stream.current.lineno
|
| 579 |
+
if not ops:
|
| 580 |
+
return expr
|
| 581 |
+
return nodes.Compare(expr, ops, lineno=lineno)
|
| 582 |
+
|
| 583 |
+
def parse_math1(self) -> nodes.Expr:
|
| 584 |
+
lineno = self.stream.current.lineno
|
| 585 |
+
left = self.parse_concat()
|
| 586 |
+
while self.stream.current.type in ("add", "sub"):
|
| 587 |
+
cls = _math_nodes[self.stream.current.type]
|
| 588 |
+
next(self.stream)
|
| 589 |
+
right = self.parse_concat()
|
| 590 |
+
left = cls(left, right, lineno=lineno)
|
| 591 |
+
lineno = self.stream.current.lineno
|
| 592 |
+
return left
|
| 593 |
+
|
| 594 |
+
def parse_concat(self) -> nodes.Expr:
|
| 595 |
+
lineno = self.stream.current.lineno
|
| 596 |
+
args = [self.parse_math2()]
|
| 597 |
+
while self.stream.current.type == "tilde":
|
| 598 |
+
next(self.stream)
|
| 599 |
+
args.append(self.parse_math2())
|
| 600 |
+
if len(args) == 1:
|
| 601 |
+
return args[0]
|
| 602 |
+
return nodes.Concat(args, lineno=lineno)
|
| 603 |
+
|
| 604 |
+
def parse_math2(self) -> nodes.Expr:
|
| 605 |
+
lineno = self.stream.current.lineno
|
| 606 |
+
left = self.parse_pow()
|
| 607 |
+
while self.stream.current.type in ("mul", "div", "floordiv", "mod"):
|
| 608 |
+
cls = _math_nodes[self.stream.current.type]
|
| 609 |
+
next(self.stream)
|
| 610 |
+
right = self.parse_pow()
|
| 611 |
+
left = cls(left, right, lineno=lineno)
|
| 612 |
+
lineno = self.stream.current.lineno
|
| 613 |
+
return left
|
| 614 |
+
|
| 615 |
+
def parse_pow(self) -> nodes.Expr:
|
| 616 |
+
lineno = self.stream.current.lineno
|
| 617 |
+
left = self.parse_unary()
|
| 618 |
+
while self.stream.current.type == "pow":
|
| 619 |
+
next(self.stream)
|
| 620 |
+
right = self.parse_unary()
|
| 621 |
+
left = nodes.Pow(left, right, lineno=lineno)
|
| 622 |
+
lineno = self.stream.current.lineno
|
| 623 |
+
return left
|
| 624 |
+
|
| 625 |
+
def parse_unary(self, with_filter: bool = True) -> nodes.Expr:
|
| 626 |
+
token_type = self.stream.current.type
|
| 627 |
+
lineno = self.stream.current.lineno
|
| 628 |
+
node: nodes.Expr
|
| 629 |
+
|
| 630 |
+
if token_type == "sub":
|
| 631 |
+
next(self.stream)
|
| 632 |
+
node = nodes.Neg(self.parse_unary(False), lineno=lineno)
|
| 633 |
+
elif token_type == "add":
|
| 634 |
+
next(self.stream)
|
| 635 |
+
node = nodes.Pos(self.parse_unary(False), lineno=lineno)
|
| 636 |
+
else:
|
| 637 |
+
node = self.parse_primary()
|
| 638 |
+
node = self.parse_postfix(node)
|
| 639 |
+
if with_filter:
|
| 640 |
+
node = self.parse_filter_expr(node)
|
| 641 |
+
return node
|
| 642 |
+
|
| 643 |
+
def parse_primary(self, with_namespace: bool = False) -> nodes.Expr:
|
| 644 |
+
"""Parse a name or literal value. If ``with_namespace`` is enabled, also
|
| 645 |
+
parse namespace attr refs, for use in assignments."""
|
| 646 |
+
token = self.stream.current
|
| 647 |
+
node: nodes.Expr
|
| 648 |
+
if token.type == "name":
|
| 649 |
+
next(self.stream)
|
| 650 |
+
if token.value in ("true", "false", "True", "False"):
|
| 651 |
+
node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)
|
| 652 |
+
elif token.value in ("none", "None"):
|
| 653 |
+
node = nodes.Const(None, lineno=token.lineno)
|
| 654 |
+
elif with_namespace and self.stream.current.type == "dot":
|
| 655 |
+
# If namespace attributes are allowed at this point, and the next
|
| 656 |
+
# token is a dot, produce a namespace reference.
|
| 657 |
+
next(self.stream)
|
| 658 |
+
attr = self.stream.expect("name")
|
| 659 |
+
node = nodes.NSRef(token.value, attr.value, lineno=token.lineno)
|
| 660 |
+
else:
|
| 661 |
+
node = nodes.Name(token.value, "load", lineno=token.lineno)
|
| 662 |
+
elif token.type == "string":
|
| 663 |
+
next(self.stream)
|
| 664 |
+
buf = [token.value]
|
| 665 |
+
lineno = token.lineno
|
| 666 |
+
while self.stream.current.type == "string":
|
| 667 |
+
buf.append(self.stream.current.value)
|
| 668 |
+
next(self.stream)
|
| 669 |
+
node = nodes.Const("".join(buf), lineno=lineno)
|
| 670 |
+
elif token.type in ("integer", "float"):
|
| 671 |
+
next(self.stream)
|
| 672 |
+
node = nodes.Const(token.value, lineno=token.lineno)
|
| 673 |
+
elif token.type == "lparen":
|
| 674 |
+
next(self.stream)
|
| 675 |
+
node = self.parse_tuple(explicit_parentheses=True)
|
| 676 |
+
self.stream.expect("rparen")
|
| 677 |
+
elif token.type == "lbracket":
|
| 678 |
+
node = self.parse_list()
|
| 679 |
+
elif token.type == "lbrace":
|
| 680 |
+
node = self.parse_dict()
|
| 681 |
+
else:
|
| 682 |
+
self.fail(f"unexpected {describe_token(token)!r}", token.lineno)
|
| 683 |
+
return node
|
| 684 |
+
|
| 685 |
+
def parse_tuple(
|
| 686 |
+
self,
|
| 687 |
+
simplified: bool = False,
|
| 688 |
+
with_condexpr: bool = True,
|
| 689 |
+
extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,
|
| 690 |
+
explicit_parentheses: bool = False,
|
| 691 |
+
with_namespace: bool = False,
|
| 692 |
+
) -> t.Union[nodes.Tuple, nodes.Expr]:
|
| 693 |
+
"""Works like `parse_expression` but if multiple expressions are
|
| 694 |
+
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
|
| 695 |
+
This method could also return a regular expression instead of a tuple
|
| 696 |
+
if no commas where found.
|
| 697 |
+
|
| 698 |
+
The default parsing mode is a full tuple. If `simplified` is `True`
|
| 699 |
+
only names and literals are parsed; ``with_namespace`` allows namespace
|
| 700 |
+
attr refs as well. The `no_condexpr` parameter is forwarded to
|
| 701 |
+
:meth:`parse_expression`.
|
| 702 |
+
|
| 703 |
+
Because tuples do not require delimiters and may end in a bogus comma
|
| 704 |
+
an extra hint is needed that marks the end of a tuple. For example
|
| 705 |
+
for loops support tuples between `for` and `in`. In that case the
|
| 706 |
+
`extra_end_rules` is set to ``['name:in']``.
|
| 707 |
+
|
| 708 |
+
`explicit_parentheses` is true if the parsing was triggered by an
|
| 709 |
+
expression in parentheses. This is used to figure out if an empty
|
| 710 |
+
tuple is a valid expression or not.
|
| 711 |
+
"""
|
| 712 |
+
lineno = self.stream.current.lineno
|
| 713 |
+
if simplified:
|
| 714 |
+
|
| 715 |
+
def parse() -> nodes.Expr:
|
| 716 |
+
return self.parse_primary(with_namespace=with_namespace)
|
| 717 |
+
|
| 718 |
+
else:
|
| 719 |
+
|
| 720 |
+
def parse() -> nodes.Expr:
|
| 721 |
+
return self.parse_expression(with_condexpr=with_condexpr)
|
| 722 |
+
|
| 723 |
+
args: t.List[nodes.Expr] = []
|
| 724 |
+
is_tuple = False
|
| 725 |
+
|
| 726 |
+
while True:
|
| 727 |
+
if args:
|
| 728 |
+
self.stream.expect("comma")
|
| 729 |
+
if self.is_tuple_end(extra_end_rules):
|
| 730 |
+
break
|
| 731 |
+
args.append(parse())
|
| 732 |
+
if self.stream.current.type == "comma":
|
| 733 |
+
is_tuple = True
|
| 734 |
+
else:
|
| 735 |
+
break
|
| 736 |
+
lineno = self.stream.current.lineno
|
| 737 |
+
|
| 738 |
+
if not is_tuple:
|
| 739 |
+
if args:
|
| 740 |
+
return args[0]
|
| 741 |
+
|
| 742 |
+
# if we don't have explicit parentheses, an empty tuple is
|
| 743 |
+
# not a valid expression. This would mean nothing (literally
|
| 744 |
+
# nothing) in the spot of an expression would be an empty
|
| 745 |
+
# tuple.
|
| 746 |
+
if not explicit_parentheses:
|
| 747 |
+
self.fail(
|
| 748 |
+
"Expected an expression,"
|
| 749 |
+
f" got {describe_token(self.stream.current)!r}"
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
return nodes.Tuple(args, "load", lineno=lineno)
|
| 753 |
+
|
| 754 |
+
def parse_list(self) -> nodes.List:
|
| 755 |
+
token = self.stream.expect("lbracket")
|
| 756 |
+
items: t.List[nodes.Expr] = []
|
| 757 |
+
while self.stream.current.type != "rbracket":
|
| 758 |
+
if items:
|
| 759 |
+
self.stream.expect("comma")
|
| 760 |
+
if self.stream.current.type == "rbracket":
|
| 761 |
+
break
|
| 762 |
+
items.append(self.parse_expression())
|
| 763 |
+
self.stream.expect("rbracket")
|
| 764 |
+
return nodes.List(items, lineno=token.lineno)
|
| 765 |
+
|
| 766 |
+
def parse_dict(self) -> nodes.Dict:
|
| 767 |
+
token = self.stream.expect("lbrace")
|
| 768 |
+
items: t.List[nodes.Pair] = []
|
| 769 |
+
while self.stream.current.type != "rbrace":
|
| 770 |
+
if items:
|
| 771 |
+
self.stream.expect("comma")
|
| 772 |
+
if self.stream.current.type == "rbrace":
|
| 773 |
+
break
|
| 774 |
+
key = self.parse_expression()
|
| 775 |
+
self.stream.expect("colon")
|
| 776 |
+
value = self.parse_expression()
|
| 777 |
+
items.append(nodes.Pair(key, value, lineno=key.lineno))
|
| 778 |
+
self.stream.expect("rbrace")
|
| 779 |
+
return nodes.Dict(items, lineno=token.lineno)
|
| 780 |
+
|
| 781 |
+
def parse_postfix(self, node: nodes.Expr) -> nodes.Expr:
|
| 782 |
+
while True:
|
| 783 |
+
token_type = self.stream.current.type
|
| 784 |
+
if token_type == "dot" or token_type == "lbracket":
|
| 785 |
+
node = self.parse_subscript(node)
|
| 786 |
+
# calls are valid both after postfix expressions (getattr
|
| 787 |
+
# and getitem) as well as filters and tests
|
| 788 |
+
elif token_type == "lparen":
|
| 789 |
+
node = self.parse_call(node)
|
| 790 |
+
else:
|
| 791 |
+
break
|
| 792 |
+
return node
|
| 793 |
+
|
| 794 |
+
def parse_filter_expr(self, node: nodes.Expr) -> nodes.Expr:
|
| 795 |
+
while True:
|
| 796 |
+
token_type = self.stream.current.type
|
| 797 |
+
if token_type == "pipe":
|
| 798 |
+
node = self.parse_filter(node) # type: ignore
|
| 799 |
+
elif token_type == "name" and self.stream.current.value == "is":
|
| 800 |
+
node = self.parse_test(node)
|
| 801 |
+
# calls are valid both after postfix expressions (getattr
|
| 802 |
+
# and getitem) as well as filters and tests
|
| 803 |
+
elif token_type == "lparen":
|
| 804 |
+
node = self.parse_call(node)
|
| 805 |
+
else:
|
| 806 |
+
break
|
| 807 |
+
return node
|
| 808 |
+
|
| 809 |
+
def parse_subscript(
|
| 810 |
+
self, node: nodes.Expr
|
| 811 |
+
) -> t.Union[nodes.Getattr, nodes.Getitem]:
|
| 812 |
+
token = next(self.stream)
|
| 813 |
+
arg: nodes.Expr
|
| 814 |
+
|
| 815 |
+
if token.type == "dot":
|
| 816 |
+
attr_token = self.stream.current
|
| 817 |
+
next(self.stream)
|
| 818 |
+
if attr_token.type == "name":
|
| 819 |
+
return nodes.Getattr(
|
| 820 |
+
node, attr_token.value, "load", lineno=token.lineno
|
| 821 |
+
)
|
| 822 |
+
elif attr_token.type != "integer":
|
| 823 |
+
self.fail("expected name or number", attr_token.lineno)
|
| 824 |
+
arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
|
| 825 |
+
return nodes.Getitem(node, arg, "load", lineno=token.lineno)
|
| 826 |
+
if token.type == "lbracket":
|
| 827 |
+
args: t.List[nodes.Expr] = []
|
| 828 |
+
while self.stream.current.type != "rbracket":
|
| 829 |
+
if args:
|
| 830 |
+
self.stream.expect("comma")
|
| 831 |
+
args.append(self.parse_subscribed())
|
| 832 |
+
self.stream.expect("rbracket")
|
| 833 |
+
if len(args) == 1:
|
| 834 |
+
arg = args[0]
|
| 835 |
+
else:
|
| 836 |
+
arg = nodes.Tuple(args, "load", lineno=token.lineno)
|
| 837 |
+
return nodes.Getitem(node, arg, "load", lineno=token.lineno)
|
| 838 |
+
self.fail("expected subscript expression", token.lineno)
|
| 839 |
+
|
| 840 |
+
def parse_subscribed(self) -> nodes.Expr:
|
| 841 |
+
lineno = self.stream.current.lineno
|
| 842 |
+
args: t.List[t.Optional[nodes.Expr]]
|
| 843 |
+
|
| 844 |
+
if self.stream.current.type == "colon":
|
| 845 |
+
next(self.stream)
|
| 846 |
+
args = [None]
|
| 847 |
+
else:
|
| 848 |
+
node = self.parse_expression()
|
| 849 |
+
if self.stream.current.type != "colon":
|
| 850 |
+
return node
|
| 851 |
+
next(self.stream)
|
| 852 |
+
args = [node]
|
| 853 |
+
|
| 854 |
+
if self.stream.current.type == "colon":
|
| 855 |
+
args.append(None)
|
| 856 |
+
elif self.stream.current.type not in ("rbracket", "comma"):
|
| 857 |
+
args.append(self.parse_expression())
|
| 858 |
+
else:
|
| 859 |
+
args.append(None)
|
| 860 |
+
|
| 861 |
+
if self.stream.current.type == "colon":
|
| 862 |
+
next(self.stream)
|
| 863 |
+
if self.stream.current.type not in ("rbracket", "comma"):
|
| 864 |
+
args.append(self.parse_expression())
|
| 865 |
+
else:
|
| 866 |
+
args.append(None)
|
| 867 |
+
else:
|
| 868 |
+
args.append(None)
|
| 869 |
+
|
| 870 |
+
return nodes.Slice(lineno=lineno, *args) # noqa: B026
|
| 871 |
+
|
| 872 |
+
def parse_call_args(
|
| 873 |
+
self,
|
| 874 |
+
) -> t.Tuple[
|
| 875 |
+
t.List[nodes.Expr],
|
| 876 |
+
t.List[nodes.Keyword],
|
| 877 |
+
t.Optional[nodes.Expr],
|
| 878 |
+
t.Optional[nodes.Expr],
|
| 879 |
+
]:
|
| 880 |
+
token = self.stream.expect("lparen")
|
| 881 |
+
args = []
|
| 882 |
+
kwargs = []
|
| 883 |
+
dyn_args = None
|
| 884 |
+
dyn_kwargs = None
|
| 885 |
+
require_comma = False
|
| 886 |
+
|
| 887 |
+
def ensure(expr: bool) -> None:
|
| 888 |
+
if not expr:
|
| 889 |
+
self.fail("invalid syntax for function call expression", token.lineno)
|
| 890 |
+
|
| 891 |
+
while self.stream.current.type != "rparen":
|
| 892 |
+
if require_comma:
|
| 893 |
+
self.stream.expect("comma")
|
| 894 |
+
|
| 895 |
+
# support for trailing comma
|
| 896 |
+
if self.stream.current.type == "rparen":
|
| 897 |
+
break
|
| 898 |
+
|
| 899 |
+
if self.stream.current.type == "mul":
|
| 900 |
+
ensure(dyn_args is None and dyn_kwargs is None)
|
| 901 |
+
next(self.stream)
|
| 902 |
+
dyn_args = self.parse_expression()
|
| 903 |
+
elif self.stream.current.type == "pow":
|
| 904 |
+
ensure(dyn_kwargs is None)
|
| 905 |
+
next(self.stream)
|
| 906 |
+
dyn_kwargs = self.parse_expression()
|
| 907 |
+
else:
|
| 908 |
+
if (
|
| 909 |
+
self.stream.current.type == "name"
|
| 910 |
+
and self.stream.look().type == "assign"
|
| 911 |
+
):
|
| 912 |
+
# Parsing a kwarg
|
| 913 |
+
ensure(dyn_kwargs is None)
|
| 914 |
+
key = self.stream.current.value
|
| 915 |
+
self.stream.skip(2)
|
| 916 |
+
value = self.parse_expression()
|
| 917 |
+
kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))
|
| 918 |
+
else:
|
| 919 |
+
# Parsing an arg
|
| 920 |
+
ensure(dyn_args is None and dyn_kwargs is None and not kwargs)
|
| 921 |
+
args.append(self.parse_expression())
|
| 922 |
+
|
| 923 |
+
require_comma = True
|
| 924 |
+
|
| 925 |
+
self.stream.expect("rparen")
|
| 926 |
+
return args, kwargs, dyn_args, dyn_kwargs
|
| 927 |
+
|
| 928 |
+
def parse_call(self, node: nodes.Expr) -> nodes.Call:
|
| 929 |
+
# The lparen will be expected in parse_call_args, but the lineno
|
| 930 |
+
# needs to be recorded before the stream is advanced.
|
| 931 |
+
token = self.stream.current
|
| 932 |
+
args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()
|
| 933 |
+
return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)
|
| 934 |
+
|
| 935 |
+
def parse_filter(
|
| 936 |
+
self, node: t.Optional[nodes.Expr], start_inline: bool = False
|
| 937 |
+
) -> t.Optional[nodes.Expr]:
|
| 938 |
+
while self.stream.current.type == "pipe" or start_inline:
|
| 939 |
+
if not start_inline:
|
| 940 |
+
next(self.stream)
|
| 941 |
+
token = self.stream.expect("name")
|
| 942 |
+
name = token.value
|
| 943 |
+
while self.stream.current.type == "dot":
|
| 944 |
+
next(self.stream)
|
| 945 |
+
name += "." + self.stream.expect("name").value
|
| 946 |
+
if self.stream.current.type == "lparen":
|
| 947 |
+
args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()
|
| 948 |
+
else:
|
| 949 |
+
args = []
|
| 950 |
+
kwargs = []
|
| 951 |
+
dyn_args = dyn_kwargs = None
|
| 952 |
+
node = nodes.Filter(
|
| 953 |
+
node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno
|
| 954 |
+
)
|
| 955 |
+
start_inline = False
|
| 956 |
+
return node
|
| 957 |
+
|
| 958 |
+
def parse_test(self, node: nodes.Expr) -> nodes.Expr:
|
| 959 |
+
token = next(self.stream)
|
| 960 |
+
if self.stream.current.test("name:not"):
|
| 961 |
+
next(self.stream)
|
| 962 |
+
negated = True
|
| 963 |
+
else:
|
| 964 |
+
negated = False
|
| 965 |
+
name = self.stream.expect("name").value
|
| 966 |
+
while self.stream.current.type == "dot":
|
| 967 |
+
next(self.stream)
|
| 968 |
+
name += "." + self.stream.expect("name").value
|
| 969 |
+
dyn_args = dyn_kwargs = None
|
| 970 |
+
kwargs: t.List[nodes.Keyword] = []
|
| 971 |
+
if self.stream.current.type == "lparen":
|
| 972 |
+
args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()
|
| 973 |
+
elif self.stream.current.type in {
|
| 974 |
+
"name",
|
| 975 |
+
"string",
|
| 976 |
+
"integer",
|
| 977 |
+
"float",
|
| 978 |
+
"lparen",
|
| 979 |
+
"lbracket",
|
| 980 |
+
"lbrace",
|
| 981 |
+
} and not self.stream.current.test_any("name:else", "name:or", "name:and"):
|
| 982 |
+
if self.stream.current.test("name:is"):
|
| 983 |
+
self.fail("You cannot chain multiple tests with is")
|
| 984 |
+
arg_node = self.parse_primary()
|
| 985 |
+
arg_node = self.parse_postfix(arg_node)
|
| 986 |
+
args = [arg_node]
|
| 987 |
+
else:
|
| 988 |
+
args = []
|
| 989 |
+
node = nodes.Test(
|
| 990 |
+
node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno
|
| 991 |
+
)
|
| 992 |
+
if negated:
|
| 993 |
+
node = nodes.Not(node, lineno=token.lineno)
|
| 994 |
+
return node
|
| 995 |
+
|
| 996 |
+
def subparse(
|
| 997 |
+
self, end_tokens: t.Optional[t.Tuple[str, ...]] = None
|
| 998 |
+
) -> t.List[nodes.Node]:
|
| 999 |
+
body: t.List[nodes.Node] = []
|
| 1000 |
+
data_buffer: t.List[nodes.Node] = []
|
| 1001 |
+
add_data = data_buffer.append
|
| 1002 |
+
|
| 1003 |
+
if end_tokens is not None:
|
| 1004 |
+
self._end_token_stack.append(end_tokens)
|
| 1005 |
+
|
| 1006 |
+
def flush_data() -> None:
|
| 1007 |
+
if data_buffer:
|
| 1008 |
+
lineno = data_buffer[0].lineno
|
| 1009 |
+
body.append(nodes.Output(data_buffer[:], lineno=lineno))
|
| 1010 |
+
del data_buffer[:]
|
| 1011 |
+
|
| 1012 |
+
try:
|
| 1013 |
+
while self.stream:
|
| 1014 |
+
token = self.stream.current
|
| 1015 |
+
if token.type == "data":
|
| 1016 |
+
if token.value:
|
| 1017 |
+
add_data(nodes.TemplateData(token.value, lineno=token.lineno))
|
| 1018 |
+
next(self.stream)
|
| 1019 |
+
elif token.type == "variable_begin":
|
| 1020 |
+
next(self.stream)
|
| 1021 |
+
add_data(self.parse_tuple(with_condexpr=True))
|
| 1022 |
+
self.stream.expect("variable_end")
|
| 1023 |
+
elif token.type == "block_begin":
|
| 1024 |
+
flush_data()
|
| 1025 |
+
next(self.stream)
|
| 1026 |
+
if end_tokens is not None and self.stream.current.test_any(
|
| 1027 |
+
*end_tokens
|
| 1028 |
+
):
|
| 1029 |
+
return body
|
| 1030 |
+
rv = self.parse_statement()
|
| 1031 |
+
if isinstance(rv, list):
|
| 1032 |
+
body.extend(rv)
|
| 1033 |
+
else:
|
| 1034 |
+
body.append(rv)
|
| 1035 |
+
self.stream.expect("block_end")
|
| 1036 |
+
else:
|
| 1037 |
+
raise AssertionError("internal parsing error")
|
| 1038 |
+
|
| 1039 |
+
flush_data()
|
| 1040 |
+
finally:
|
| 1041 |
+
if end_tokens is not None:
|
| 1042 |
+
self._end_token_stack.pop()
|
| 1043 |
+
return body
|
| 1044 |
+
|
| 1045 |
+
def parse(self) -> nodes.Template:
|
| 1046 |
+
"""Parse the whole template into a `Template` node."""
|
| 1047 |
+
result = nodes.Template(self.subparse(), lineno=1)
|
| 1048 |
+
result.set_environment(self.environment)
|
| 1049 |
+
return result
|
wemm/lib/python3.10/site-packages/jinja2/runtime.py
ADDED
|
@@ -0,0 +1,1062 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The runtime functions and state used by compiled templates."""
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import sys
|
| 5 |
+
import typing as t
|
| 6 |
+
from collections import abc
|
| 7 |
+
from itertools import chain
|
| 8 |
+
|
| 9 |
+
from markupsafe import escape # noqa: F401
|
| 10 |
+
from markupsafe import Markup
|
| 11 |
+
from markupsafe import soft_str
|
| 12 |
+
|
| 13 |
+
from .async_utils import auto_aiter
|
| 14 |
+
from .async_utils import auto_await # noqa: F401
|
| 15 |
+
from .exceptions import TemplateNotFound # noqa: F401
|
| 16 |
+
from .exceptions import TemplateRuntimeError # noqa: F401
|
| 17 |
+
from .exceptions import UndefinedError
|
| 18 |
+
from .nodes import EvalContext
|
| 19 |
+
from .utils import _PassArg
|
| 20 |
+
from .utils import concat
|
| 21 |
+
from .utils import internalcode
|
| 22 |
+
from .utils import missing
|
| 23 |
+
from .utils import Namespace # noqa: F401
|
| 24 |
+
from .utils import object_type_repr
|
| 25 |
+
from .utils import pass_eval_context
|
| 26 |
+
|
| 27 |
+
V = t.TypeVar("V")
|
| 28 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
| 29 |
+
|
| 30 |
+
if t.TYPE_CHECKING:
|
| 31 |
+
import logging
|
| 32 |
+
|
| 33 |
+
import typing_extensions as te
|
| 34 |
+
|
| 35 |
+
from .environment import Environment
|
| 36 |
+
|
| 37 |
+
class LoopRenderFunc(te.Protocol):
|
| 38 |
+
def __call__(
|
| 39 |
+
self,
|
| 40 |
+
reciter: t.Iterable[V],
|
| 41 |
+
loop_render_func: "LoopRenderFunc",
|
| 42 |
+
depth: int = 0,
|
| 43 |
+
) -> str: ...
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# these variables are exported to the template runtime
|
| 47 |
+
exported = [
|
| 48 |
+
"LoopContext",
|
| 49 |
+
"TemplateReference",
|
| 50 |
+
"Macro",
|
| 51 |
+
"Markup",
|
| 52 |
+
"TemplateRuntimeError",
|
| 53 |
+
"missing",
|
| 54 |
+
"escape",
|
| 55 |
+
"markup_join",
|
| 56 |
+
"str_join",
|
| 57 |
+
"identity",
|
| 58 |
+
"TemplateNotFound",
|
| 59 |
+
"Namespace",
|
| 60 |
+
"Undefined",
|
| 61 |
+
"internalcode",
|
| 62 |
+
]
|
| 63 |
+
async_exported = [
|
| 64 |
+
"AsyncLoopContext",
|
| 65 |
+
"auto_aiter",
|
| 66 |
+
"auto_await",
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def identity(x: V) -> V:
|
| 71 |
+
"""Returns its argument. Useful for certain things in the
|
| 72 |
+
environment.
|
| 73 |
+
"""
|
| 74 |
+
return x
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def markup_join(seq: t.Iterable[t.Any]) -> str:
|
| 78 |
+
"""Concatenation that escapes if necessary and converts to string."""
|
| 79 |
+
buf = []
|
| 80 |
+
iterator = map(soft_str, seq)
|
| 81 |
+
for arg in iterator:
|
| 82 |
+
buf.append(arg)
|
| 83 |
+
if hasattr(arg, "__html__"):
|
| 84 |
+
return Markup("").join(chain(buf, iterator))
|
| 85 |
+
return concat(buf)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def str_join(seq: t.Iterable[t.Any]) -> str:
|
| 89 |
+
"""Simple args to string conversion and concatenation."""
|
| 90 |
+
return concat(map(str, seq))
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def new_context(
|
| 94 |
+
environment: "Environment",
|
| 95 |
+
template_name: t.Optional[str],
|
| 96 |
+
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
|
| 97 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
| 98 |
+
shared: bool = False,
|
| 99 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 100 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
| 101 |
+
) -> "Context":
|
| 102 |
+
"""Internal helper for context creation."""
|
| 103 |
+
if vars is None:
|
| 104 |
+
vars = {}
|
| 105 |
+
if shared:
|
| 106 |
+
parent = vars
|
| 107 |
+
else:
|
| 108 |
+
parent = dict(globals or (), **vars)
|
| 109 |
+
if locals:
|
| 110 |
+
# if the parent is shared a copy should be created because
|
| 111 |
+
# we don't want to modify the dict passed
|
| 112 |
+
if shared:
|
| 113 |
+
parent = dict(parent)
|
| 114 |
+
for key, value in locals.items():
|
| 115 |
+
if value is not missing:
|
| 116 |
+
parent[key] = value
|
| 117 |
+
return environment.context_class(
|
| 118 |
+
environment, parent, template_name, blocks, globals=globals
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class TemplateReference:
|
| 123 |
+
"""The `self` in templates."""
|
| 124 |
+
|
| 125 |
+
def __init__(self, context: "Context") -> None:
|
| 126 |
+
self.__context = context
|
| 127 |
+
|
| 128 |
+
def __getitem__(self, name: str) -> t.Any:
|
| 129 |
+
blocks = self.__context.blocks[name]
|
| 130 |
+
return BlockReference(name, self.__context, blocks, 0)
|
| 131 |
+
|
| 132 |
+
def __repr__(self) -> str:
|
| 133 |
+
return f"<{type(self).__name__} {self.__context.name!r}>"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _dict_method_all(dict_method: F) -> F:
|
| 137 |
+
@functools.wraps(dict_method)
|
| 138 |
+
def f_all(self: "Context") -> t.Any:
|
| 139 |
+
return dict_method(self.get_all())
|
| 140 |
+
|
| 141 |
+
return t.cast(F, f_all)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@abc.Mapping.register
|
| 145 |
+
class Context:
|
| 146 |
+
"""The template context holds the variables of a template. It stores the
|
| 147 |
+
values passed to the template and also the names the template exports.
|
| 148 |
+
Creating instances is neither supported nor useful as it's created
|
| 149 |
+
automatically at various stages of the template evaluation and should not
|
| 150 |
+
be created by hand.
|
| 151 |
+
|
| 152 |
+
The context is immutable. Modifications on :attr:`parent` **must not**
|
| 153 |
+
happen and modifications on :attr:`vars` are allowed from generated
|
| 154 |
+
template code only. Template filters and global functions marked as
|
| 155 |
+
:func:`pass_context` get the active context passed as first argument
|
| 156 |
+
and are allowed to access the context read-only.
|
| 157 |
+
|
| 158 |
+
The template context supports read only dict operations (`get`,
|
| 159 |
+
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
|
| 160 |
+
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
|
| 161 |
+
method that doesn't fail with a `KeyError` but returns an
|
| 162 |
+
:class:`Undefined` object for missing variables.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
def __init__(
|
| 166 |
+
self,
|
| 167 |
+
environment: "Environment",
|
| 168 |
+
parent: t.Dict[str, t.Any],
|
| 169 |
+
name: t.Optional[str],
|
| 170 |
+
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
|
| 171 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
| 172 |
+
):
|
| 173 |
+
self.parent = parent
|
| 174 |
+
self.vars: t.Dict[str, t.Any] = {}
|
| 175 |
+
self.environment: Environment = environment
|
| 176 |
+
self.eval_ctx = EvalContext(self.environment, name)
|
| 177 |
+
self.exported_vars: t.Set[str] = set()
|
| 178 |
+
self.name = name
|
| 179 |
+
self.globals_keys = set() if globals is None else set(globals)
|
| 180 |
+
|
| 181 |
+
# create the initial mapping of blocks. Whenever template inheritance
|
| 182 |
+
# takes place the runtime will update this mapping with the new blocks
|
| 183 |
+
# from the template.
|
| 184 |
+
self.blocks = {k: [v] for k, v in blocks.items()}
|
| 185 |
+
|
| 186 |
+
def super(
|
| 187 |
+
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
|
| 188 |
+
) -> t.Union["BlockReference", "Undefined"]:
|
| 189 |
+
"""Render a parent block."""
|
| 190 |
+
try:
|
| 191 |
+
blocks = self.blocks[name]
|
| 192 |
+
index = blocks.index(current) + 1
|
| 193 |
+
blocks[index]
|
| 194 |
+
except LookupError:
|
| 195 |
+
return self.environment.undefined(
|
| 196 |
+
f"there is no parent block called {name!r}.", name="super"
|
| 197 |
+
)
|
| 198 |
+
return BlockReference(name, self, blocks, index)
|
| 199 |
+
|
| 200 |
+
def get(self, key: str, default: t.Any = None) -> t.Any:
|
| 201 |
+
"""Look up a variable by name, or return a default if the key is
|
| 202 |
+
not found.
|
| 203 |
+
|
| 204 |
+
:param key: The variable name to look up.
|
| 205 |
+
:param default: The value to return if the key is not found.
|
| 206 |
+
"""
|
| 207 |
+
try:
|
| 208 |
+
return self[key]
|
| 209 |
+
except KeyError:
|
| 210 |
+
return default
|
| 211 |
+
|
| 212 |
+
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
|
| 213 |
+
"""Look up a variable by name, or return an :class:`Undefined`
|
| 214 |
+
object if the key is not found.
|
| 215 |
+
|
| 216 |
+
If you need to add custom behavior, override
|
| 217 |
+
:meth:`resolve_or_missing`, not this method. The various lookup
|
| 218 |
+
functions use that method, not this one.
|
| 219 |
+
|
| 220 |
+
:param key: The variable name to look up.
|
| 221 |
+
"""
|
| 222 |
+
rv = self.resolve_or_missing(key)
|
| 223 |
+
|
| 224 |
+
if rv is missing:
|
| 225 |
+
return self.environment.undefined(name=key)
|
| 226 |
+
|
| 227 |
+
return rv
|
| 228 |
+
|
| 229 |
+
def resolve_or_missing(self, key: str) -> t.Any:
|
| 230 |
+
"""Look up a variable by name, or return a ``missing`` sentinel
|
| 231 |
+
if the key is not found.
|
| 232 |
+
|
| 233 |
+
Override this method to add custom lookup behavior.
|
| 234 |
+
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
|
| 235 |
+
method. Don't call this method directly.
|
| 236 |
+
|
| 237 |
+
:param key: The variable name to look up.
|
| 238 |
+
"""
|
| 239 |
+
if key in self.vars:
|
| 240 |
+
return self.vars[key]
|
| 241 |
+
|
| 242 |
+
if key in self.parent:
|
| 243 |
+
return self.parent[key]
|
| 244 |
+
|
| 245 |
+
return missing
|
| 246 |
+
|
| 247 |
+
def get_exported(self) -> t.Dict[str, t.Any]:
|
| 248 |
+
"""Get a new dict with the exported variables."""
|
| 249 |
+
return {k: self.vars[k] for k in self.exported_vars}
|
| 250 |
+
|
| 251 |
+
def get_all(self) -> t.Dict[str, t.Any]:
|
| 252 |
+
"""Return the complete context as dict including the exported
|
| 253 |
+
variables. For optimizations reasons this might not return an
|
| 254 |
+
actual copy so be careful with using it.
|
| 255 |
+
"""
|
| 256 |
+
if not self.vars:
|
| 257 |
+
return self.parent
|
| 258 |
+
if not self.parent:
|
| 259 |
+
return self.vars
|
| 260 |
+
return dict(self.parent, **self.vars)
|
| 261 |
+
|
| 262 |
+
@internalcode
|
| 263 |
+
def call(
|
| 264 |
+
__self,
|
| 265 |
+
__obj: t.Callable[..., t.Any],
|
| 266 |
+
*args: t.Any,
|
| 267 |
+
**kwargs: t.Any, # noqa: B902
|
| 268 |
+
) -> t.Union[t.Any, "Undefined"]:
|
| 269 |
+
"""Call the callable with the arguments and keyword arguments
|
| 270 |
+
provided but inject the active context or environment as first
|
| 271 |
+
argument if the callable has :func:`pass_context` or
|
| 272 |
+
:func:`pass_environment`.
|
| 273 |
+
"""
|
| 274 |
+
if __debug__:
|
| 275 |
+
__traceback_hide__ = True # noqa
|
| 276 |
+
|
| 277 |
+
# Allow callable classes to take a context
|
| 278 |
+
if (
|
| 279 |
+
hasattr(__obj, "__call__") # noqa: B004
|
| 280 |
+
and _PassArg.from_obj(__obj.__call__) is not None
|
| 281 |
+
):
|
| 282 |
+
__obj = __obj.__call__
|
| 283 |
+
|
| 284 |
+
pass_arg = _PassArg.from_obj(__obj)
|
| 285 |
+
|
| 286 |
+
if pass_arg is _PassArg.context:
|
| 287 |
+
# the active context should have access to variables set in
|
| 288 |
+
# loops and blocks without mutating the context itself
|
| 289 |
+
if kwargs.get("_loop_vars"):
|
| 290 |
+
__self = __self.derived(kwargs["_loop_vars"])
|
| 291 |
+
if kwargs.get("_block_vars"):
|
| 292 |
+
__self = __self.derived(kwargs["_block_vars"])
|
| 293 |
+
args = (__self,) + args
|
| 294 |
+
elif pass_arg is _PassArg.eval_context:
|
| 295 |
+
args = (__self.eval_ctx,) + args
|
| 296 |
+
elif pass_arg is _PassArg.environment:
|
| 297 |
+
args = (__self.environment,) + args
|
| 298 |
+
|
| 299 |
+
kwargs.pop("_block_vars", None)
|
| 300 |
+
kwargs.pop("_loop_vars", None)
|
| 301 |
+
|
| 302 |
+
try:
|
| 303 |
+
return __obj(*args, **kwargs)
|
| 304 |
+
except StopIteration:
|
| 305 |
+
return __self.environment.undefined(
|
| 306 |
+
"value was undefined because a callable raised a"
|
| 307 |
+
" StopIteration exception"
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
|
| 311 |
+
"""Internal helper function to create a derived context. This is
|
| 312 |
+
used in situations where the system needs a new context in the same
|
| 313 |
+
template that is independent.
|
| 314 |
+
"""
|
| 315 |
+
context = new_context(
|
| 316 |
+
self.environment, self.name, {}, self.get_all(), True, None, locals
|
| 317 |
+
)
|
| 318 |
+
context.eval_ctx = self.eval_ctx
|
| 319 |
+
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
|
| 320 |
+
return context
|
| 321 |
+
|
| 322 |
+
keys = _dict_method_all(dict.keys)
|
| 323 |
+
values = _dict_method_all(dict.values)
|
| 324 |
+
items = _dict_method_all(dict.items)
|
| 325 |
+
|
| 326 |
+
def __contains__(self, name: str) -> bool:
|
| 327 |
+
return name in self.vars or name in self.parent
|
| 328 |
+
|
| 329 |
+
def __getitem__(self, key: str) -> t.Any:
|
| 330 |
+
"""Look up a variable by name with ``[]`` syntax, or raise a
|
| 331 |
+
``KeyError`` if the key is not found.
|
| 332 |
+
"""
|
| 333 |
+
item = self.resolve_or_missing(key)
|
| 334 |
+
|
| 335 |
+
if item is missing:
|
| 336 |
+
raise KeyError(key)
|
| 337 |
+
|
| 338 |
+
return item
|
| 339 |
+
|
| 340 |
+
def __repr__(self) -> str:
|
| 341 |
+
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class BlockReference:
|
| 345 |
+
"""One block on a template reference."""
|
| 346 |
+
|
| 347 |
+
def __init__(
|
| 348 |
+
self,
|
| 349 |
+
name: str,
|
| 350 |
+
context: "Context",
|
| 351 |
+
stack: t.List[t.Callable[["Context"], t.Iterator[str]]],
|
| 352 |
+
depth: int,
|
| 353 |
+
) -> None:
|
| 354 |
+
self.name = name
|
| 355 |
+
self._context = context
|
| 356 |
+
self._stack = stack
|
| 357 |
+
self._depth = depth
|
| 358 |
+
|
| 359 |
+
@property
|
| 360 |
+
def super(self) -> t.Union["BlockReference", "Undefined"]:
|
| 361 |
+
"""Super the block."""
|
| 362 |
+
if self._depth + 1 >= len(self._stack):
|
| 363 |
+
return self._context.environment.undefined(
|
| 364 |
+
f"there is no parent block called {self.name!r}.", name="super"
|
| 365 |
+
)
|
| 366 |
+
return BlockReference(self.name, self._context, self._stack, self._depth + 1)
|
| 367 |
+
|
| 368 |
+
@internalcode
|
| 369 |
+
async def _async_call(self) -> str:
|
| 370 |
+
rv = self._context.environment.concat( # type: ignore
|
| 371 |
+
[x async for x in self._stack[self._depth](self._context)] # type: ignore
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
if self._context.eval_ctx.autoescape:
|
| 375 |
+
return Markup(rv)
|
| 376 |
+
|
| 377 |
+
return rv
|
| 378 |
+
|
| 379 |
+
@internalcode
|
| 380 |
+
def __call__(self) -> str:
|
| 381 |
+
if self._context.environment.is_async:
|
| 382 |
+
return self._async_call() # type: ignore
|
| 383 |
+
|
| 384 |
+
rv = self._context.environment.concat( # type: ignore
|
| 385 |
+
self._stack[self._depth](self._context)
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
if self._context.eval_ctx.autoescape:
|
| 389 |
+
return Markup(rv)
|
| 390 |
+
|
| 391 |
+
return rv
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class LoopContext:
|
| 395 |
+
"""A wrapper iterable for dynamic ``for`` loops, with information
|
| 396 |
+
about the loop and iteration.
|
| 397 |
+
"""
|
| 398 |
+
|
| 399 |
+
#: Current iteration of the loop, starting at 0.
|
| 400 |
+
index0 = -1
|
| 401 |
+
|
| 402 |
+
_length: t.Optional[int] = None
|
| 403 |
+
_after: t.Any = missing
|
| 404 |
+
_current: t.Any = missing
|
| 405 |
+
_before: t.Any = missing
|
| 406 |
+
_last_changed_value: t.Any = missing
|
| 407 |
+
|
| 408 |
+
def __init__(
|
| 409 |
+
self,
|
| 410 |
+
iterable: t.Iterable[V],
|
| 411 |
+
undefined: t.Type["Undefined"],
|
| 412 |
+
recurse: t.Optional["LoopRenderFunc"] = None,
|
| 413 |
+
depth0: int = 0,
|
| 414 |
+
) -> None:
|
| 415 |
+
"""
|
| 416 |
+
:param iterable: Iterable to wrap.
|
| 417 |
+
:param undefined: :class:`Undefined` class to use for next and
|
| 418 |
+
previous items.
|
| 419 |
+
:param recurse: The function to render the loop body when the
|
| 420 |
+
loop is marked recursive.
|
| 421 |
+
:param depth0: Incremented when looping recursively.
|
| 422 |
+
"""
|
| 423 |
+
self._iterable = iterable
|
| 424 |
+
self._iterator = self._to_iterator(iterable)
|
| 425 |
+
self._undefined = undefined
|
| 426 |
+
self._recurse = recurse
|
| 427 |
+
#: How many levels deep a recursive loop currently is, starting at 0.
|
| 428 |
+
self.depth0 = depth0
|
| 429 |
+
|
| 430 |
+
@staticmethod
|
| 431 |
+
def _to_iterator(iterable: t.Iterable[V]) -> t.Iterator[V]:
|
| 432 |
+
return iter(iterable)
|
| 433 |
+
|
| 434 |
+
@property
|
| 435 |
+
def length(self) -> int:
|
| 436 |
+
"""Length of the iterable.
|
| 437 |
+
|
| 438 |
+
If the iterable is a generator or otherwise does not have a
|
| 439 |
+
size, it is eagerly evaluated to get a size.
|
| 440 |
+
"""
|
| 441 |
+
if self._length is not None:
|
| 442 |
+
return self._length
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
self._length = len(self._iterable) # type: ignore
|
| 446 |
+
except TypeError:
|
| 447 |
+
iterable = list(self._iterator)
|
| 448 |
+
self._iterator = self._to_iterator(iterable)
|
| 449 |
+
self._length = len(iterable) + self.index + (self._after is not missing)
|
| 450 |
+
|
| 451 |
+
return self._length
|
| 452 |
+
|
| 453 |
+
def __len__(self) -> int:
|
| 454 |
+
return self.length
|
| 455 |
+
|
| 456 |
+
@property
|
| 457 |
+
def depth(self) -> int:
|
| 458 |
+
"""How many levels deep a recursive loop currently is, starting at 1."""
|
| 459 |
+
return self.depth0 + 1
|
| 460 |
+
|
| 461 |
+
@property
|
| 462 |
+
def index(self) -> int:
|
| 463 |
+
"""Current iteration of the loop, starting at 1."""
|
| 464 |
+
return self.index0 + 1
|
| 465 |
+
|
| 466 |
+
@property
|
| 467 |
+
def revindex0(self) -> int:
|
| 468 |
+
"""Number of iterations from the end of the loop, ending at 0.
|
| 469 |
+
|
| 470 |
+
Requires calculating :attr:`length`.
|
| 471 |
+
"""
|
| 472 |
+
return self.length - self.index
|
| 473 |
+
|
| 474 |
+
@property
|
| 475 |
+
def revindex(self) -> int:
|
| 476 |
+
"""Number of iterations from the end of the loop, ending at 1.
|
| 477 |
+
|
| 478 |
+
Requires calculating :attr:`length`.
|
| 479 |
+
"""
|
| 480 |
+
return self.length - self.index0
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def first(self) -> bool:
|
| 484 |
+
"""Whether this is the first iteration of the loop."""
|
| 485 |
+
return self.index0 == 0
|
| 486 |
+
|
| 487 |
+
def _peek_next(self) -> t.Any:
|
| 488 |
+
"""Return the next element in the iterable, or :data:`missing`
|
| 489 |
+
if the iterable is exhausted. Only peeks one item ahead, caching
|
| 490 |
+
the result in :attr:`_last` for use in subsequent checks. The
|
| 491 |
+
cache is reset when :meth:`__next__` is called.
|
| 492 |
+
"""
|
| 493 |
+
if self._after is not missing:
|
| 494 |
+
return self._after
|
| 495 |
+
|
| 496 |
+
self._after = next(self._iterator, missing)
|
| 497 |
+
return self._after
|
| 498 |
+
|
| 499 |
+
@property
|
| 500 |
+
def last(self) -> bool:
|
| 501 |
+
"""Whether this is the last iteration of the loop.
|
| 502 |
+
|
| 503 |
+
Causes the iterable to advance early. See
|
| 504 |
+
:func:`itertools.groupby` for issues this can cause.
|
| 505 |
+
The :func:`groupby` filter avoids that issue.
|
| 506 |
+
"""
|
| 507 |
+
return self._peek_next() is missing
|
| 508 |
+
|
| 509 |
+
@property
|
| 510 |
+
def previtem(self) -> t.Union[t.Any, "Undefined"]:
|
| 511 |
+
"""The item in the previous iteration. Undefined during the
|
| 512 |
+
first iteration.
|
| 513 |
+
"""
|
| 514 |
+
if self.first:
|
| 515 |
+
return self._undefined("there is no previous item")
|
| 516 |
+
|
| 517 |
+
return self._before
|
| 518 |
+
|
| 519 |
+
@property
|
| 520 |
+
def nextitem(self) -> t.Union[t.Any, "Undefined"]:
|
| 521 |
+
"""The item in the next iteration. Undefined during the last
|
| 522 |
+
iteration.
|
| 523 |
+
|
| 524 |
+
Causes the iterable to advance early. See
|
| 525 |
+
:func:`itertools.groupby` for issues this can cause.
|
| 526 |
+
The :func:`jinja-filters.groupby` filter avoids that issue.
|
| 527 |
+
"""
|
| 528 |
+
rv = self._peek_next()
|
| 529 |
+
|
| 530 |
+
if rv is missing:
|
| 531 |
+
return self._undefined("there is no next item")
|
| 532 |
+
|
| 533 |
+
return rv
|
| 534 |
+
|
| 535 |
+
def cycle(self, *args: V) -> V:
|
| 536 |
+
"""Return a value from the given args, cycling through based on
|
| 537 |
+
the current :attr:`index0`.
|
| 538 |
+
|
| 539 |
+
:param args: One or more values to cycle through.
|
| 540 |
+
"""
|
| 541 |
+
if not args:
|
| 542 |
+
raise TypeError("no items for cycling given")
|
| 543 |
+
|
| 544 |
+
return args[self.index0 % len(args)]
|
| 545 |
+
|
| 546 |
+
def changed(self, *value: t.Any) -> bool:
|
| 547 |
+
"""Return ``True`` if previously called with a different value
|
| 548 |
+
(including when called for the first time).
|
| 549 |
+
|
| 550 |
+
:param value: One or more values to compare to the last call.
|
| 551 |
+
"""
|
| 552 |
+
if self._last_changed_value != value:
|
| 553 |
+
self._last_changed_value = value
|
| 554 |
+
return True
|
| 555 |
+
|
| 556 |
+
return False
|
| 557 |
+
|
| 558 |
+
def __iter__(self) -> "LoopContext":
|
| 559 |
+
return self
|
| 560 |
+
|
| 561 |
+
def __next__(self) -> t.Tuple[t.Any, "LoopContext"]:
|
| 562 |
+
if self._after is not missing:
|
| 563 |
+
rv = self._after
|
| 564 |
+
self._after = missing
|
| 565 |
+
else:
|
| 566 |
+
rv = next(self._iterator)
|
| 567 |
+
|
| 568 |
+
self.index0 += 1
|
| 569 |
+
self._before = self._current
|
| 570 |
+
self._current = rv
|
| 571 |
+
return rv, self
|
| 572 |
+
|
| 573 |
+
@internalcode
|
| 574 |
+
def __call__(self, iterable: t.Iterable[V]) -> str:
|
| 575 |
+
"""When iterating over nested data, render the body of the loop
|
| 576 |
+
recursively with the given inner iterable data.
|
| 577 |
+
|
| 578 |
+
The loop must have the ``recursive`` marker for this to work.
|
| 579 |
+
"""
|
| 580 |
+
if self._recurse is None:
|
| 581 |
+
raise TypeError(
|
| 582 |
+
"The loop must have the 'recursive' marker to be called recursively."
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
return self._recurse(iterable, self._recurse, depth=self.depth)
|
| 586 |
+
|
| 587 |
+
def __repr__(self) -> str:
|
| 588 |
+
return f"<{type(self).__name__} {self.index}/{self.length}>"
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
class AsyncLoopContext(LoopContext):
|
| 592 |
+
_iterator: t.AsyncIterator[t.Any] # type: ignore
|
| 593 |
+
|
| 594 |
+
@staticmethod
|
| 595 |
+
def _to_iterator( # type: ignore
|
| 596 |
+
iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]],
|
| 597 |
+
) -> t.AsyncIterator[V]:
|
| 598 |
+
return auto_aiter(iterable)
|
| 599 |
+
|
| 600 |
+
@property
|
| 601 |
+
async def length(self) -> int: # type: ignore
|
| 602 |
+
if self._length is not None:
|
| 603 |
+
return self._length
|
| 604 |
+
|
| 605 |
+
try:
|
| 606 |
+
self._length = len(self._iterable) # type: ignore
|
| 607 |
+
except TypeError:
|
| 608 |
+
iterable = [x async for x in self._iterator]
|
| 609 |
+
self._iterator = self._to_iterator(iterable)
|
| 610 |
+
self._length = len(iterable) + self.index + (self._after is not missing)
|
| 611 |
+
|
| 612 |
+
return self._length
|
| 613 |
+
|
| 614 |
+
@property
|
| 615 |
+
async def revindex0(self) -> int: # type: ignore
|
| 616 |
+
return await self.length - self.index
|
| 617 |
+
|
| 618 |
+
@property
|
| 619 |
+
async def revindex(self) -> int: # type: ignore
|
| 620 |
+
return await self.length - self.index0
|
| 621 |
+
|
| 622 |
+
async def _peek_next(self) -> t.Any:
|
| 623 |
+
if self._after is not missing:
|
| 624 |
+
return self._after
|
| 625 |
+
|
| 626 |
+
try:
|
| 627 |
+
self._after = await self._iterator.__anext__()
|
| 628 |
+
except StopAsyncIteration:
|
| 629 |
+
self._after = missing
|
| 630 |
+
|
| 631 |
+
return self._after
|
| 632 |
+
|
| 633 |
+
@property
|
| 634 |
+
async def last(self) -> bool: # type: ignore
|
| 635 |
+
return await self._peek_next() is missing
|
| 636 |
+
|
| 637 |
+
@property
|
| 638 |
+
async def nextitem(self) -> t.Union[t.Any, "Undefined"]:
|
| 639 |
+
rv = await self._peek_next()
|
| 640 |
+
|
| 641 |
+
if rv is missing:
|
| 642 |
+
return self._undefined("there is no next item")
|
| 643 |
+
|
| 644 |
+
return rv
|
| 645 |
+
|
| 646 |
+
def __aiter__(self) -> "AsyncLoopContext":
|
| 647 |
+
return self
|
| 648 |
+
|
| 649 |
+
async def __anext__(self) -> t.Tuple[t.Any, "AsyncLoopContext"]:
|
| 650 |
+
if self._after is not missing:
|
| 651 |
+
rv = self._after
|
| 652 |
+
self._after = missing
|
| 653 |
+
else:
|
| 654 |
+
rv = await self._iterator.__anext__()
|
| 655 |
+
|
| 656 |
+
self.index0 += 1
|
| 657 |
+
self._before = self._current
|
| 658 |
+
self._current = rv
|
| 659 |
+
return rv, self
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
class Macro:
|
| 663 |
+
"""Wraps a macro function."""
|
| 664 |
+
|
| 665 |
+
def __init__(
|
| 666 |
+
self,
|
| 667 |
+
environment: "Environment",
|
| 668 |
+
func: t.Callable[..., str],
|
| 669 |
+
name: str,
|
| 670 |
+
arguments: t.List[str],
|
| 671 |
+
catch_kwargs: bool,
|
| 672 |
+
catch_varargs: bool,
|
| 673 |
+
caller: bool,
|
| 674 |
+
default_autoescape: t.Optional[bool] = None,
|
| 675 |
+
):
|
| 676 |
+
self._environment = environment
|
| 677 |
+
self._func = func
|
| 678 |
+
self._argument_count = len(arguments)
|
| 679 |
+
self.name = name
|
| 680 |
+
self.arguments = arguments
|
| 681 |
+
self.catch_kwargs = catch_kwargs
|
| 682 |
+
self.catch_varargs = catch_varargs
|
| 683 |
+
self.caller = caller
|
| 684 |
+
self.explicit_caller = "caller" in arguments
|
| 685 |
+
|
| 686 |
+
if default_autoescape is None:
|
| 687 |
+
if callable(environment.autoescape):
|
| 688 |
+
default_autoescape = environment.autoescape(None)
|
| 689 |
+
else:
|
| 690 |
+
default_autoescape = environment.autoescape
|
| 691 |
+
|
| 692 |
+
self._default_autoescape = default_autoescape
|
| 693 |
+
|
| 694 |
+
@internalcode
|
| 695 |
+
@pass_eval_context
|
| 696 |
+
def __call__(self, *args: t.Any, **kwargs: t.Any) -> str:
|
| 697 |
+
# This requires a bit of explanation, In the past we used to
|
| 698 |
+
# decide largely based on compile-time information if a macro is
|
| 699 |
+
# safe or unsafe. While there was a volatile mode it was largely
|
| 700 |
+
# unused for deciding on escaping. This turns out to be
|
| 701 |
+
# problematic for macros because whether a macro is safe depends not
|
| 702 |
+
# on the escape mode when it was defined, but rather when it was used.
|
| 703 |
+
#
|
| 704 |
+
# Because however we export macros from the module system and
|
| 705 |
+
# there are historic callers that do not pass an eval context (and
|
| 706 |
+
# will continue to not pass one), we need to perform an instance
|
| 707 |
+
# check here.
|
| 708 |
+
#
|
| 709 |
+
# This is considered safe because an eval context is not a valid
|
| 710 |
+
# argument to callables otherwise anyway. Worst case here is
|
| 711 |
+
# that if no eval context is passed we fall back to the compile
|
| 712 |
+
# time autoescape flag.
|
| 713 |
+
if args and isinstance(args[0], EvalContext):
|
| 714 |
+
autoescape = args[0].autoescape
|
| 715 |
+
args = args[1:]
|
| 716 |
+
else:
|
| 717 |
+
autoescape = self._default_autoescape
|
| 718 |
+
|
| 719 |
+
# try to consume the positional arguments
|
| 720 |
+
arguments = list(args[: self._argument_count])
|
| 721 |
+
off = len(arguments)
|
| 722 |
+
|
| 723 |
+
# For information why this is necessary refer to the handling
|
| 724 |
+
# of caller in the `macro_body` handler in the compiler.
|
| 725 |
+
found_caller = False
|
| 726 |
+
|
| 727 |
+
# if the number of arguments consumed is not the number of
|
| 728 |
+
# arguments expected we start filling in keyword arguments
|
| 729 |
+
# and defaults.
|
| 730 |
+
if off != self._argument_count:
|
| 731 |
+
for name in self.arguments[len(arguments) :]:
|
| 732 |
+
try:
|
| 733 |
+
value = kwargs.pop(name)
|
| 734 |
+
except KeyError:
|
| 735 |
+
value = missing
|
| 736 |
+
if name == "caller":
|
| 737 |
+
found_caller = True
|
| 738 |
+
arguments.append(value)
|
| 739 |
+
else:
|
| 740 |
+
found_caller = self.explicit_caller
|
| 741 |
+
|
| 742 |
+
# it's important that the order of these arguments does not change
|
| 743 |
+
# if not also changed in the compiler's `function_scoping` method.
|
| 744 |
+
# the order is caller, keyword arguments, positional arguments!
|
| 745 |
+
if self.caller and not found_caller:
|
| 746 |
+
caller = kwargs.pop("caller", None)
|
| 747 |
+
if caller is None:
|
| 748 |
+
caller = self._environment.undefined("No caller defined", name="caller")
|
| 749 |
+
arguments.append(caller)
|
| 750 |
+
|
| 751 |
+
if self.catch_kwargs:
|
| 752 |
+
arguments.append(kwargs)
|
| 753 |
+
elif kwargs:
|
| 754 |
+
if "caller" in kwargs:
|
| 755 |
+
raise TypeError(
|
| 756 |
+
f"macro {self.name!r} was invoked with two values for the special"
|
| 757 |
+
" caller argument. This is most likely a bug."
|
| 758 |
+
)
|
| 759 |
+
raise TypeError(
|
| 760 |
+
f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"
|
| 761 |
+
)
|
| 762 |
+
if self.catch_varargs:
|
| 763 |
+
arguments.append(args[self._argument_count :])
|
| 764 |
+
elif len(args) > self._argument_count:
|
| 765 |
+
raise TypeError(
|
| 766 |
+
f"macro {self.name!r} takes not more than"
|
| 767 |
+
f" {len(self.arguments)} argument(s)"
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
return self._invoke(arguments, autoescape)
|
| 771 |
+
|
| 772 |
+
async def _async_invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:
|
| 773 |
+
rv = await self._func(*arguments) # type: ignore
|
| 774 |
+
|
| 775 |
+
if autoescape:
|
| 776 |
+
return Markup(rv)
|
| 777 |
+
|
| 778 |
+
return rv # type: ignore
|
| 779 |
+
|
| 780 |
+
def _invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:
|
| 781 |
+
if self._environment.is_async:
|
| 782 |
+
return self._async_invoke(arguments, autoescape) # type: ignore
|
| 783 |
+
|
| 784 |
+
rv = self._func(*arguments)
|
| 785 |
+
|
| 786 |
+
if autoescape:
|
| 787 |
+
rv = Markup(rv)
|
| 788 |
+
|
| 789 |
+
return rv
|
| 790 |
+
|
| 791 |
+
def __repr__(self) -> str:
|
| 792 |
+
name = "anonymous" if self.name is None else repr(self.name)
|
| 793 |
+
return f"<{type(self).__name__} {name}>"
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
class Undefined:
|
| 797 |
+
"""The default undefined type. This can be printed, iterated, and treated as
|
| 798 |
+
a boolean. Any other operation will raise an :exc:`UndefinedError`.
|
| 799 |
+
|
| 800 |
+
>>> foo = Undefined(name='foo')
|
| 801 |
+
>>> str(foo)
|
| 802 |
+
''
|
| 803 |
+
>>> not foo
|
| 804 |
+
True
|
| 805 |
+
>>> foo + 42
|
| 806 |
+
Traceback (most recent call last):
|
| 807 |
+
...
|
| 808 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
| 809 |
+
"""
|
| 810 |
+
|
| 811 |
+
__slots__ = (
|
| 812 |
+
"_undefined_hint",
|
| 813 |
+
"_undefined_obj",
|
| 814 |
+
"_undefined_name",
|
| 815 |
+
"_undefined_exception",
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
def __init__(
|
| 819 |
+
self,
|
| 820 |
+
hint: t.Optional[str] = None,
|
| 821 |
+
obj: t.Any = missing,
|
| 822 |
+
name: t.Optional[str] = None,
|
| 823 |
+
exc: t.Type[TemplateRuntimeError] = UndefinedError,
|
| 824 |
+
) -> None:
|
| 825 |
+
self._undefined_hint = hint
|
| 826 |
+
self._undefined_obj = obj
|
| 827 |
+
self._undefined_name = name
|
| 828 |
+
self._undefined_exception = exc
|
| 829 |
+
|
| 830 |
+
@property
|
| 831 |
+
def _undefined_message(self) -> str:
|
| 832 |
+
"""Build a message about the undefined value based on how it was
|
| 833 |
+
accessed.
|
| 834 |
+
"""
|
| 835 |
+
if self._undefined_hint:
|
| 836 |
+
return self._undefined_hint
|
| 837 |
+
|
| 838 |
+
if self._undefined_obj is missing:
|
| 839 |
+
return f"{self._undefined_name!r} is undefined"
|
| 840 |
+
|
| 841 |
+
if not isinstance(self._undefined_name, str):
|
| 842 |
+
return (
|
| 843 |
+
f"{object_type_repr(self._undefined_obj)} has no"
|
| 844 |
+
f" element {self._undefined_name!r}"
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
return (
|
| 848 |
+
f"{object_type_repr(self._undefined_obj)!r} has no"
|
| 849 |
+
f" attribute {self._undefined_name!r}"
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
@internalcode
|
| 853 |
+
def _fail_with_undefined_error(
|
| 854 |
+
self, *args: t.Any, **kwargs: t.Any
|
| 855 |
+
) -> "te.NoReturn":
|
| 856 |
+
"""Raise an :exc:`UndefinedError` when operations are performed
|
| 857 |
+
on the undefined value.
|
| 858 |
+
"""
|
| 859 |
+
raise self._undefined_exception(self._undefined_message)
|
| 860 |
+
|
| 861 |
+
@internalcode
|
| 862 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 863 |
+
# Raise AttributeError on requests for names that appear to be unimplemented
|
| 864 |
+
# dunder methods to keep Python's internal protocol probing behaviors working
|
| 865 |
+
# properly in cases where another exception type could cause unexpected or
|
| 866 |
+
# difficult-to-diagnose failures.
|
| 867 |
+
if name[:2] == "__" and name[-2:] == "__":
|
| 868 |
+
raise AttributeError(name)
|
| 869 |
+
|
| 870 |
+
return self._fail_with_undefined_error()
|
| 871 |
+
|
| 872 |
+
__add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error
|
| 873 |
+
__mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error
|
| 874 |
+
__truediv__ = __rtruediv__ = _fail_with_undefined_error
|
| 875 |
+
__floordiv__ = __rfloordiv__ = _fail_with_undefined_error
|
| 876 |
+
__mod__ = __rmod__ = _fail_with_undefined_error
|
| 877 |
+
__pos__ = __neg__ = _fail_with_undefined_error
|
| 878 |
+
__call__ = __getitem__ = _fail_with_undefined_error
|
| 879 |
+
__lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
|
| 880 |
+
__int__ = __float__ = __complex__ = _fail_with_undefined_error
|
| 881 |
+
__pow__ = __rpow__ = _fail_with_undefined_error
|
| 882 |
+
|
| 883 |
+
def __eq__(self, other: t.Any) -> bool:
|
| 884 |
+
return type(self) is type(other)
|
| 885 |
+
|
| 886 |
+
def __ne__(self, other: t.Any) -> bool:
|
| 887 |
+
return not self.__eq__(other)
|
| 888 |
+
|
| 889 |
+
def __hash__(self) -> int:
|
| 890 |
+
return id(type(self))
|
| 891 |
+
|
| 892 |
+
def __str__(self) -> str:
|
| 893 |
+
return ""
|
| 894 |
+
|
| 895 |
+
def __len__(self) -> int:
|
| 896 |
+
return 0
|
| 897 |
+
|
| 898 |
+
def __iter__(self) -> t.Iterator[t.Any]:
|
| 899 |
+
yield from ()
|
| 900 |
+
|
| 901 |
+
async def __aiter__(self) -> t.AsyncIterator[t.Any]:
|
| 902 |
+
for _ in ():
|
| 903 |
+
yield
|
| 904 |
+
|
| 905 |
+
def __bool__(self) -> bool:
|
| 906 |
+
return False
|
| 907 |
+
|
| 908 |
+
def __repr__(self) -> str:
|
| 909 |
+
return "Undefined"
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
def make_logging_undefined(
|
| 913 |
+
logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined
|
| 914 |
+
) -> t.Type[Undefined]:
|
| 915 |
+
"""Given a logger object this returns a new undefined class that will
|
| 916 |
+
log certain failures. It will log iterations and printing. If no
|
| 917 |
+
logger is given a default logger is created.
|
| 918 |
+
|
| 919 |
+
Example::
|
| 920 |
+
|
| 921 |
+
logger = logging.getLogger(__name__)
|
| 922 |
+
LoggingUndefined = make_logging_undefined(
|
| 923 |
+
logger=logger,
|
| 924 |
+
base=Undefined
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
.. versionadded:: 2.8
|
| 928 |
+
|
| 929 |
+
:param logger: the logger to use. If not provided, a default logger
|
| 930 |
+
is created.
|
| 931 |
+
:param base: the base class to add logging functionality to. This
|
| 932 |
+
defaults to :class:`Undefined`.
|
| 933 |
+
"""
|
| 934 |
+
if logger is None:
|
| 935 |
+
import logging
|
| 936 |
+
|
| 937 |
+
logger = logging.getLogger(__name__)
|
| 938 |
+
logger.addHandler(logging.StreamHandler(sys.stderr))
|
| 939 |
+
|
| 940 |
+
def _log_message(undef: Undefined) -> None:
|
| 941 |
+
logger.warning("Template variable warning: %s", undef._undefined_message)
|
| 942 |
+
|
| 943 |
+
class LoggingUndefined(base): # type: ignore
|
| 944 |
+
__slots__ = ()
|
| 945 |
+
|
| 946 |
+
def _fail_with_undefined_error( # type: ignore
|
| 947 |
+
self, *args: t.Any, **kwargs: t.Any
|
| 948 |
+
) -> "te.NoReturn":
|
| 949 |
+
try:
|
| 950 |
+
super()._fail_with_undefined_error(*args, **kwargs)
|
| 951 |
+
except self._undefined_exception as e:
|
| 952 |
+
logger.error("Template variable error: %s", e) # type: ignore
|
| 953 |
+
raise e
|
| 954 |
+
|
| 955 |
+
def __str__(self) -> str:
|
| 956 |
+
_log_message(self)
|
| 957 |
+
return super().__str__() # type: ignore
|
| 958 |
+
|
| 959 |
+
def __iter__(self) -> t.Iterator[t.Any]:
|
| 960 |
+
_log_message(self)
|
| 961 |
+
return super().__iter__() # type: ignore
|
| 962 |
+
|
| 963 |
+
def __bool__(self) -> bool:
|
| 964 |
+
_log_message(self)
|
| 965 |
+
return super().__bool__() # type: ignore
|
| 966 |
+
|
| 967 |
+
return LoggingUndefined
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
class ChainableUndefined(Undefined):
|
| 971 |
+
"""An undefined that is chainable, where both ``__getattr__`` and
|
| 972 |
+
``__getitem__`` return itself rather than raising an
|
| 973 |
+
:exc:`UndefinedError`.
|
| 974 |
+
|
| 975 |
+
>>> foo = ChainableUndefined(name='foo')
|
| 976 |
+
>>> str(foo.bar['baz'])
|
| 977 |
+
''
|
| 978 |
+
>>> foo.bar['baz'] + 42
|
| 979 |
+
Traceback (most recent call last):
|
| 980 |
+
...
|
| 981 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
| 982 |
+
|
| 983 |
+
.. versionadded:: 2.11.0
|
| 984 |
+
"""
|
| 985 |
+
|
| 986 |
+
__slots__ = ()
|
| 987 |
+
|
| 988 |
+
def __html__(self) -> str:
|
| 989 |
+
return str(self)
|
| 990 |
+
|
| 991 |
+
def __getattr__(self, name: str) -> "ChainableUndefined":
|
| 992 |
+
# Raise AttributeError on requests for names that appear to be unimplemented
|
| 993 |
+
# dunder methods to avoid confusing Python with truthy non-method objects that
|
| 994 |
+
# do not implement the protocol being probed for. e.g., copy.copy(Undefined())
|
| 995 |
+
# fails spectacularly if getattr(Undefined(), '__setstate__') returns an
|
| 996 |
+
# Undefined object instead of raising AttributeError to signal that it does not
|
| 997 |
+
# support that style of object initialization.
|
| 998 |
+
if name[:2] == "__" and name[-2:] == "__":
|
| 999 |
+
raise AttributeError(name)
|
| 1000 |
+
|
| 1001 |
+
return self
|
| 1002 |
+
|
| 1003 |
+
def __getitem__(self, _name: str) -> "ChainableUndefined": # type: ignore[override]
|
| 1004 |
+
return self
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
class DebugUndefined(Undefined):
|
| 1008 |
+
"""An undefined that returns the debug info when printed.
|
| 1009 |
+
|
| 1010 |
+
>>> foo = DebugUndefined(name='foo')
|
| 1011 |
+
>>> str(foo)
|
| 1012 |
+
'{{ foo }}'
|
| 1013 |
+
>>> not foo
|
| 1014 |
+
True
|
| 1015 |
+
>>> foo + 42
|
| 1016 |
+
Traceback (most recent call last):
|
| 1017 |
+
...
|
| 1018 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
| 1019 |
+
"""
|
| 1020 |
+
|
| 1021 |
+
__slots__ = ()
|
| 1022 |
+
|
| 1023 |
+
def __str__(self) -> str:
|
| 1024 |
+
if self._undefined_hint:
|
| 1025 |
+
message = f"undefined value printed: {self._undefined_hint}"
|
| 1026 |
+
|
| 1027 |
+
elif self._undefined_obj is missing:
|
| 1028 |
+
message = self._undefined_name # type: ignore
|
| 1029 |
+
|
| 1030 |
+
else:
|
| 1031 |
+
message = (
|
| 1032 |
+
f"no such element: {object_type_repr(self._undefined_obj)}"
|
| 1033 |
+
f"[{self._undefined_name!r}]"
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
return f"{{{{ {message} }}}}"
|
| 1037 |
+
|
| 1038 |
+
|
| 1039 |
+
class StrictUndefined(Undefined):
|
| 1040 |
+
"""An undefined that barks on print and iteration as well as boolean
|
| 1041 |
+
tests and all kinds of comparisons. In other words: you can do nothing
|
| 1042 |
+
with it except checking if it's defined using the `defined` test.
|
| 1043 |
+
|
| 1044 |
+
>>> foo = StrictUndefined(name='foo')
|
| 1045 |
+
>>> str(foo)
|
| 1046 |
+
Traceback (most recent call last):
|
| 1047 |
+
...
|
| 1048 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
| 1049 |
+
>>> not foo
|
| 1050 |
+
Traceback (most recent call last):
|
| 1051 |
+
...
|
| 1052 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
| 1053 |
+
>>> foo + 42
|
| 1054 |
+
Traceback (most recent call last):
|
| 1055 |
+
...
|
| 1056 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
| 1057 |
+
"""
|
| 1058 |
+
|
| 1059 |
+
__slots__ = ()
|
| 1060 |
+
__iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error
|
| 1061 |
+
__eq__ = __ne__ = __bool__ = __hash__ = Undefined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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A sandbox layer that ensures unsafe operations cannot be performed.
|
| 2 |
+
Useful when the template itself comes from an untrusted source.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import operator
|
| 6 |
+
import types
|
| 7 |
+
import typing as t
|
| 8 |
+
from _string import formatter_field_name_split # type: ignore
|
| 9 |
+
from collections import abc
|
| 10 |
+
from collections import deque
|
| 11 |
+
from functools import update_wrapper
|
| 12 |
+
from string import Formatter
|
| 13 |
+
|
| 14 |
+
from markupsafe import EscapeFormatter
|
| 15 |
+
from markupsafe import Markup
|
| 16 |
+
|
| 17 |
+
from .environment import Environment
|
| 18 |
+
from .exceptions import SecurityError
|
| 19 |
+
from .runtime import Context
|
| 20 |
+
from .runtime import Undefined
|
| 21 |
+
|
| 22 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
| 23 |
+
|
| 24 |
+
#: maximum number of items a range may produce
|
| 25 |
+
MAX_RANGE = 100000
|
| 26 |
+
|
| 27 |
+
#: Unsafe function attributes.
|
| 28 |
+
UNSAFE_FUNCTION_ATTRIBUTES: t.Set[str] = set()
|
| 29 |
+
|
| 30 |
+
#: Unsafe method attributes. Function attributes are unsafe for methods too.
|
| 31 |
+
UNSAFE_METHOD_ATTRIBUTES: t.Set[str] = set()
|
| 32 |
+
|
| 33 |
+
#: unsafe generator attributes.
|
| 34 |
+
UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}
|
| 35 |
+
|
| 36 |
+
#: unsafe attributes on coroutines
|
| 37 |
+
UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}
|
| 38 |
+
|
| 39 |
+
#: unsafe attributes on async generators
|
| 40 |
+
UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}
|
| 41 |
+
|
| 42 |
+
_mutable_spec: t.Tuple[t.Tuple[t.Type[t.Any], t.FrozenSet[str]], ...] = (
|
| 43 |
+
(
|
| 44 |
+
abc.MutableSet,
|
| 45 |
+
frozenset(
|
| 46 |
+
[
|
| 47 |
+
"add",
|
| 48 |
+
"clear",
|
| 49 |
+
"difference_update",
|
| 50 |
+
"discard",
|
| 51 |
+
"pop",
|
| 52 |
+
"remove",
|
| 53 |
+
"symmetric_difference_update",
|
| 54 |
+
"update",
|
| 55 |
+
]
|
| 56 |
+
),
|
| 57 |
+
),
|
| 58 |
+
(
|
| 59 |
+
abc.MutableMapping,
|
| 60 |
+
frozenset(["clear", "pop", "popitem", "setdefault", "update"]),
|
| 61 |
+
),
|
| 62 |
+
(
|
| 63 |
+
abc.MutableSequence,
|
| 64 |
+
frozenset(
|
| 65 |
+
["append", "clear", "pop", "reverse", "insert", "sort", "extend", "remove"]
|
| 66 |
+
),
|
| 67 |
+
),
|
| 68 |
+
(
|
| 69 |
+
deque,
|
| 70 |
+
frozenset(
|
| 71 |
+
[
|
| 72 |
+
"append",
|
| 73 |
+
"appendleft",
|
| 74 |
+
"clear",
|
| 75 |
+
"extend",
|
| 76 |
+
"extendleft",
|
| 77 |
+
"pop",
|
| 78 |
+
"popleft",
|
| 79 |
+
"remove",
|
| 80 |
+
"rotate",
|
| 81 |
+
]
|
| 82 |
+
),
|
| 83 |
+
),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def safe_range(*args: int) -> range:
|
| 88 |
+
"""A range that can't generate ranges with a length of more than
|
| 89 |
+
MAX_RANGE items.
|
| 90 |
+
"""
|
| 91 |
+
rng = range(*args)
|
| 92 |
+
|
| 93 |
+
if len(rng) > MAX_RANGE:
|
| 94 |
+
raise OverflowError(
|
| 95 |
+
"Range too big. The sandbox blocks ranges larger than"
|
| 96 |
+
f" MAX_RANGE ({MAX_RANGE})."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
return rng
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def unsafe(f: F) -> F:
|
| 103 |
+
"""Marks a function or method as unsafe.
|
| 104 |
+
|
| 105 |
+
.. code-block: python
|
| 106 |
+
|
| 107 |
+
@unsafe
|
| 108 |
+
def delete(self):
|
| 109 |
+
pass
|
| 110 |
+
"""
|
| 111 |
+
f.unsafe_callable = True # type: ignore
|
| 112 |
+
return f
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def is_internal_attribute(obj: t.Any, attr: str) -> bool:
|
| 116 |
+
"""Test if the attribute given is an internal python attribute. For
|
| 117 |
+
example this function returns `True` for the `func_code` attribute of
|
| 118 |
+
python objects. This is useful if the environment method
|
| 119 |
+
:meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
|
| 120 |
+
|
| 121 |
+
>>> from jinja2.sandbox import is_internal_attribute
|
| 122 |
+
>>> is_internal_attribute(str, "mro")
|
| 123 |
+
True
|
| 124 |
+
>>> is_internal_attribute(str, "upper")
|
| 125 |
+
False
|
| 126 |
+
"""
|
| 127 |
+
if isinstance(obj, types.FunctionType):
|
| 128 |
+
if attr in UNSAFE_FUNCTION_ATTRIBUTES:
|
| 129 |
+
return True
|
| 130 |
+
elif isinstance(obj, types.MethodType):
|
| 131 |
+
if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:
|
| 132 |
+
return True
|
| 133 |
+
elif isinstance(obj, type):
|
| 134 |
+
if attr == "mro":
|
| 135 |
+
return True
|
| 136 |
+
elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
|
| 137 |
+
return True
|
| 138 |
+
elif isinstance(obj, types.GeneratorType):
|
| 139 |
+
if attr in UNSAFE_GENERATOR_ATTRIBUTES:
|
| 140 |
+
return True
|
| 141 |
+
elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):
|
| 142 |
+
if attr in UNSAFE_COROUTINE_ATTRIBUTES:
|
| 143 |
+
return True
|
| 144 |
+
elif hasattr(types, "AsyncGeneratorType") and isinstance(
|
| 145 |
+
obj, types.AsyncGeneratorType
|
| 146 |
+
):
|
| 147 |
+
if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
|
| 148 |
+
return True
|
| 149 |
+
return attr.startswith("__")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def modifies_known_mutable(obj: t.Any, attr: str) -> bool:
|
| 153 |
+
"""This function checks if an attribute on a builtin mutable object
|
| 154 |
+
(list, dict, set or deque) or the corresponding ABCs would modify it
|
| 155 |
+
if called.
|
| 156 |
+
|
| 157 |
+
>>> modifies_known_mutable({}, "clear")
|
| 158 |
+
True
|
| 159 |
+
>>> modifies_known_mutable({}, "keys")
|
| 160 |
+
False
|
| 161 |
+
>>> modifies_known_mutable([], "append")
|
| 162 |
+
True
|
| 163 |
+
>>> modifies_known_mutable([], "index")
|
| 164 |
+
False
|
| 165 |
+
|
| 166 |
+
If called with an unsupported object, ``False`` is returned.
|
| 167 |
+
|
| 168 |
+
>>> modifies_known_mutable("foo", "upper")
|
| 169 |
+
False
|
| 170 |
+
"""
|
| 171 |
+
for typespec, unsafe in _mutable_spec:
|
| 172 |
+
if isinstance(obj, typespec):
|
| 173 |
+
return attr in unsafe
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SandboxedEnvironment(Environment):
|
| 178 |
+
"""The sandboxed environment. It works like the regular environment but
|
| 179 |
+
tells the compiler to generate sandboxed code. Additionally subclasses of
|
| 180 |
+
this environment may override the methods that tell the runtime what
|
| 181 |
+
attributes or functions are safe to access.
|
| 182 |
+
|
| 183 |
+
If the template tries to access insecure code a :exc:`SecurityError` is
|
| 184 |
+
raised. However also other exceptions may occur during the rendering so
|
| 185 |
+
the caller has to ensure that all exceptions are caught.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
sandboxed = True
|
| 189 |
+
|
| 190 |
+
#: default callback table for the binary operators. A copy of this is
|
| 191 |
+
#: available on each instance of a sandboxed environment as
|
| 192 |
+
#: :attr:`binop_table`
|
| 193 |
+
default_binop_table: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
|
| 194 |
+
"+": operator.add,
|
| 195 |
+
"-": operator.sub,
|
| 196 |
+
"*": operator.mul,
|
| 197 |
+
"/": operator.truediv,
|
| 198 |
+
"//": operator.floordiv,
|
| 199 |
+
"**": operator.pow,
|
| 200 |
+
"%": operator.mod,
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
#: default callback table for the unary operators. A copy of this is
|
| 204 |
+
#: available on each instance of a sandboxed environment as
|
| 205 |
+
#: :attr:`unop_table`
|
| 206 |
+
default_unop_table: t.Dict[str, t.Callable[[t.Any], t.Any]] = {
|
| 207 |
+
"+": operator.pos,
|
| 208 |
+
"-": operator.neg,
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
#: a set of binary operators that should be intercepted. Each operator
|
| 212 |
+
#: that is added to this set (empty by default) is delegated to the
|
| 213 |
+
#: :meth:`call_binop` method that will perform the operator. The default
|
| 214 |
+
#: operator callback is specified by :attr:`binop_table`.
|
| 215 |
+
#:
|
| 216 |
+
#: The following binary operators are interceptable:
|
| 217 |
+
#: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``
|
| 218 |
+
#:
|
| 219 |
+
#: The default operation form the operator table corresponds to the
|
| 220 |
+
#: builtin function. Intercepted calls are always slower than the native
|
| 221 |
+
#: operator call, so make sure only to intercept the ones you are
|
| 222 |
+
#: interested in.
|
| 223 |
+
#:
|
| 224 |
+
#: .. versionadded:: 2.6
|
| 225 |
+
intercepted_binops: t.FrozenSet[str] = frozenset()
|
| 226 |
+
|
| 227 |
+
#: a set of unary operators that should be intercepted. Each operator
|
| 228 |
+
#: that is added to this set (empty by default) is delegated to the
|
| 229 |
+
#: :meth:`call_unop` method that will perform the operator. The default
|
| 230 |
+
#: operator callback is specified by :attr:`unop_table`.
|
| 231 |
+
#:
|
| 232 |
+
#: The following unary operators are interceptable: ``+``, ``-``
|
| 233 |
+
#:
|
| 234 |
+
#: The default operation form the operator table corresponds to the
|
| 235 |
+
#: builtin function. Intercepted calls are always slower than the native
|
| 236 |
+
#: operator call, so make sure only to intercept the ones you are
|
| 237 |
+
#: interested in.
|
| 238 |
+
#:
|
| 239 |
+
#: .. versionadded:: 2.6
|
| 240 |
+
intercepted_unops: t.FrozenSet[str] = frozenset()
|
| 241 |
+
|
| 242 |
+
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
|
| 243 |
+
super().__init__(*args, **kwargs)
|
| 244 |
+
self.globals["range"] = safe_range
|
| 245 |
+
self.binop_table = self.default_binop_table.copy()
|
| 246 |
+
self.unop_table = self.default_unop_table.copy()
|
| 247 |
+
|
| 248 |
+
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
|
| 249 |
+
"""The sandboxed environment will call this method to check if the
|
| 250 |
+
attribute of an object is safe to access. Per default all attributes
|
| 251 |
+
starting with an underscore are considered private as well as the
|
| 252 |
+
special attributes of internal python objects as returned by the
|
| 253 |
+
:func:`is_internal_attribute` function.
|
| 254 |
+
"""
|
| 255 |
+
return not (attr.startswith("_") or is_internal_attribute(obj, attr))
|
| 256 |
+
|
| 257 |
+
def is_safe_callable(self, obj: t.Any) -> bool:
|
| 258 |
+
"""Check if an object is safely callable. By default callables
|
| 259 |
+
are considered safe unless decorated with :func:`unsafe`.
|
| 260 |
+
|
| 261 |
+
This also recognizes the Django convention of setting
|
| 262 |
+
``func.alters_data = True``.
|
| 263 |
+
"""
|
| 264 |
+
return not (
|
| 265 |
+
getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
def call_binop(
|
| 269 |
+
self, context: Context, operator: str, left: t.Any, right: t.Any
|
| 270 |
+
) -> t.Any:
|
| 271 |
+
"""For intercepted binary operator calls (:meth:`intercepted_binops`)
|
| 272 |
+
this function is executed instead of the builtin operator. This can
|
| 273 |
+
be used to fine tune the behavior of certain operators.
|
| 274 |
+
|
| 275 |
+
.. versionadded:: 2.6
|
| 276 |
+
"""
|
| 277 |
+
return self.binop_table[operator](left, right)
|
| 278 |
+
|
| 279 |
+
def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:
|
| 280 |
+
"""For intercepted unary operator calls (:meth:`intercepted_unops`)
|
| 281 |
+
this function is executed instead of the builtin operator. This can
|
| 282 |
+
be used to fine tune the behavior of certain operators.
|
| 283 |
+
|
| 284 |
+
.. versionadded:: 2.6
|
| 285 |
+
"""
|
| 286 |
+
return self.unop_table[operator](arg)
|
| 287 |
+
|
| 288 |
+
def getitem(
|
| 289 |
+
self, obj: t.Any, argument: t.Union[str, t.Any]
|
| 290 |
+
) -> t.Union[t.Any, Undefined]:
|
| 291 |
+
"""Subscribe an object from sandboxed code."""
|
| 292 |
+
try:
|
| 293 |
+
return obj[argument]
|
| 294 |
+
except (TypeError, LookupError):
|
| 295 |
+
if isinstance(argument, str):
|
| 296 |
+
try:
|
| 297 |
+
attr = str(argument)
|
| 298 |
+
except Exception:
|
| 299 |
+
pass
|
| 300 |
+
else:
|
| 301 |
+
try:
|
| 302 |
+
value = getattr(obj, attr)
|
| 303 |
+
except AttributeError:
|
| 304 |
+
pass
|
| 305 |
+
else:
|
| 306 |
+
fmt = self.wrap_str_format(value)
|
| 307 |
+
if fmt is not None:
|
| 308 |
+
return fmt
|
| 309 |
+
if self.is_safe_attribute(obj, argument, value):
|
| 310 |
+
return value
|
| 311 |
+
return self.unsafe_undefined(obj, argument)
|
| 312 |
+
return self.undefined(obj=obj, name=argument)
|
| 313 |
+
|
| 314 |
+
def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:
|
| 315 |
+
"""Subscribe an object from sandboxed code and prefer the
|
| 316 |
+
attribute. The attribute passed *must* be a bytestring.
|
| 317 |
+
"""
|
| 318 |
+
try:
|
| 319 |
+
value = getattr(obj, attribute)
|
| 320 |
+
except AttributeError:
|
| 321 |
+
try:
|
| 322 |
+
return obj[attribute]
|
| 323 |
+
except (TypeError, LookupError):
|
| 324 |
+
pass
|
| 325 |
+
else:
|
| 326 |
+
fmt = self.wrap_str_format(value)
|
| 327 |
+
if fmt is not None:
|
| 328 |
+
return fmt
|
| 329 |
+
if self.is_safe_attribute(obj, attribute, value):
|
| 330 |
+
return value
|
| 331 |
+
return self.unsafe_undefined(obj, attribute)
|
| 332 |
+
return self.undefined(obj=obj, name=attribute)
|
| 333 |
+
|
| 334 |
+
def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:
|
| 335 |
+
"""Return an undefined object for unsafe attributes."""
|
| 336 |
+
return self.undefined(
|
| 337 |
+
f"access to attribute {attribute!r} of"
|
| 338 |
+
f" {type(obj).__name__!r} object is unsafe.",
|
| 339 |
+
name=attribute,
|
| 340 |
+
obj=obj,
|
| 341 |
+
exc=SecurityError,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:
|
| 345 |
+
"""If the given value is a ``str.format`` or ``str.format_map`` method,
|
| 346 |
+
return a new function than handles sandboxing. This is done at access
|
| 347 |
+
rather than in :meth:`call`, so that calls made without ``call`` are
|
| 348 |
+
also sandboxed.
|
| 349 |
+
"""
|
| 350 |
+
if not isinstance(
|
| 351 |
+
value, (types.MethodType, types.BuiltinMethodType)
|
| 352 |
+
) or value.__name__ not in ("format", "format_map"):
|
| 353 |
+
return None
|
| 354 |
+
|
| 355 |
+
f_self: t.Any = value.__self__
|
| 356 |
+
|
| 357 |
+
if not isinstance(f_self, str):
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
str_type: t.Type[str] = type(f_self)
|
| 361 |
+
is_format_map = value.__name__ == "format_map"
|
| 362 |
+
formatter: SandboxedFormatter
|
| 363 |
+
|
| 364 |
+
if isinstance(f_self, Markup):
|
| 365 |
+
formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)
|
| 366 |
+
else:
|
| 367 |
+
formatter = SandboxedFormatter(self)
|
| 368 |
+
|
| 369 |
+
vformat = formatter.vformat
|
| 370 |
+
|
| 371 |
+
def wrapper(*args: t.Any, **kwargs: t.Any) -> str:
|
| 372 |
+
if is_format_map:
|
| 373 |
+
if kwargs:
|
| 374 |
+
raise TypeError("format_map() takes no keyword arguments")
|
| 375 |
+
|
| 376 |
+
if len(args) != 1:
|
| 377 |
+
raise TypeError(
|
| 378 |
+
f"format_map() takes exactly one argument ({len(args)} given)"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
kwargs = args[0]
|
| 382 |
+
args = ()
|
| 383 |
+
|
| 384 |
+
return str_type(vformat(f_self, args, kwargs))
|
| 385 |
+
|
| 386 |
+
return update_wrapper(wrapper, value)
|
| 387 |
+
|
| 388 |
+
def call(
|
| 389 |
+
__self, # noqa: B902
|
| 390 |
+
__context: Context,
|
| 391 |
+
__obj: t.Any,
|
| 392 |
+
*args: t.Any,
|
| 393 |
+
**kwargs: t.Any,
|
| 394 |
+
) -> t.Any:
|
| 395 |
+
"""Call an object from sandboxed code."""
|
| 396 |
+
|
| 397 |
+
# the double prefixes are to avoid double keyword argument
|
| 398 |
+
# errors when proxying the call.
|
| 399 |
+
if not __self.is_safe_callable(__obj):
|
| 400 |
+
raise SecurityError(f"{__obj!r} is not safely callable")
|
| 401 |
+
return __context.call(__obj, *args, **kwargs)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class ImmutableSandboxedEnvironment(SandboxedEnvironment):
|
| 405 |
+
"""Works exactly like the regular `SandboxedEnvironment` but does not
|
| 406 |
+
permit modifications on the builtin mutable objects `list`, `set`, and
|
| 407 |
+
`dict` by using the :func:`modifies_known_mutable` function.
|
| 408 |
+
"""
|
| 409 |
+
|
| 410 |
+
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
|
| 411 |
+
if not super().is_safe_attribute(obj, attr, value):
|
| 412 |
+
return False
|
| 413 |
+
|
| 414 |
+
return not modifies_known_mutable(obj, attr)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class SandboxedFormatter(Formatter):
|
| 418 |
+
def __init__(self, env: Environment, **kwargs: t.Any) -> None:
|
| 419 |
+
self._env = env
|
| 420 |
+
super().__init__(**kwargs)
|
| 421 |
+
|
| 422 |
+
def get_field(
|
| 423 |
+
self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]
|
| 424 |
+
) -> t.Tuple[t.Any, str]:
|
| 425 |
+
first, rest = formatter_field_name_split(field_name)
|
| 426 |
+
obj = self.get_value(first, args, kwargs)
|
| 427 |
+
for is_attr, i in rest:
|
| 428 |
+
if is_attr:
|
| 429 |
+
obj = self._env.getattr(obj, i)
|
| 430 |
+
else:
|
| 431 |
+
obj = self._env.getitem(obj, i)
|
| 432 |
+
return obj, first
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class SandboxedEscapeFormatter(SandboxedFormatter, EscapeForm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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Built-in template tests used with the ``is`` operator."""
|
| 2 |
+
|
| 3 |
+
import operator
|
| 4 |
+
import typing as t
|
| 5 |
+
from collections import abc
|
| 6 |
+
from numbers import Number
|
| 7 |
+
|
| 8 |
+
from .runtime import Undefined
|
| 9 |
+
from .utils import pass_environment
|
| 10 |
+
|
| 11 |
+
if t.TYPE_CHECKING:
|
| 12 |
+
from .environment import Environment
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_odd(value: int) -> bool:
|
| 16 |
+
"""Return true if the variable is odd."""
|
| 17 |
+
return value % 2 == 1
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_even(value: int) -> bool:
|
| 21 |
+
"""Return true if the variable is even."""
|
| 22 |
+
return value % 2 == 0
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_divisibleby(value: int, num: int) -> bool:
|
| 26 |
+
"""Check if a variable is divisible by a number."""
|
| 27 |
+
return value % num == 0
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_defined(value: t.Any) -> bool:
|
| 31 |
+
"""Return true if the variable is defined:
|
| 32 |
+
|
| 33 |
+
.. sourcecode:: jinja
|
| 34 |
+
|
| 35 |
+
{% if variable is defined %}
|
| 36 |
+
value of variable: {{ variable }}
|
| 37 |
+
{% else %}
|
| 38 |
+
variable is not defined
|
| 39 |
+
{% endif %}
|
| 40 |
+
|
| 41 |
+
See the :func:`default` filter for a simple way to set undefined
|
| 42 |
+
variables.
|
| 43 |
+
"""
|
| 44 |
+
return not isinstance(value, Undefined)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_undefined(value: t.Any) -> bool:
|
| 48 |
+
"""Like :func:`defined` but the other way round."""
|
| 49 |
+
return isinstance(value, Undefined)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pass_environment
|
| 53 |
+
def test_filter(env: "Environment", value: str) -> bool:
|
| 54 |
+
"""Check if a filter exists by name. Useful if a filter may be
|
| 55 |
+
optionally available.
|
| 56 |
+
|
| 57 |
+
.. code-block:: jinja
|
| 58 |
+
|
| 59 |
+
{% if 'markdown' is filter %}
|
| 60 |
+
{{ value | markdown }}
|
| 61 |
+
{% else %}
|
| 62 |
+
{{ value }}
|
| 63 |
+
{% endif %}
|
| 64 |
+
|
| 65 |
+
.. versionadded:: 3.0
|
| 66 |
+
"""
|
| 67 |
+
return value in env.filters
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pass_environment
|
| 71 |
+
def test_test(env: "Environment", value: str) -> bool:
|
| 72 |
+
"""Check if a test exists by name. Useful if a test may be
|
| 73 |
+
optionally available.
|
| 74 |
+
|
| 75 |
+
.. code-block:: jinja
|
| 76 |
+
|
| 77 |
+
{% if 'loud' is test %}
|
| 78 |
+
{% if value is loud %}
|
| 79 |
+
{{ value|upper }}
|
| 80 |
+
{% else %}
|
| 81 |
+
{{ value|lower }}
|
| 82 |
+
{% endif %}
|
| 83 |
+
{% else %}
|
| 84 |
+
{{ value }}
|
| 85 |
+
{% endif %}
|
| 86 |
+
|
| 87 |
+
.. versionadded:: 3.0
|
| 88 |
+
"""
|
| 89 |
+
return value in env.tests
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_none(value: t.Any) -> bool:
|
| 93 |
+
"""Return true if the variable is none."""
|
| 94 |
+
return value is None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_boolean(value: t.Any) -> bool:
|
| 98 |
+
"""Return true if the object is a boolean value.
|
| 99 |
+
|
| 100 |
+
.. versionadded:: 2.11
|
| 101 |
+
"""
|
| 102 |
+
return value is True or value is False
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_false(value: t.Any) -> bool:
|
| 106 |
+
"""Return true if the object is False.
|
| 107 |
+
|
| 108 |
+
.. versionadded:: 2.11
|
| 109 |
+
"""
|
| 110 |
+
return value is False
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_true(value: t.Any) -> bool:
|
| 114 |
+
"""Return true if the object is True.
|
| 115 |
+
|
| 116 |
+
.. versionadded:: 2.11
|
| 117 |
+
"""
|
| 118 |
+
return value is True
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# NOTE: The existing 'number' test matches booleans and floats
|
| 122 |
+
def test_integer(value: t.Any) -> bool:
|
| 123 |
+
"""Return true if the object is an integer.
|
| 124 |
+
|
| 125 |
+
.. versionadded:: 2.11
|
| 126 |
+
"""
|
| 127 |
+
return isinstance(value, int) and value is not True and value is not False
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# NOTE: The existing 'number' test matches booleans and integers
|
| 131 |
+
def test_float(value: t.Any) -> bool:
|
| 132 |
+
"""Return true if the object is a float.
|
| 133 |
+
|
| 134 |
+
.. versionadded:: 2.11
|
| 135 |
+
"""
|
| 136 |
+
return isinstance(value, float)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_lower(value: str) -> bool:
|
| 140 |
+
"""Return true if the variable is lowercased."""
|
| 141 |
+
return str(value).islower()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_upper(value: str) -> bool:
|
| 145 |
+
"""Return true if the variable is uppercased."""
|
| 146 |
+
return str(value).isupper()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_string(value: t.Any) -> bool:
|
| 150 |
+
"""Return true if the object is a string."""
|
| 151 |
+
return isinstance(value, str)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def test_mapping(value: t.Any) -> bool:
|
| 155 |
+
"""Return true if the object is a mapping (dict etc.).
|
| 156 |
+
|
| 157 |
+
.. versionadded:: 2.6
|
| 158 |
+
"""
|
| 159 |
+
return isinstance(value, abc.Mapping)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_number(value: t.Any) -> bool:
|
| 163 |
+
"""Return true if the variable is a number."""
|
| 164 |
+
return isinstance(value, Number)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_sequence(value: t.Any) -> bool:
|
| 168 |
+
"""Return true if the variable is a sequence. Sequences are variables
|
| 169 |
+
that are iterable.
|
| 170 |
+
"""
|
| 171 |
+
try:
|
| 172 |
+
len(value)
|
| 173 |
+
value.__getitem__ # noqa B018
|
| 174 |
+
except Exception:
|
| 175 |
+
return False
|
| 176 |
+
|
| 177 |
+
return True
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def test_sameas(value: t.Any, other: t.Any) -> bool:
|
| 181 |
+
"""Check if an object points to the same memory address than another
|
| 182 |
+
object:
|
| 183 |
+
|
| 184 |
+
.. sourcecode:: jinja
|
| 185 |
+
|
| 186 |
+
{% if foo.attribute is sameas false %}
|
| 187 |
+
the foo attribute really is the `False` singleton
|
| 188 |
+
{% endif %}
|
| 189 |
+
"""
|
| 190 |
+
return value is other
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_iterable(value: t.Any) -> bool:
|
| 194 |
+
"""Check if it's possible to iterate over an object."""
|
| 195 |
+
try:
|
| 196 |
+
iter(value)
|
| 197 |
+
except TypeError:
|
| 198 |
+
return False
|
| 199 |
+
|
| 200 |
+
return True
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def test_escaped(value: t.Any) -> bool:
|
| 204 |
+
"""Check if the value is escaped."""
|
| 205 |
+
return hasattr(value, "__html__")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:
|
| 209 |
+
"""Check if value is in seq.
|
| 210 |
+
|
| 211 |
+
.. versionadded:: 2.10
|
| 212 |
+
"""
|
| 213 |
+
return value in seq
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
TESTS = {
|
| 217 |
+
"odd": test_odd,
|
| 218 |
+
"even": test_even,
|
| 219 |
+
"divisibleby": test_divisibleby,
|
| 220 |
+
"defined": test_defined,
|
| 221 |
+
"undefined": test_undefined,
|
| 222 |
+
"filter": test_filter,
|
| 223 |
+
"test": test_test,
|
| 224 |
+
"none": test_none,
|
| 225 |
+
"boolean": test_boolean,
|
| 226 |
+
"false": test_false,
|
| 227 |
+
"true": test_true,
|
| 228 |
+
"integer": test_integer,
|
| 229 |
+
"float": test_float,
|
| 230 |
+
"lower": test_lower,
|
| 231 |
+
"upper": test_upper,
|
| 232 |
+
"string": test_string,
|
| 233 |
+
"mapping": test_mapping,
|
| 234 |
+
"number": test_number,
|
| 235 |
+
"sequence": test_sequence,
|
| 236 |
+
"iterable": test_iterable,
|
| 237 |
+
"callable": callable,
|
| 238 |
+
"sameas": test_sameas,
|
| 239 |
+
"escaped": test_escaped,
|
| 240 |
+
"in": test_in,
|
| 241 |
+
"==": operator.eq,
|
| 242 |
+
"eq": operator.eq,
|
| 243 |
+
"equalto": operator.eq,
|
| 244 |
+
"!=": operator.ne,
|
| 245 |
+
"ne": operator.ne,
|
| 246 |
+
">": operator.gt,
|
| 247 |
+
"gt": operator.gt,
|
| 248 |
+
"greaterthan": operator.gt,
|
| 249 |
+
"ge": operator.ge,
|
| 250 |
+
">=": operator.ge,
|
| 251 |
+
"<": operator.lt,
|
| 252 |
+
"lt": operator.lt,
|
| 253 |
+
"lessthan": operator.lt,
|
| 254 |
+
"<=": operator.le,
|
| 255 |
+
"le": operator.le,
|
| 256 |
+
}
|
wemm/lib/python3.10/site-packages/jinja2/utils.py
ADDED
|
@@ -0,0 +1,766 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import typing as t
|
| 6 |
+
from collections import abc
|
| 7 |
+
from collections import deque
|
| 8 |
+
from random import choice
|
| 9 |
+
from random import randrange
|
| 10 |
+
from threading import Lock
|
| 11 |
+
from types import CodeType
|
| 12 |
+
from urllib.parse import quote_from_bytes
|
| 13 |
+
|
| 14 |
+
import markupsafe
|
| 15 |
+
|
| 16 |
+
if t.TYPE_CHECKING:
|
| 17 |
+
import typing_extensions as te
|
| 18 |
+
|
| 19 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class _MissingType:
|
| 23 |
+
def __repr__(self) -> str:
|
| 24 |
+
return "missing"
|
| 25 |
+
|
| 26 |
+
def __reduce__(self) -> str:
|
| 27 |
+
return "missing"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
missing: t.Any = _MissingType()
|
| 31 |
+
"""Special singleton representing missing values for the runtime."""
|
| 32 |
+
|
| 33 |
+
internal_code: t.MutableSet[CodeType] = set()
|
| 34 |
+
|
| 35 |
+
concat = "".join
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def pass_context(f: F) -> F:
|
| 39 |
+
"""Pass the :class:`~jinja2.runtime.Context` as the first argument
|
| 40 |
+
to the decorated function when called while rendering a template.
|
| 41 |
+
|
| 42 |
+
Can be used on functions, filters, and tests.
|
| 43 |
+
|
| 44 |
+
If only ``Context.eval_context`` is needed, use
|
| 45 |
+
:func:`pass_eval_context`. If only ``Context.environment`` is
|
| 46 |
+
needed, use :func:`pass_environment`.
|
| 47 |
+
|
| 48 |
+
.. versionadded:: 3.0.0
|
| 49 |
+
Replaces ``contextfunction`` and ``contextfilter``.
|
| 50 |
+
"""
|
| 51 |
+
f.jinja_pass_arg = _PassArg.context # type: ignore
|
| 52 |
+
return f
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def pass_eval_context(f: F) -> F:
|
| 56 |
+
"""Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
|
| 57 |
+
to the decorated function when called while rendering a template.
|
| 58 |
+
See :ref:`eval-context`.
|
| 59 |
+
|
| 60 |
+
Can be used on functions, filters, and tests.
|
| 61 |
+
|
| 62 |
+
If only ``EvalContext.environment`` is needed, use
|
| 63 |
+
:func:`pass_environment`.
|
| 64 |
+
|
| 65 |
+
.. versionadded:: 3.0.0
|
| 66 |
+
Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
|
| 67 |
+
"""
|
| 68 |
+
f.jinja_pass_arg = _PassArg.eval_context # type: ignore
|
| 69 |
+
return f
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def pass_environment(f: F) -> F:
|
| 73 |
+
"""Pass the :class:`~jinja2.Environment` as the first argument to
|
| 74 |
+
the decorated function when called while rendering a template.
|
| 75 |
+
|
| 76 |
+
Can be used on functions, filters, and tests.
|
| 77 |
+
|
| 78 |
+
.. versionadded:: 3.0.0
|
| 79 |
+
Replaces ``environmentfunction`` and ``environmentfilter``.
|
| 80 |
+
"""
|
| 81 |
+
f.jinja_pass_arg = _PassArg.environment # type: ignore
|
| 82 |
+
return f
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class _PassArg(enum.Enum):
|
| 86 |
+
context = enum.auto()
|
| 87 |
+
eval_context = enum.auto()
|
| 88 |
+
environment = enum.auto()
|
| 89 |
+
|
| 90 |
+
@classmethod
|
| 91 |
+
def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
|
| 92 |
+
if hasattr(obj, "jinja_pass_arg"):
|
| 93 |
+
return obj.jinja_pass_arg # type: ignore
|
| 94 |
+
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def internalcode(f: F) -> F:
|
| 99 |
+
"""Marks the function as internally used"""
|
| 100 |
+
internal_code.add(f.__code__)
|
| 101 |
+
return f
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def is_undefined(obj: t.Any) -> bool:
|
| 105 |
+
"""Check if the object passed is undefined. This does nothing more than
|
| 106 |
+
performing an instance check against :class:`Undefined` but looks nicer.
|
| 107 |
+
This can be used for custom filters or tests that want to react to
|
| 108 |
+
undefined variables. For example a custom default filter can look like
|
| 109 |
+
this::
|
| 110 |
+
|
| 111 |
+
def default(var, default=''):
|
| 112 |
+
if is_undefined(var):
|
| 113 |
+
return default
|
| 114 |
+
return var
|
| 115 |
+
"""
|
| 116 |
+
from .runtime import Undefined
|
| 117 |
+
|
| 118 |
+
return isinstance(obj, Undefined)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def consume(iterable: t.Iterable[t.Any]) -> None:
|
| 122 |
+
"""Consumes an iterable without doing anything with it."""
|
| 123 |
+
for _ in iterable:
|
| 124 |
+
pass
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def clear_caches() -> None:
|
| 128 |
+
"""Jinja keeps internal caches for environments and lexers. These are
|
| 129 |
+
used so that Jinja doesn't have to recreate environments and lexers all
|
| 130 |
+
the time. Normally you don't have to care about that but if you are
|
| 131 |
+
measuring memory consumption you may want to clean the caches.
|
| 132 |
+
"""
|
| 133 |
+
from .environment import get_spontaneous_environment
|
| 134 |
+
from .lexer import _lexer_cache
|
| 135 |
+
|
| 136 |
+
get_spontaneous_environment.cache_clear()
|
| 137 |
+
_lexer_cache.clear()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def import_string(import_name: str, silent: bool = False) -> t.Any:
|
| 141 |
+
"""Imports an object based on a string. This is useful if you want to
|
| 142 |
+
use import paths as endpoints or something similar. An import path can
|
| 143 |
+
be specified either in dotted notation (``xml.sax.saxutils.escape``)
|
| 144 |
+
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
|
| 145 |
+
|
| 146 |
+
If the `silent` is True the return value will be `None` if the import
|
| 147 |
+
fails.
|
| 148 |
+
|
| 149 |
+
:return: imported object
|
| 150 |
+
"""
|
| 151 |
+
try:
|
| 152 |
+
if ":" in import_name:
|
| 153 |
+
module, obj = import_name.split(":", 1)
|
| 154 |
+
elif "." in import_name:
|
| 155 |
+
module, _, obj = import_name.rpartition(".")
|
| 156 |
+
else:
|
| 157 |
+
return __import__(import_name)
|
| 158 |
+
return getattr(__import__(module, None, None, [obj]), obj)
|
| 159 |
+
except (ImportError, AttributeError):
|
| 160 |
+
if not silent:
|
| 161 |
+
raise
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO[t.Any]]:
|
| 165 |
+
"""Returns a file descriptor for the filename if that file exists,
|
| 166 |
+
otherwise ``None``.
|
| 167 |
+
"""
|
| 168 |
+
if not os.path.isfile(filename):
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
return open(filename, mode)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def object_type_repr(obj: t.Any) -> str:
|
| 175 |
+
"""Returns the name of the object's type. For some recognized
|
| 176 |
+
singletons the name of the object is returned instead. (For
|
| 177 |
+
example for `None` and `Ellipsis`).
|
| 178 |
+
"""
|
| 179 |
+
if obj is None:
|
| 180 |
+
return "None"
|
| 181 |
+
elif obj is Ellipsis:
|
| 182 |
+
return "Ellipsis"
|
| 183 |
+
|
| 184 |
+
cls = type(obj)
|
| 185 |
+
|
| 186 |
+
if cls.__module__ == "builtins":
|
| 187 |
+
return f"{cls.__name__} object"
|
| 188 |
+
|
| 189 |
+
return f"{cls.__module__}.{cls.__name__} object"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def pformat(obj: t.Any) -> str:
|
| 193 |
+
"""Format an object using :func:`pprint.pformat`."""
|
| 194 |
+
from pprint import pformat
|
| 195 |
+
|
| 196 |
+
return pformat(obj)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
_http_re = re.compile(
|
| 200 |
+
r"""
|
| 201 |
+
^
|
| 202 |
+
(
|
| 203 |
+
(https?://|www\.) # scheme or www
|
| 204 |
+
(([\w%-]+\.)+)? # subdomain
|
| 205 |
+
(
|
| 206 |
+
[a-z]{2,63} # basic tld
|
| 207 |
+
|
|
| 208 |
+
xn--[\w%]{2,59} # idna tld
|
| 209 |
+
)
|
| 210 |
+
|
|
| 211 |
+
([\w%-]{2,63}\.)+ # basic domain
|
| 212 |
+
(com|net|int|edu|gov|org|info|mil) # basic tld
|
| 213 |
+
|
|
| 214 |
+
(https?://) # scheme
|
| 215 |
+
(
|
| 216 |
+
(([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4
|
| 217 |
+
|
|
| 218 |
+
(\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6
|
| 219 |
+
)
|
| 220 |
+
)
|
| 221 |
+
(?::[\d]{1,5})? # port
|
| 222 |
+
(?:[/?#]\S*)? # path, query, and fragment
|
| 223 |
+
$
|
| 224 |
+
""",
|
| 225 |
+
re.IGNORECASE | re.VERBOSE,
|
| 226 |
+
)
|
| 227 |
+
_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def urlize(
|
| 231 |
+
text: str,
|
| 232 |
+
trim_url_limit: t.Optional[int] = None,
|
| 233 |
+
rel: t.Optional[str] = None,
|
| 234 |
+
target: t.Optional[str] = None,
|
| 235 |
+
extra_schemes: t.Optional[t.Iterable[str]] = None,
|
| 236 |
+
) -> str:
|
| 237 |
+
"""Convert URLs in text into clickable links.
|
| 238 |
+
|
| 239 |
+
This may not recognize links in some situations. Usually, a more
|
| 240 |
+
comprehensive formatter, such as a Markdown library, is a better
|
| 241 |
+
choice.
|
| 242 |
+
|
| 243 |
+
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
|
| 244 |
+
addresses. Links with trailing punctuation (periods, commas, closing
|
| 245 |
+
parentheses) and leading punctuation (opening parentheses) are
|
| 246 |
+
recognized excluding the punctuation. Email addresses that include
|
| 247 |
+
header fields are not recognized (for example,
|
| 248 |
+
``mailto:address@example.com?cc=copy@example.com``).
|
| 249 |
+
|
| 250 |
+
:param text: Original text containing URLs to link.
|
| 251 |
+
:param trim_url_limit: Shorten displayed URL values to this length.
|
| 252 |
+
:param target: Add the ``target`` attribute to links.
|
| 253 |
+
:param rel: Add the ``rel`` attribute to links.
|
| 254 |
+
:param extra_schemes: Recognize URLs that start with these schemes
|
| 255 |
+
in addition to the default behavior.
|
| 256 |
+
|
| 257 |
+
.. versionchanged:: 3.0
|
| 258 |
+
The ``extra_schemes`` parameter was added.
|
| 259 |
+
|
| 260 |
+
.. versionchanged:: 3.0
|
| 261 |
+
Generate ``https://`` links for URLs without a scheme.
|
| 262 |
+
|
| 263 |
+
.. versionchanged:: 3.0
|
| 264 |
+
The parsing rules were updated. Recognize email addresses with
|
| 265 |
+
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
|
| 266 |
+
parentheses and brackets in more cases.
|
| 267 |
+
"""
|
| 268 |
+
if trim_url_limit is not None:
|
| 269 |
+
|
| 270 |
+
def trim_url(x: str) -> str:
|
| 271 |
+
if len(x) > trim_url_limit:
|
| 272 |
+
return f"{x[:trim_url_limit]}..."
|
| 273 |
+
|
| 274 |
+
return x
|
| 275 |
+
|
| 276 |
+
else:
|
| 277 |
+
|
| 278 |
+
def trim_url(x: str) -> str:
|
| 279 |
+
return x
|
| 280 |
+
|
| 281 |
+
words = re.split(r"(\s+)", str(markupsafe.escape(text)))
|
| 282 |
+
rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
|
| 283 |
+
target_attr = f' target="{markupsafe.escape(target)}"' if target else ""
|
| 284 |
+
|
| 285 |
+
for i, word in enumerate(words):
|
| 286 |
+
head, middle, tail = "", word, ""
|
| 287 |
+
match = re.match(r"^([(<]|<)+", middle)
|
| 288 |
+
|
| 289 |
+
if match:
|
| 290 |
+
head = match.group()
|
| 291 |
+
middle = middle[match.end() :]
|
| 292 |
+
|
| 293 |
+
# Unlike lead, which is anchored to the start of the string,
|
| 294 |
+
# need to check that the string ends with any of the characters
|
| 295 |
+
# before trying to match all of them, to avoid backtracking.
|
| 296 |
+
if middle.endswith((")", ">", ".", ",", "\n", ">")):
|
| 297 |
+
match = re.search(r"([)>.,\n]|>)+$", middle)
|
| 298 |
+
|
| 299 |
+
if match:
|
| 300 |
+
tail = match.group()
|
| 301 |
+
middle = middle[: match.start()]
|
| 302 |
+
|
| 303 |
+
# Prefer balancing parentheses in URLs instead of ignoring a
|
| 304 |
+
# trailing character.
|
| 305 |
+
for start_char, end_char in ("(", ")"), ("<", ">"), ("<", ">"):
|
| 306 |
+
start_count = middle.count(start_char)
|
| 307 |
+
|
| 308 |
+
if start_count <= middle.count(end_char):
|
| 309 |
+
# Balanced, or lighter on the left
|
| 310 |
+
continue
|
| 311 |
+
|
| 312 |
+
# Move as many as possible from the tail to balance
|
| 313 |
+
for _ in range(min(start_count, tail.count(end_char))):
|
| 314 |
+
end_index = tail.index(end_char) + len(end_char)
|
| 315 |
+
# Move anything in the tail before the end char too
|
| 316 |
+
middle += tail[:end_index]
|
| 317 |
+
tail = tail[end_index:]
|
| 318 |
+
|
| 319 |
+
if _http_re.match(middle):
|
| 320 |
+
if middle.startswith("https://") or middle.startswith("http://"):
|
| 321 |
+
middle = (
|
| 322 |
+
f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'
|
| 323 |
+
)
|
| 324 |
+
else:
|
| 325 |
+
middle = (
|
| 326 |
+
f'<a href="https://{middle}"{rel_attr}{target_attr}>'
|
| 327 |
+
f"{trim_url(middle)}</a>"
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
elif middle.startswith("mailto:") and _email_re.match(middle[7:]):
|
| 331 |
+
middle = f'<a href="{middle}">{middle[7:]}</a>'
|
| 332 |
+
|
| 333 |
+
elif (
|
| 334 |
+
"@" in middle
|
| 335 |
+
and not middle.startswith("www.")
|
| 336 |
+
# ignore values like `@a@b`
|
| 337 |
+
and not middle.startswith("@")
|
| 338 |
+
and ":" not in middle
|
| 339 |
+
and _email_re.match(middle)
|
| 340 |
+
):
|
| 341 |
+
middle = f'<a href="mailto:{middle}">{middle}</a>'
|
| 342 |
+
|
| 343 |
+
elif extra_schemes is not None:
|
| 344 |
+
for scheme in extra_schemes:
|
| 345 |
+
if middle != scheme and middle.startswith(scheme):
|
| 346 |
+
middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'
|
| 347 |
+
|
| 348 |
+
words[i] = f"{head}{middle}{tail}"
|
| 349 |
+
|
| 350 |
+
return "".join(words)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def generate_lorem_ipsum(
|
| 354 |
+
n: int = 5, html: bool = True, min: int = 20, max: int = 100
|
| 355 |
+
) -> str:
|
| 356 |
+
"""Generate some lorem ipsum for the template."""
|
| 357 |
+
from .constants import LOREM_IPSUM_WORDS
|
| 358 |
+
|
| 359 |
+
words = LOREM_IPSUM_WORDS.split()
|
| 360 |
+
result = []
|
| 361 |
+
|
| 362 |
+
for _ in range(n):
|
| 363 |
+
next_capitalized = True
|
| 364 |
+
last_comma = last_fullstop = 0
|
| 365 |
+
word = None
|
| 366 |
+
last = None
|
| 367 |
+
p = []
|
| 368 |
+
|
| 369 |
+
# each paragraph contains out of 20 to 100 words.
|
| 370 |
+
for idx, _ in enumerate(range(randrange(min, max))):
|
| 371 |
+
while True:
|
| 372 |
+
word = choice(words)
|
| 373 |
+
if word != last:
|
| 374 |
+
last = word
|
| 375 |
+
break
|
| 376 |
+
if next_capitalized:
|
| 377 |
+
word = word.capitalize()
|
| 378 |
+
next_capitalized = False
|
| 379 |
+
# add commas
|
| 380 |
+
if idx - randrange(3, 8) > last_comma:
|
| 381 |
+
last_comma = idx
|
| 382 |
+
last_fullstop += 2
|
| 383 |
+
word += ","
|
| 384 |
+
# add end of sentences
|
| 385 |
+
if idx - randrange(10, 20) > last_fullstop:
|
| 386 |
+
last_comma = last_fullstop = idx
|
| 387 |
+
word += "."
|
| 388 |
+
next_capitalized = True
|
| 389 |
+
p.append(word)
|
| 390 |
+
|
| 391 |
+
# ensure that the paragraph ends with a dot.
|
| 392 |
+
p_str = " ".join(p)
|
| 393 |
+
|
| 394 |
+
if p_str.endswith(","):
|
| 395 |
+
p_str = p_str[:-1] + "."
|
| 396 |
+
elif not p_str.endswith("."):
|
| 397 |
+
p_str += "."
|
| 398 |
+
|
| 399 |
+
result.append(p_str)
|
| 400 |
+
|
| 401 |
+
if not html:
|
| 402 |
+
return "\n\n".join(result)
|
| 403 |
+
return markupsafe.Markup(
|
| 404 |
+
"\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
|
| 409 |
+
"""Quote a string for use in a URL using the given charset.
|
| 410 |
+
|
| 411 |
+
:param obj: String or bytes to quote. Other types are converted to
|
| 412 |
+
string then encoded to bytes using the given charset.
|
| 413 |
+
:param charset: Encode text to bytes using this charset.
|
| 414 |
+
:param for_qs: Quote "/" and use "+" for spaces.
|
| 415 |
+
"""
|
| 416 |
+
if not isinstance(obj, bytes):
|
| 417 |
+
if not isinstance(obj, str):
|
| 418 |
+
obj = str(obj)
|
| 419 |
+
|
| 420 |
+
obj = obj.encode(charset)
|
| 421 |
+
|
| 422 |
+
safe = b"" if for_qs else b"/"
|
| 423 |
+
rv = quote_from_bytes(obj, safe)
|
| 424 |
+
|
| 425 |
+
if for_qs:
|
| 426 |
+
rv = rv.replace("%20", "+")
|
| 427 |
+
|
| 428 |
+
return rv
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
@abc.MutableMapping.register
|
| 432 |
+
class LRUCache:
|
| 433 |
+
"""A simple LRU Cache implementation."""
|
| 434 |
+
|
| 435 |
+
# this is fast for small capacities (something below 1000) but doesn't
|
| 436 |
+
# scale. But as long as it's only used as storage for templates this
|
| 437 |
+
# won't do any harm.
|
| 438 |
+
|
| 439 |
+
def __init__(self, capacity: int) -> None:
|
| 440 |
+
self.capacity = capacity
|
| 441 |
+
self._mapping: t.Dict[t.Any, t.Any] = {}
|
| 442 |
+
self._queue: te.Deque[t.Any] = deque()
|
| 443 |
+
self._postinit()
|
| 444 |
+
|
| 445 |
+
def _postinit(self) -> None:
|
| 446 |
+
# alias all queue methods for faster lookup
|
| 447 |
+
self._popleft = self._queue.popleft
|
| 448 |
+
self._pop = self._queue.pop
|
| 449 |
+
self._remove = self._queue.remove
|
| 450 |
+
self._wlock = Lock()
|
| 451 |
+
self._append = self._queue.append
|
| 452 |
+
|
| 453 |
+
def __getstate__(self) -> t.Mapping[str, t.Any]:
|
| 454 |
+
return {
|
| 455 |
+
"capacity": self.capacity,
|
| 456 |
+
"_mapping": self._mapping,
|
| 457 |
+
"_queue": self._queue,
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:
|
| 461 |
+
self.__dict__.update(d)
|
| 462 |
+
self._postinit()
|
| 463 |
+
|
| 464 |
+
def __getnewargs__(self) -> t.Tuple[t.Any, ...]:
|
| 465 |
+
return (self.capacity,)
|
| 466 |
+
|
| 467 |
+
def copy(self) -> "te.Self":
|
| 468 |
+
"""Return a shallow copy of the instance."""
|
| 469 |
+
rv = self.__class__(self.capacity)
|
| 470 |
+
rv._mapping.update(self._mapping)
|
| 471 |
+
rv._queue.extend(self._queue)
|
| 472 |
+
return rv
|
| 473 |
+
|
| 474 |
+
def get(self, key: t.Any, default: t.Any = None) -> t.Any:
|
| 475 |
+
"""Return an item from the cache dict or `default`"""
|
| 476 |
+
try:
|
| 477 |
+
return self[key]
|
| 478 |
+
except KeyError:
|
| 479 |
+
return default
|
| 480 |
+
|
| 481 |
+
def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:
|
| 482 |
+
"""Set `default` if the key is not in the cache otherwise
|
| 483 |
+
leave unchanged. Return the value of this key.
|
| 484 |
+
"""
|
| 485 |
+
try:
|
| 486 |
+
return self[key]
|
| 487 |
+
except KeyError:
|
| 488 |
+
self[key] = default
|
| 489 |
+
return default
|
| 490 |
+
|
| 491 |
+
def clear(self) -> None:
|
| 492 |
+
"""Clear the cache."""
|
| 493 |
+
with self._wlock:
|
| 494 |
+
self._mapping.clear()
|
| 495 |
+
self._queue.clear()
|
| 496 |
+
|
| 497 |
+
def __contains__(self, key: t.Any) -> bool:
|
| 498 |
+
"""Check if a key exists in this cache."""
|
| 499 |
+
return key in self._mapping
|
| 500 |
+
|
| 501 |
+
def __len__(self) -> int:
|
| 502 |
+
"""Return the current size of the cache."""
|
| 503 |
+
return len(self._mapping)
|
| 504 |
+
|
| 505 |
+
def __repr__(self) -> str:
|
| 506 |
+
return f"<{type(self).__name__} {self._mapping!r}>"
|
| 507 |
+
|
| 508 |
+
def __getitem__(self, key: t.Any) -> t.Any:
|
| 509 |
+
"""Get an item from the cache. Moves the item up so that it has the
|
| 510 |
+
highest priority then.
|
| 511 |
+
|
| 512 |
+
Raise a `KeyError` if it does not exist.
|
| 513 |
+
"""
|
| 514 |
+
with self._wlock:
|
| 515 |
+
rv = self._mapping[key]
|
| 516 |
+
|
| 517 |
+
if self._queue[-1] != key:
|
| 518 |
+
try:
|
| 519 |
+
self._remove(key)
|
| 520 |
+
except ValueError:
|
| 521 |
+
# if something removed the key from the container
|
| 522 |
+
# when we read, ignore the ValueError that we would
|
| 523 |
+
# get otherwise.
|
| 524 |
+
pass
|
| 525 |
+
|
| 526 |
+
self._append(key)
|
| 527 |
+
|
| 528 |
+
return rv
|
| 529 |
+
|
| 530 |
+
def __setitem__(self, key: t.Any, value: t.Any) -> None:
|
| 531 |
+
"""Sets the value for an item. Moves the item up so that it
|
| 532 |
+
has the highest priority then.
|
| 533 |
+
"""
|
| 534 |
+
with self._wlock:
|
| 535 |
+
if key in self._mapping:
|
| 536 |
+
self._remove(key)
|
| 537 |
+
elif len(self._mapping) == self.capacity:
|
| 538 |
+
del self._mapping[self._popleft()]
|
| 539 |
+
|
| 540 |
+
self._append(key)
|
| 541 |
+
self._mapping[key] = value
|
| 542 |
+
|
| 543 |
+
def __delitem__(self, key: t.Any) -> None:
|
| 544 |
+
"""Remove an item from the cache dict.
|
| 545 |
+
Raise a `KeyError` if it does not exist.
|
| 546 |
+
"""
|
| 547 |
+
with self._wlock:
|
| 548 |
+
del self._mapping[key]
|
| 549 |
+
|
| 550 |
+
try:
|
| 551 |
+
self._remove(key)
|
| 552 |
+
except ValueError:
|
| 553 |
+
pass
|
| 554 |
+
|
| 555 |
+
def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:
|
| 556 |
+
"""Return a list of items."""
|
| 557 |
+
result = [(key, self._mapping[key]) for key in list(self._queue)]
|
| 558 |
+
result.reverse()
|
| 559 |
+
return result
|
| 560 |
+
|
| 561 |
+
def values(self) -> t.Iterable[t.Any]:
|
| 562 |
+
"""Return a list of all values."""
|
| 563 |
+
return [x[1] for x in self.items()]
|
| 564 |
+
|
| 565 |
+
def keys(self) -> t.Iterable[t.Any]:
|
| 566 |
+
"""Return a list of all keys ordered by most recent usage."""
|
| 567 |
+
return list(self)
|
| 568 |
+
|
| 569 |
+
def __iter__(self) -> t.Iterator[t.Any]:
|
| 570 |
+
return reversed(tuple(self._queue))
|
| 571 |
+
|
| 572 |
+
def __reversed__(self) -> t.Iterator[t.Any]:
|
| 573 |
+
"""Iterate over the keys in the cache dict, oldest items
|
| 574 |
+
coming first.
|
| 575 |
+
"""
|
| 576 |
+
return iter(tuple(self._queue))
|
| 577 |
+
|
| 578 |
+
__copy__ = copy
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def select_autoescape(
|
| 582 |
+
enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
|
| 583 |
+
disabled_extensions: t.Collection[str] = (),
|
| 584 |
+
default_for_string: bool = True,
|
| 585 |
+
default: bool = False,
|
| 586 |
+
) -> t.Callable[[t.Optional[str]], bool]:
|
| 587 |
+
"""Intelligently sets the initial value of autoescaping based on the
|
| 588 |
+
filename of the template. This is the recommended way to configure
|
| 589 |
+
autoescaping if you do not want to write a custom function yourself.
|
| 590 |
+
|
| 591 |
+
If you want to enable it for all templates created from strings or
|
| 592 |
+
for all templates with `.html` and `.xml` extensions::
|
| 593 |
+
|
| 594 |
+
from jinja2 import Environment, select_autoescape
|
| 595 |
+
env = Environment(autoescape=select_autoescape(
|
| 596 |
+
enabled_extensions=('html', 'xml'),
|
| 597 |
+
default_for_string=True,
|
| 598 |
+
))
|
| 599 |
+
|
| 600 |
+
Example configuration to turn it on at all times except if the template
|
| 601 |
+
ends with `.txt`::
|
| 602 |
+
|
| 603 |
+
from jinja2 import Environment, select_autoescape
|
| 604 |
+
env = Environment(autoescape=select_autoescape(
|
| 605 |
+
disabled_extensions=('txt',),
|
| 606 |
+
default_for_string=True,
|
| 607 |
+
default=True,
|
| 608 |
+
))
|
| 609 |
+
|
| 610 |
+
The `enabled_extensions` is an iterable of all the extensions that
|
| 611 |
+
autoescaping should be enabled for. Likewise `disabled_extensions` is
|
| 612 |
+
a list of all templates it should be disabled for. If a template is
|
| 613 |
+
loaded from a string then the default from `default_for_string` is used.
|
| 614 |
+
If nothing matches then the initial value of autoescaping is set to the
|
| 615 |
+
value of `default`.
|
| 616 |
+
|
| 617 |
+
For security reasons this function operates case insensitive.
|
| 618 |
+
|
| 619 |
+
.. versionadded:: 2.9
|
| 620 |
+
"""
|
| 621 |
+
enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
|
| 622 |
+
disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)
|
| 623 |
+
|
| 624 |
+
def autoescape(template_name: t.Optional[str]) -> bool:
|
| 625 |
+
if template_name is None:
|
| 626 |
+
return default_for_string
|
| 627 |
+
template_name = template_name.lower()
|
| 628 |
+
if template_name.endswith(enabled_patterns):
|
| 629 |
+
return True
|
| 630 |
+
if template_name.endswith(disabled_patterns):
|
| 631 |
+
return False
|
| 632 |
+
return default
|
| 633 |
+
|
| 634 |
+
return autoescape
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def htmlsafe_json_dumps(
|
| 638 |
+
obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
|
| 639 |
+
) -> markupsafe.Markup:
|
| 640 |
+
"""Serialize an object to a string of JSON with :func:`json.dumps`,
|
| 641 |
+
then replace HTML-unsafe characters with Unicode escapes and mark
|
| 642 |
+
the result safe with :class:`~markupsafe.Markup`.
|
| 643 |
+
|
| 644 |
+
This is available in templates as the ``|tojson`` filter.
|
| 645 |
+
|
| 646 |
+
The following characters are escaped: ``<``, ``>``, ``&``, ``'``.
|
| 647 |
+
|
| 648 |
+
The returned string is safe to render in HTML documents and
|
| 649 |
+
``<script>`` tags. The exception is in HTML attributes that are
|
| 650 |
+
double quoted; either use single quotes or the ``|forceescape``
|
| 651 |
+
filter.
|
| 652 |
+
|
| 653 |
+
:param obj: The object to serialize to JSON.
|
| 654 |
+
:param dumps: The ``dumps`` function to use. Defaults to
|
| 655 |
+
``env.policies["json.dumps_function"]``, which defaults to
|
| 656 |
+
:func:`json.dumps`.
|
| 657 |
+
:param kwargs: Extra arguments to pass to ``dumps``. Merged onto
|
| 658 |
+
``env.policies["json.dumps_kwargs"]``.
|
| 659 |
+
|
| 660 |
+
.. versionchanged:: 3.0
|
| 661 |
+
The ``dumper`` parameter is renamed to ``dumps``.
|
| 662 |
+
|
| 663 |
+
.. versionadded:: 2.9
|
| 664 |
+
"""
|
| 665 |
+
if dumps is None:
|
| 666 |
+
dumps = json.dumps
|
| 667 |
+
|
| 668 |
+
return markupsafe.Markup(
|
| 669 |
+
dumps(obj, **kwargs)
|
| 670 |
+
.replace("<", "\\u003c")
|
| 671 |
+
.replace(">", "\\u003e")
|
| 672 |
+
.replace("&", "\\u0026")
|
| 673 |
+
.replace("'", "\\u0027")
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
class Cycler:
|
| 678 |
+
"""Cycle through values by yield them one at a time, then restarting
|
| 679 |
+
once the end is reached. Available as ``cycler`` in templates.
|
| 680 |
+
|
| 681 |
+
Similar to ``loop.cycle``, but can be used outside loops or across
|
| 682 |
+
multiple loops. For example, render a list of folders and files in a
|
| 683 |
+
list, alternating giving them "odd" and "even" classes.
|
| 684 |
+
|
| 685 |
+
.. code-block:: html+jinja
|
| 686 |
+
|
| 687 |
+
{% set row_class = cycler("odd", "even") %}
|
| 688 |
+
<ul class="browser">
|
| 689 |
+
{% for folder in folders %}
|
| 690 |
+
<li class="folder {{ row_class.next() }}">{{ folder }}
|
| 691 |
+
{% endfor %}
|
| 692 |
+
{% for file in files %}
|
| 693 |
+
<li class="file {{ row_class.next() }}">{{ file }}
|
| 694 |
+
{% endfor %}
|
| 695 |
+
</ul>
|
| 696 |
+
|
| 697 |
+
:param items: Each positional argument will be yielded in the order
|
| 698 |
+
given for each cycle.
|
| 699 |
+
|
| 700 |
+
.. versionadded:: 2.1
|
| 701 |
+
"""
|
| 702 |
+
|
| 703 |
+
def __init__(self, *items: t.Any) -> None:
|
| 704 |
+
if not items:
|
| 705 |
+
raise RuntimeError("at least one item has to be provided")
|
| 706 |
+
self.items = items
|
| 707 |
+
self.pos = 0
|
| 708 |
+
|
| 709 |
+
def reset(self) -> None:
|
| 710 |
+
"""Resets the current item to the first item."""
|
| 711 |
+
self.pos = 0
|
| 712 |
+
|
| 713 |
+
@property
|
| 714 |
+
def current(self) -> t.Any:
|
| 715 |
+
"""Return the current item. Equivalent to the item that will be
|
| 716 |
+
returned next time :meth:`next` is called.
|
| 717 |
+
"""
|
| 718 |
+
return self.items[self.pos]
|
| 719 |
+
|
| 720 |
+
def next(self) -> t.Any:
|
| 721 |
+
"""Return the current item, then advance :attr:`current` to the
|
| 722 |
+
next item.
|
| 723 |
+
"""
|
| 724 |
+
rv = self.current
|
| 725 |
+
self.pos = (self.pos + 1) % len(self.items)
|
| 726 |
+
return rv
|
| 727 |
+
|
| 728 |
+
__next__ = next
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
class Joiner:
|
| 732 |
+
"""A joining helper for templates."""
|
| 733 |
+
|
| 734 |
+
def __init__(self, sep: str = ", ") -> None:
|
| 735 |
+
self.sep = sep
|
| 736 |
+
self.used = False
|
| 737 |
+
|
| 738 |
+
def __call__(self) -> str:
|
| 739 |
+
if not self.used:
|
| 740 |
+
self.used = True
|
| 741 |
+
return ""
|
| 742 |
+
return self.sep
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
class Namespace:
|
| 746 |
+
"""A namespace object that can hold arbitrary attributes. It may be
|
| 747 |
+
initialized from a dictionary or with keyword arguments."""
|
| 748 |
+
|
| 749 |
+
def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902
|
| 750 |
+
self, args = args[0], args[1:]
|
| 751 |
+
self.__attrs = dict(*args, **kwargs)
|
| 752 |
+
|
| 753 |
+
def __getattribute__(self, name: str) -> t.Any:
|
| 754 |
+
# __class__ is needed for the awaitable check in async mode
|
| 755 |
+
if name in {"_Namespace__attrs", "__class__"}:
|
| 756 |
+
return object.__getattribute__(self, name)
|
| 757 |
+
try:
|
| 758 |
+
return self.__attrs[name]
|
| 759 |
+
except KeyError:
|
| 760 |
+
raise AttributeError(name) from None
|
| 761 |
+
|
| 762 |
+
def __setitem__(self, name: str, value: t.Any) -> None:
|
| 763 |
+
self.__attrs[name] = value
|
| 764 |
+
|
| 765 |
+
def __repr__(self) -> str:
|
| 766 |
+
return f"<Namespace {self.__attrs!r}>"
|
wemm/lib/python3.10/site-packages/lightning_utilities-0.11.9.dist-info/METADATA
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: lightning-utilities
|
| 3 |
+
Version: 0.11.9
|
| 4 |
+
Summary: Lightning toolbox for across the our ecosystem.
|
| 5 |
+
Home-page: https://github.com/Lightning-AI/utilities
|
| 6 |
+
Download-URL: https://github.com/Lightning-AI/utilities
|
| 7 |
+
Author: Lightning AI et al.
|
| 8 |
+
Author-email: pytorch@lightning.ai
|
| 9 |
+
License: Apache-2.0
|
| 10 |
+
Project-URL: Bug Tracker, https://github.com/Lightning-AI/utilities/issues
|
| 11 |
+
Project-URL: Documentation, https://dev-toolbox.rtfd.io/en/latest/
|
| 12 |
+
Project-URL: Source Code, https://github.com/Lightning-AI/utilities
|
| 13 |
+
Keywords: Utilities,DevOps,CI/CD
|
| 14 |
+
Classifier: Environment :: Console
|
| 15 |
+
Classifier: Natural Language :: English
|
| 16 |
+
Classifier: Development Status :: 3 - Alpha
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: Operating System :: OS Independent
|
| 19 |
+
Classifier: Programming Language :: Python :: 3
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Requires-Python: >=3.8
|
| 26 |
+
Description-Content-Type: text/markdown
|
| 27 |
+
License-File: LICENSE
|
| 28 |
+
Requires-Dist: packaging>=17.1
|
| 29 |
+
Requires-Dist: setuptools
|
| 30 |
+
Requires-Dist: typing-extensions
|
| 31 |
+
Requires-Dist: importlib-metadata>=4.0.0; python_version < "3.8"
|
| 32 |
+
Provides-Extra: cli
|
| 33 |
+
Requires-Dist: fire; extra == "cli"
|
| 34 |
+
Provides-Extra: docs
|
| 35 |
+
Requires-Dist: requests>=2.0.0; extra == "docs"
|
| 36 |
+
Provides-Extra: typing
|
| 37 |
+
Requires-Dist: mypy>=1.0.0; extra == "typing"
|
| 38 |
+
Requires-Dist: types-setuptools; extra == "typing"
|
| 39 |
+
|
| 40 |
+
# Lightning Utilities
|
| 41 |
+
|
| 42 |
+
[](https://badge.fury.io/py/lightning-utilities)
|
| 43 |
+
[](https://github.com/Lightning-AI/utilities/blob/master/LICENSE)
|
| 44 |
+
[](https://pepy.tech/project/lightning-utilities)
|
| 45 |
+
[](https://pypi.org/project/lightning-utilities/)
|
| 46 |
+
|
| 47 |
+
[](https://github.com/Lightning-AI/utilities/actions/workflows/ci-testing.yml)
|
| 48 |
+
[](https://github.com/Lightning-AI/utilities/actions/workflows/ci-use-checks.yaml)
|
| 49 |
+
[](https://lit-utilities.readthedocs.io/en/latest/?badge=latest)
|
| 50 |
+
[](https://results.pre-commit.ci/latest/github/Lightning-AI/utilities/main)
|
| 51 |
+
|
| 52 |
+
__This repository covers the following use-cases:__
|
| 53 |
+
|
| 54 |
+
1. _Reusable GitHub workflows_
|
| 55 |
+
2. _Shared GitHub actions_
|
| 56 |
+
3. _General Python utilities in `lightning_utilities.core`_
|
| 57 |
+
4. _CLI `python -m lightning_utilities.cli --help`_
|
| 58 |
+
|
| 59 |
+
## 1. Reusable workflows
|
| 60 |
+
|
| 61 |
+
__Usage:__
|
| 62 |
+
|
| 63 |
+
```yaml
|
| 64 |
+
name: Check schema
|
| 65 |
+
|
| 66 |
+
on: [push]
|
| 67 |
+
|
| 68 |
+
jobs:
|
| 69 |
+
|
| 70 |
+
check-schema:
|
| 71 |
+
uses: Lightning-AI/utilities/.github/workflows/check-schema.yml@v0.5.0
|
| 72 |
+
with:
|
| 73 |
+
azure-dir: "" # skip Azure check
|
| 74 |
+
|
| 75 |
+
check-code:
|
| 76 |
+
uses: Lightning-AI/utilities/.github/workflows/check-code.yml@main
|
| 77 |
+
with:
|
| 78 |
+
actions-ref: main # normally you shall use the same version as the workflow
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
See usage of other workflows in [.github/workflows/ci-use-checks.yaml](https://github.com/Lightning-AI/utilities/tree/main/.github/workflows/ci-use-checks.yaml).
|
| 82 |
+
|
| 83 |
+
## 2. Reusable composite actions
|
| 84 |
+
|
| 85 |
+
See available composite actions [.github/actions/](https://github.com/Lightning-AI/utilities/tree/main/.github/actions).
|
| 86 |
+
|
| 87 |
+
__Usage:__
|
| 88 |
+
|
| 89 |
+
```yaml
|
| 90 |
+
name: Do something with cache
|
| 91 |
+
|
| 92 |
+
on: [push]
|
| 93 |
+
|
| 94 |
+
jobs:
|
| 95 |
+
pytest:
|
| 96 |
+
runs-on: ubuntu-20.04
|
| 97 |
+
steps:
|
| 98 |
+
- uses: actions/checkout@v3
|
| 99 |
+
- uses: actions/setup-python@v4
|
| 100 |
+
with:
|
| 101 |
+
python-version: 3.9
|
| 102 |
+
- uses: Lightning-AI/utilities/.github/actions/cache
|
| 103 |
+
with:
|
| 104 |
+
python-version: 3.9
|
| 105 |
+
requires: oldest # or latest
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
## 3. General Python utilities `lightning_utilities.core`
|
| 109 |
+
|
| 110 |
+
<details>
|
| 111 |
+
<summary>Installation</summary>
|
| 112 |
+
From source:
|
| 113 |
+
|
| 114 |
+
```bash
|
| 115 |
+
pip install https://github.com/Lightning-AI/utilities/archive/refs/heads/main.zip
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
From pypi:
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
pip install lightning_utilities
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
</details>
|
| 125 |
+
|
| 126 |
+
__Usage:__
|
| 127 |
+
|
| 128 |
+
Example for optional imports:
|
| 129 |
+
|
| 130 |
+
```python
|
| 131 |
+
from lightning_utilities.core.imports import module_available
|
| 132 |
+
|
| 133 |
+
if module_available("some_package.something"):
|
| 134 |
+
from some_package import something
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
## 4. CLI `lightning_utilities.cli`
|
| 138 |
+
|
| 139 |
+
The package provides common CLI commands.
|
| 140 |
+
|
| 141 |
+
<details>
|
| 142 |
+
<summary>Installation</summary>
|
| 143 |
+
|
| 144 |
+
From pypi:
|
| 145 |
+
|
| 146 |
+
```bash
|
| 147 |
+
pip install lightning_utilities[cli]
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
</details>
|
| 151 |
+
|
| 152 |
+
__Usage:__
|
| 153 |
+
|
| 154 |
+
```bash
|
| 155 |
+
python -m lightning_utilities.cli [group] [command]
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
<details>
|
| 159 |
+
<summary>Example for setting min versions</summary>
|
| 160 |
+
|
| 161 |
+
```console
|
| 162 |
+
$ cat requirements/test.txt
|
| 163 |
+
coverage>=5.0
|
| 164 |
+
codecov>=2.1
|
| 165 |
+
pytest>=6.0
|
| 166 |
+
pytest-cov
|
| 167 |
+
pytest-timeout
|
| 168 |
+
$ python -m lightning_utilities.cli requirements set-oldest
|
| 169 |
+
$ cat requirements/test.txt
|
| 170 |
+
coverage==5.0
|
| 171 |
+
codecov==2.1
|
| 172 |
+
pytest==6.0
|
| 173 |
+
pytest-cov
|
| 174 |
+
pytest-timeout
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
</details>
|
wemm/lib/python3.10/site-packages/multidict-6.1.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
multidict-6.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
multidict-6.1.0.dist-info/LICENSE,sha256=k9Ealo4vDzY3PECBH_bSDhc_WMPKtYhM1mF7v9eVSSo,611
|
| 3 |
+
multidict-6.1.0.dist-info/METADATA,sha256=OnCx5DR4XPf64GIDK4XmcA2e7HLQ_784vMfEQy287kM,4979
|
| 4 |
+
multidict-6.1.0.dist-info/RECORD,,
|
| 5 |
+
multidict-6.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
multidict-6.1.0.dist-info/WHEEL,sha256=K6ps4aVUsEay-13wCJy8H3VKOTWNlXTmCBW4TF80uCE,151
|
| 7 |
+
multidict-6.1.0.dist-info/top_level.txt,sha256=-euDElkk5_qkmfIJ7WiqCab02ZlSFZWynejKg59qZQQ,10
|
| 8 |
+
multidict/__init__.py,sha256=p60Ag5UVACSli1txazSi85foCmHN-cg3qZDCuWdOKng,928
|
| 9 |
+
multidict/__init__.pyi,sha256=SbgC2ew1NvNXWlRKs9o0KhW4moozgMqgQ0OA4Re5JQQ,4840
|
| 10 |
+
multidict/__pycache__/__init__.cpython-310.pyc,,
|
| 11 |
+
multidict/__pycache__/_abc.cpython-310.pyc,,
|
| 12 |
+
multidict/__pycache__/_compat.cpython-310.pyc,,
|
| 13 |
+
multidict/__pycache__/_multidict_base.cpython-310.pyc,,
|
| 14 |
+
multidict/__pycache__/_multidict_py.cpython-310.pyc,,
|
| 15 |
+
multidict/_abc.py,sha256=Zvnrn4SBkrv4QTD7-ZzqNcoxw0f8KStLMPzGvBuGT2w,1190
|
| 16 |
+
multidict/_compat.py,sha256=uCNUpVHJSFOiKUJmRcz3SDqMpkb37C_csc29ijr8Evo,352
|
| 17 |
+
multidict/_multidict.cpython-310-x86_64-linux-gnu.so,sha256=PM5Jz9d2OytBpQNf2J2rbDXasWF9b9M4abzFOc3c5xI,394656
|
| 18 |
+
multidict/_multidict_base.py,sha256=ZndtnZ5oc1sODKmXsv6F9kWvVNCda9xAEEFXkaPoFoA,3979
|
| 19 |
+
multidict/_multidict_py.py,sha256=57h4sYrRIu7EjMX4YpHVIZVrV9-q1KCW3F6rao10D3U,15050
|
| 20 |
+
multidict/py.typed,sha256=e9bmbH3UFxsabQrnNFPG9qxIXztwbcM6IKDYnvZwprY,15
|
wemm/lib/python3.10/site-packages/networkx-3.4.2.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
wemm/lib/python3.10/site-packages/networkx-3.4.2.dist-info/METADATA
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: networkx
|
| 3 |
+
Version: 3.4.2
|
| 4 |
+
Summary: Python package for creating and manipulating graphs and networks
|
| 5 |
+
Author-email: Aric Hagberg <hagberg@lanl.gov>
|
| 6 |
+
Maintainer-email: NetworkX Developers <networkx-discuss@googlegroups.com>
|
| 7 |
+
Project-URL: Homepage, https://networkx.org/
|
| 8 |
+
Project-URL: Bug Tracker, https://github.com/networkx/networkx/issues
|
| 9 |
+
Project-URL: Documentation, https://networkx.org/documentation/stable/
|
| 10 |
+
Project-URL: Source Code, https://github.com/networkx/networkx
|
| 11 |
+
Keywords: Networks,Graph Theory,Mathematics,network,graph,discrete mathematics,math
|
| 12 |
+
Platform: Linux
|
| 13 |
+
Platform: Mac OSX
|
| 14 |
+
Platform: Windows
|
| 15 |
+
Platform: Unix
|
| 16 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: Intended Audience :: Science/Research
|
| 19 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 20 |
+
Classifier: Operating System :: OS Independent
|
| 21 |
+
Classifier: Programming Language :: Python :: 3
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 26 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
| 29 |
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
| 30 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 31 |
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
| 32 |
+
Requires-Python: >=3.10
|
| 33 |
+
Description-Content-Type: text/x-rst
|
| 34 |
+
License-File: LICENSE.txt
|
| 35 |
+
Provides-Extra: default
|
| 36 |
+
Requires-Dist: numpy >=1.24 ; extra == 'default'
|
| 37 |
+
Requires-Dist: scipy !=1.11.0,!=1.11.1,>=1.10 ; extra == 'default'
|
| 38 |
+
Requires-Dist: matplotlib >=3.7 ; extra == 'default'
|
| 39 |
+
Requires-Dist: pandas >=2.0 ; extra == 'default'
|
| 40 |
+
Provides-Extra: developer
|
| 41 |
+
Requires-Dist: changelist ==0.5 ; extra == 'developer'
|
| 42 |
+
Requires-Dist: pre-commit >=3.2 ; extra == 'developer'
|
| 43 |
+
Requires-Dist: mypy >=1.1 ; extra == 'developer'
|
| 44 |
+
Requires-Dist: rtoml ; extra == 'developer'
|
| 45 |
+
Provides-Extra: doc
|
| 46 |
+
Requires-Dist: sphinx >=7.3 ; extra == 'doc'
|
| 47 |
+
Requires-Dist: pydata-sphinx-theme >=0.15 ; extra == 'doc'
|
| 48 |
+
Requires-Dist: sphinx-gallery >=0.16 ; extra == 'doc'
|
| 49 |
+
Requires-Dist: numpydoc >=1.8.0 ; extra == 'doc'
|
| 50 |
+
Requires-Dist: pillow >=9.4 ; extra == 'doc'
|
| 51 |
+
Requires-Dist: texext >=0.6.7 ; extra == 'doc'
|
| 52 |
+
Requires-Dist: myst-nb >=1.1 ; extra == 'doc'
|
| 53 |
+
Requires-Dist: intersphinx-registry ; extra == 'doc'
|
| 54 |
+
Provides-Extra: example
|
| 55 |
+
Requires-Dist: osmnx >=1.9 ; extra == 'example'
|
| 56 |
+
Requires-Dist: momepy >=0.7.2 ; extra == 'example'
|
| 57 |
+
Requires-Dist: contextily >=1.6 ; extra == 'example'
|
| 58 |
+
Requires-Dist: seaborn >=0.13 ; extra == 'example'
|
| 59 |
+
Requires-Dist: cairocffi >=1.7 ; extra == 'example'
|
| 60 |
+
Requires-Dist: igraph >=0.11 ; extra == 'example'
|
| 61 |
+
Requires-Dist: scikit-learn >=1.5 ; extra == 'example'
|
| 62 |
+
Provides-Extra: extra
|
| 63 |
+
Requires-Dist: lxml >=4.6 ; extra == 'extra'
|
| 64 |
+
Requires-Dist: pygraphviz >=1.14 ; extra == 'extra'
|
| 65 |
+
Requires-Dist: pydot >=3.0.1 ; extra == 'extra'
|
| 66 |
+
Requires-Dist: sympy >=1.10 ; extra == 'extra'
|
| 67 |
+
Provides-Extra: test
|
| 68 |
+
Requires-Dist: pytest >=7.2 ; extra == 'test'
|
| 69 |
+
Requires-Dist: pytest-cov >=4.0 ; extra == 'test'
|
| 70 |
+
|
| 71 |
+
NetworkX
|
| 72 |
+
========
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
.. image::
|
| 76 |
+
https://github.com/networkx/networkx/workflows/test/badge.svg?branch=main
|
| 77 |
+
:target: https://github.com/networkx/networkx/actions?query=workflow%3Atest
|
| 78 |
+
|
| 79 |
+
.. image::
|
| 80 |
+
https://codecov.io/gh/networkx/networkx/branch/main/graph/badge.svg?
|
| 81 |
+
:target: https://app.codecov.io/gh/networkx/networkx/branch/main
|
| 82 |
+
|
| 83 |
+
.. image::
|
| 84 |
+
https://img.shields.io/pypi/v/networkx.svg?
|
| 85 |
+
:target: https://pypi.python.org/pypi/networkx
|
| 86 |
+
|
| 87 |
+
.. image::
|
| 88 |
+
https://img.shields.io/pypi/l/networkx.svg?
|
| 89 |
+
:target: https://github.com/networkx/networkx/blob/main/LICENSE.txt
|
| 90 |
+
|
| 91 |
+
.. image::
|
| 92 |
+
https://img.shields.io/pypi/pyversions/networkx.svg?
|
| 93 |
+
:target: https://pypi.python.org/pypi/networkx
|
| 94 |
+
|
| 95 |
+
.. image::
|
| 96 |
+
https://img.shields.io/github/labels/networkx/networkx/good%20first%20issue?color=green&label=contribute
|
| 97 |
+
:target: https://github.com/networkx/networkx/contribute
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
NetworkX is a Python package for the creation, manipulation,
|
| 101 |
+
and study of the structure, dynamics, and functions
|
| 102 |
+
of complex networks.
|
| 103 |
+
|
| 104 |
+
- **Website (including documentation):** https://networkx.org
|
| 105 |
+
- **Mailing list:** https://groups.google.com/forum/#!forum/networkx-discuss
|
| 106 |
+
- **Source:** https://github.com/networkx/networkx
|
| 107 |
+
- **Bug reports:** https://github.com/networkx/networkx/issues
|
| 108 |
+
- **Report a security vulnerability:** https://tidelift.com/security
|
| 109 |
+
- **Tutorial:** https://networkx.org/documentation/latest/tutorial.html
|
| 110 |
+
- **GitHub Discussions:** https://github.com/networkx/networkx/discussions
|
| 111 |
+
- **Discord (Scientific Python) invite link:** https://discord.com/invite/vur45CbwMz
|
| 112 |
+
- **NetworkX meetings calendar (open to all):** https://scientific-python.org/calendars/networkx.ics
|
| 113 |
+
|
| 114 |
+
Simple example
|
| 115 |
+
--------------
|
| 116 |
+
|
| 117 |
+
Find the shortest path between two nodes in an undirected graph:
|
| 118 |
+
|
| 119 |
+
.. code:: pycon
|
| 120 |
+
|
| 121 |
+
>>> import networkx as nx
|
| 122 |
+
>>> G = nx.Graph()
|
| 123 |
+
>>> G.add_edge("A", "B", weight=4)
|
| 124 |
+
>>> G.add_edge("B", "D", weight=2)
|
| 125 |
+
>>> G.add_edge("A", "C", weight=3)
|
| 126 |
+
>>> G.add_edge("C", "D", weight=4)
|
| 127 |
+
>>> nx.shortest_path(G, "A", "D", weight="weight")
|
| 128 |
+
['A', 'B', 'D']
|
| 129 |
+
|
| 130 |
+
Install
|
| 131 |
+
-------
|
| 132 |
+
|
| 133 |
+
Install the latest released version of NetworkX:
|
| 134 |
+
|
| 135 |
+
.. code:: shell
|
| 136 |
+
|
| 137 |
+
$ pip install networkx
|
| 138 |
+
|
| 139 |
+
Install with all optional dependencies:
|
| 140 |
+
|
| 141 |
+
.. code:: shell
|
| 142 |
+
|
| 143 |
+
$ pip install networkx[default]
|
| 144 |
+
|
| 145 |
+
For additional details,
|
| 146 |
+
please see the `installation guide <https://networkx.org/documentation/stable/install.html>`_.
|
| 147 |
+
|
| 148 |
+
Bugs
|
| 149 |
+
----
|
| 150 |
+
|
| 151 |
+
Please report any bugs that you find `here <https://github.com/networkx/networkx/issues>`_.
|
| 152 |
+
Or, even better, fork the repository on `GitHub <https://github.com/networkx/networkx>`_
|
| 153 |
+
and create a pull request (PR). We welcome all changes, big or small, and we
|
| 154 |
+
will help you make the PR if you are new to `git` (just ask on the issue and/or
|
| 155 |
+
see the `contributor guide <https://networkx.org/documentation/latest/developer/contribute.html>`_).
|
| 156 |
+
|
| 157 |
+
License
|
| 158 |
+
-------
|
| 159 |
+
|
| 160 |
+
Released under the `3-Clause BSD license <https://github.com/networkx/networkx/blob/main/LICENSE.txt>`_::
|
| 161 |
+
|
| 162 |
+
Copyright (C) 2004-2024 NetworkX Developers
|
| 163 |
+
Aric Hagberg <hagberg@lanl.gov>
|
| 164 |
+
Dan Schult <dschult@colgate.edu>
|
| 165 |
+
Pieter Swart <swart@lanl.gov>
|