1*635a8641SAndroid Build Coastguard Worker# -*- coding: utf-8 -*- 2*635a8641SAndroid Build Coastguard Worker""" 3*635a8641SAndroid Build Coastguard Worker jinja2.environment 4*635a8641SAndroid Build Coastguard Worker ~~~~~~~~~~~~~~~~~~ 5*635a8641SAndroid Build Coastguard Worker 6*635a8641SAndroid Build Coastguard Worker Provides a class that holds runtime and parsing time options. 7*635a8641SAndroid Build Coastguard Worker 8*635a8641SAndroid Build Coastguard Worker :copyright: (c) 2017 by the Jinja Team. 9*635a8641SAndroid Build Coastguard Worker :license: BSD, see LICENSE for more details. 10*635a8641SAndroid Build Coastguard Worker""" 11*635a8641SAndroid Build Coastguard Workerimport os 12*635a8641SAndroid Build Coastguard Workerimport sys 13*635a8641SAndroid Build Coastguard Workerimport weakref 14*635a8641SAndroid Build Coastguard Workerfrom functools import reduce, partial 15*635a8641SAndroid Build Coastguard Workerfrom jinja2 import nodes 16*635a8641SAndroid Build Coastguard Workerfrom jinja2.defaults import BLOCK_START_STRING, \ 17*635a8641SAndroid Build Coastguard Worker BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \ 18*635a8641SAndroid Build Coastguard Worker COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \ 19*635a8641SAndroid Build Coastguard Worker LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \ 20*635a8641SAndroid Build Coastguard Worker DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \ 21*635a8641SAndroid Build Coastguard Worker DEFAULT_POLICIES, KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS 22*635a8641SAndroid Build Coastguard Workerfrom jinja2.lexer import get_lexer, TokenStream 23*635a8641SAndroid Build Coastguard Workerfrom jinja2.parser import Parser 24*635a8641SAndroid Build Coastguard Workerfrom jinja2.nodes import EvalContext 25*635a8641SAndroid Build Coastguard Workerfrom jinja2.compiler import generate, CodeGenerator 26*635a8641SAndroid Build Coastguard Workerfrom jinja2.runtime import Undefined, new_context, Context 27*635a8641SAndroid Build Coastguard Workerfrom jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \ 28*635a8641SAndroid Build Coastguard Worker TemplatesNotFound, TemplateRuntimeError 29*635a8641SAndroid Build Coastguard Workerfrom jinja2.utils import import_string, LRUCache, Markup, missing, \ 30*635a8641SAndroid Build Coastguard Worker concat, consume, internalcode, have_async_gen 31*635a8641SAndroid Build Coastguard Workerfrom jinja2._compat import imap, ifilter, string_types, iteritems, \ 32*635a8641SAndroid Build Coastguard Worker text_type, reraise, implements_iterator, implements_to_string, \ 33*635a8641SAndroid Build Coastguard Worker encode_filename, PY2, PYPY 34*635a8641SAndroid Build Coastguard Worker 35*635a8641SAndroid Build Coastguard Worker 36*635a8641SAndroid Build Coastguard Worker# for direct template usage we have up to ten living environments 37*635a8641SAndroid Build Coastguard Worker_spontaneous_environments = LRUCache(10) 38*635a8641SAndroid Build Coastguard Worker 39*635a8641SAndroid Build Coastguard Worker# the function to create jinja traceback objects. This is dynamically 40*635a8641SAndroid Build Coastguard Worker# imported on the first exception in the exception handler. 41*635a8641SAndroid Build Coastguard Worker_make_traceback = None 42*635a8641SAndroid Build Coastguard Worker 43*635a8641SAndroid Build Coastguard Worker 44*635a8641SAndroid Build Coastguard Workerdef get_spontaneous_environment(*args): 45*635a8641SAndroid Build Coastguard Worker """Return a new spontaneous environment. A spontaneous environment is an 46*635a8641SAndroid Build Coastguard Worker unnamed and unaccessible (in theory) environment that is used for 47*635a8641SAndroid Build Coastguard Worker templates generated from a string and not from the file system. 48*635a8641SAndroid Build Coastguard Worker """ 49*635a8641SAndroid Build Coastguard Worker try: 50*635a8641SAndroid Build Coastguard Worker env = _spontaneous_environments.get(args) 51*635a8641SAndroid Build Coastguard Worker except TypeError: 52*635a8641SAndroid Build Coastguard Worker return Environment(*args) 53*635a8641SAndroid Build Coastguard Worker if env is not None: 54*635a8641SAndroid Build Coastguard Worker return env 55*635a8641SAndroid Build Coastguard Worker _spontaneous_environments[args] = env = Environment(*args) 56*635a8641SAndroid Build Coastguard Worker env.shared = True 57*635a8641SAndroid Build Coastguard Worker return env 58*635a8641SAndroid Build Coastguard Worker 59*635a8641SAndroid Build Coastguard Worker 60*635a8641SAndroid Build Coastguard Workerdef create_cache(size): 61*635a8641SAndroid Build Coastguard Worker """Return the cache class for the given size.""" 62*635a8641SAndroid Build Coastguard Worker if size == 0: 63*635a8641SAndroid Build Coastguard Worker return None 64*635a8641SAndroid Build Coastguard Worker if size < 0: 65*635a8641SAndroid Build Coastguard Worker return {} 66*635a8641SAndroid Build Coastguard Worker return LRUCache(size) 67*635a8641SAndroid Build Coastguard Worker 68*635a8641SAndroid Build Coastguard Worker 69*635a8641SAndroid Build Coastguard Workerdef copy_cache(cache): 70*635a8641SAndroid Build Coastguard Worker """Create an empty copy of the given cache.""" 71*635a8641SAndroid Build Coastguard Worker if cache is None: 72*635a8641SAndroid Build Coastguard Worker return None 73*635a8641SAndroid Build Coastguard Worker elif type(cache) is dict: 74*635a8641SAndroid Build Coastguard Worker return {} 75*635a8641SAndroid Build Coastguard Worker return LRUCache(cache.capacity) 76*635a8641SAndroid Build Coastguard Worker 77*635a8641SAndroid Build Coastguard Worker 78*635a8641SAndroid Build Coastguard Workerdef load_extensions(environment, extensions): 79*635a8641SAndroid Build Coastguard Worker """Load the extensions from the list and bind it to the environment. 80*635a8641SAndroid Build Coastguard Worker Returns a dict of instantiated environments. 81*635a8641SAndroid Build Coastguard Worker """ 82*635a8641SAndroid Build Coastguard Worker result = {} 83*635a8641SAndroid Build Coastguard Worker for extension in extensions: 84*635a8641SAndroid Build Coastguard Worker if isinstance(extension, string_types): 85*635a8641SAndroid Build Coastguard Worker extension = import_string(extension) 86*635a8641SAndroid Build Coastguard Worker result[extension.identifier] = extension(environment) 87*635a8641SAndroid Build Coastguard Worker return result 88*635a8641SAndroid Build Coastguard Worker 89*635a8641SAndroid Build Coastguard Worker 90*635a8641SAndroid Build Coastguard Workerdef fail_for_missing_callable(string, name): 91*635a8641SAndroid Build Coastguard Worker msg = string % name 92*635a8641SAndroid Build Coastguard Worker if isinstance(name, Undefined): 93*635a8641SAndroid Build Coastguard Worker try: 94*635a8641SAndroid Build Coastguard Worker name._fail_with_undefined_error() 95*635a8641SAndroid Build Coastguard Worker except Exception as e: 96*635a8641SAndroid Build Coastguard Worker msg = '%s (%s; did you forget to quote the callable name?)' % (msg, e) 97*635a8641SAndroid Build Coastguard Worker raise TemplateRuntimeError(msg) 98*635a8641SAndroid Build Coastguard Worker 99*635a8641SAndroid Build Coastguard Worker 100*635a8641SAndroid Build Coastguard Workerdef _environment_sanity_check(environment): 101*635a8641SAndroid Build Coastguard Worker """Perform a sanity check on the environment.""" 102*635a8641SAndroid Build Coastguard Worker assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 103*635a8641SAndroid Build Coastguard Worker 'be a subclass of undefined because filters depend on it.' 104*635a8641SAndroid Build Coastguard Worker assert environment.block_start_string != \ 105*635a8641SAndroid Build Coastguard Worker environment.variable_start_string != \ 106*635a8641SAndroid Build Coastguard Worker environment.comment_start_string, 'block, variable and comment ' \ 107*635a8641SAndroid Build Coastguard Worker 'start strings must be different' 108*635a8641SAndroid Build Coastguard Worker assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ 109*635a8641SAndroid Build Coastguard Worker 'newline_sequence set to unknown line ending string.' 110*635a8641SAndroid Build Coastguard Worker return environment 111*635a8641SAndroid Build Coastguard Worker 112*635a8641SAndroid Build Coastguard Worker 113*635a8641SAndroid Build Coastguard Workerclass Environment(object): 114*635a8641SAndroid Build Coastguard Worker r"""The core component of Jinja is the `Environment`. It contains 115*635a8641SAndroid Build Coastguard Worker important shared variables like configuration, filters, tests, 116*635a8641SAndroid Build Coastguard Worker globals and others. Instances of this class may be modified if 117*635a8641SAndroid Build Coastguard Worker they are not shared and if no template was loaded so far. 118*635a8641SAndroid Build Coastguard Worker Modifications on environments after the first template was loaded 119*635a8641SAndroid Build Coastguard Worker will lead to surprising effects and undefined behavior. 120*635a8641SAndroid Build Coastguard Worker 121*635a8641SAndroid Build Coastguard Worker Here are the possible initialization parameters: 122*635a8641SAndroid Build Coastguard Worker 123*635a8641SAndroid Build Coastguard Worker `block_start_string` 124*635a8641SAndroid Build Coastguard Worker The string marking the beginning of a block. Defaults to ``'{%'``. 125*635a8641SAndroid Build Coastguard Worker 126*635a8641SAndroid Build Coastguard Worker `block_end_string` 127*635a8641SAndroid Build Coastguard Worker The string marking the end of a block. Defaults to ``'%}'``. 128*635a8641SAndroid Build Coastguard Worker 129*635a8641SAndroid Build Coastguard Worker `variable_start_string` 130*635a8641SAndroid Build Coastguard Worker The string marking the beginning of a print statement. 131*635a8641SAndroid Build Coastguard Worker Defaults to ``'{{'``. 132*635a8641SAndroid Build Coastguard Worker 133*635a8641SAndroid Build Coastguard Worker `variable_end_string` 134*635a8641SAndroid Build Coastguard Worker The string marking the end of a print statement. Defaults to 135*635a8641SAndroid Build Coastguard Worker ``'}}'``. 136*635a8641SAndroid Build Coastguard Worker 137*635a8641SAndroid Build Coastguard Worker `comment_start_string` 138*635a8641SAndroid Build Coastguard Worker The string marking the beginning of a comment. Defaults to ``'{#'``. 139*635a8641SAndroid Build Coastguard Worker 140*635a8641SAndroid Build Coastguard Worker `comment_end_string` 141*635a8641SAndroid Build Coastguard Worker The string marking the end of a comment. Defaults to ``'#}'``. 142*635a8641SAndroid Build Coastguard Worker 143*635a8641SAndroid Build Coastguard Worker `line_statement_prefix` 144*635a8641SAndroid Build Coastguard Worker If given and a string, this will be used as prefix for line based 145*635a8641SAndroid Build Coastguard Worker statements. See also :ref:`line-statements`. 146*635a8641SAndroid Build Coastguard Worker 147*635a8641SAndroid Build Coastguard Worker `line_comment_prefix` 148*635a8641SAndroid Build Coastguard Worker If given and a string, this will be used as prefix for line based 149*635a8641SAndroid Build Coastguard Worker comments. See also :ref:`line-statements`. 150*635a8641SAndroid Build Coastguard Worker 151*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.2 152*635a8641SAndroid Build Coastguard Worker 153*635a8641SAndroid Build Coastguard Worker `trim_blocks` 154*635a8641SAndroid Build Coastguard Worker If this is set to ``True`` the first newline after a block is 155*635a8641SAndroid Build Coastguard Worker removed (block, not variable tag!). Defaults to `False`. 156*635a8641SAndroid Build Coastguard Worker 157*635a8641SAndroid Build Coastguard Worker `lstrip_blocks` 158*635a8641SAndroid Build Coastguard Worker If this is set to ``True`` leading spaces and tabs are stripped 159*635a8641SAndroid Build Coastguard Worker from the start of a line to a block. Defaults to `False`. 160*635a8641SAndroid Build Coastguard Worker 161*635a8641SAndroid Build Coastguard Worker `newline_sequence` 162*635a8641SAndroid Build Coastguard Worker The sequence that starts a newline. Must be one of ``'\r'``, 163*635a8641SAndroid Build Coastguard Worker ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a 164*635a8641SAndroid Build Coastguard Worker useful default for Linux and OS X systems as well as web 165*635a8641SAndroid Build Coastguard Worker applications. 166*635a8641SAndroid Build Coastguard Worker 167*635a8641SAndroid Build Coastguard Worker `keep_trailing_newline` 168*635a8641SAndroid Build Coastguard Worker Preserve the trailing newline when rendering templates. 169*635a8641SAndroid Build Coastguard Worker The default is ``False``, which causes a single newline, 170*635a8641SAndroid Build Coastguard Worker if present, to be stripped from the end of the template. 171*635a8641SAndroid Build Coastguard Worker 172*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.7 173*635a8641SAndroid Build Coastguard Worker 174*635a8641SAndroid Build Coastguard Worker `extensions` 175*635a8641SAndroid Build Coastguard Worker List of Jinja extensions to use. This can either be import paths 176*635a8641SAndroid Build Coastguard Worker as strings or extension classes. For more information have a 177*635a8641SAndroid Build Coastguard Worker look at :ref:`the extensions documentation <jinja-extensions>`. 178*635a8641SAndroid Build Coastguard Worker 179*635a8641SAndroid Build Coastguard Worker `optimized` 180*635a8641SAndroid Build Coastguard Worker should the optimizer be enabled? Default is ``True``. 181*635a8641SAndroid Build Coastguard Worker 182*635a8641SAndroid Build Coastguard Worker `undefined` 183*635a8641SAndroid Build Coastguard Worker :class:`Undefined` or a subclass of it that is used to represent 184*635a8641SAndroid Build Coastguard Worker undefined values in the template. 185*635a8641SAndroid Build Coastguard Worker 186*635a8641SAndroid Build Coastguard Worker `finalize` 187*635a8641SAndroid Build Coastguard Worker A callable that can be used to process the result of a variable 188*635a8641SAndroid Build Coastguard Worker expression before it is output. For example one can convert 189*635a8641SAndroid Build Coastguard Worker ``None`` implicitly into an empty string here. 190*635a8641SAndroid Build Coastguard Worker 191*635a8641SAndroid Build Coastguard Worker `autoescape` 192*635a8641SAndroid Build Coastguard Worker If set to ``True`` the XML/HTML autoescaping feature is enabled by 193*635a8641SAndroid Build Coastguard Worker default. For more details about autoescaping see 194*635a8641SAndroid Build Coastguard Worker :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also 195*635a8641SAndroid Build Coastguard Worker be a callable that is passed the template name and has to 196*635a8641SAndroid Build Coastguard Worker return ``True`` or ``False`` depending on autoescape should be 197*635a8641SAndroid Build Coastguard Worker enabled by default. 198*635a8641SAndroid Build Coastguard Worker 199*635a8641SAndroid Build Coastguard Worker .. versionchanged:: 2.4 200*635a8641SAndroid Build Coastguard Worker `autoescape` can now be a function 201*635a8641SAndroid Build Coastguard Worker 202*635a8641SAndroid Build Coastguard Worker `loader` 203*635a8641SAndroid Build Coastguard Worker The template loader for this environment. 204*635a8641SAndroid Build Coastguard Worker 205*635a8641SAndroid Build Coastguard Worker `cache_size` 206*635a8641SAndroid Build Coastguard Worker The size of the cache. Per default this is ``400`` which means 207*635a8641SAndroid Build Coastguard Worker that if more than 400 templates are loaded the loader will clean 208*635a8641SAndroid Build Coastguard Worker out the least recently used template. If the cache size is set to 209*635a8641SAndroid Build Coastguard Worker ``0`` templates are recompiled all the time, if the cache size is 210*635a8641SAndroid Build Coastguard Worker ``-1`` the cache will not be cleaned. 211*635a8641SAndroid Build Coastguard Worker 212*635a8641SAndroid Build Coastguard Worker .. versionchanged:: 2.8 213*635a8641SAndroid Build Coastguard Worker The cache size was increased to 400 from a low 50. 214*635a8641SAndroid Build Coastguard Worker 215*635a8641SAndroid Build Coastguard Worker `auto_reload` 216*635a8641SAndroid Build Coastguard Worker Some loaders load templates from locations where the template 217*635a8641SAndroid Build Coastguard Worker sources may change (ie: file system or database). If 218*635a8641SAndroid Build Coastguard Worker ``auto_reload`` is set to ``True`` (default) every time a template is 219*635a8641SAndroid Build Coastguard Worker requested the loader checks if the source changed and if yes, it 220*635a8641SAndroid Build Coastguard Worker will reload the template. For higher performance it's possible to 221*635a8641SAndroid Build Coastguard Worker disable that. 222*635a8641SAndroid Build Coastguard Worker 223*635a8641SAndroid Build Coastguard Worker `bytecode_cache` 224*635a8641SAndroid Build Coastguard Worker If set to a bytecode cache object, this object will provide a 225*635a8641SAndroid Build Coastguard Worker cache for the internal Jinja bytecode so that templates don't 226*635a8641SAndroid Build Coastguard Worker have to be parsed if they were not changed. 227*635a8641SAndroid Build Coastguard Worker 228*635a8641SAndroid Build Coastguard Worker See :ref:`bytecode-cache` for more information. 229*635a8641SAndroid Build Coastguard Worker 230*635a8641SAndroid Build Coastguard Worker `enable_async` 231*635a8641SAndroid Build Coastguard Worker If set to true this enables async template execution which allows 232*635a8641SAndroid Build Coastguard Worker you to take advantage of newer Python features. This requires 233*635a8641SAndroid Build Coastguard Worker Python 3.6 or later. 234*635a8641SAndroid Build Coastguard Worker """ 235*635a8641SAndroid Build Coastguard Worker 236*635a8641SAndroid Build Coastguard Worker #: if this environment is sandboxed. Modifying this variable won't make 237*635a8641SAndroid Build Coastguard Worker #: the environment sandboxed though. For a real sandboxed environment 238*635a8641SAndroid Build Coastguard Worker #: have a look at jinja2.sandbox. This flag alone controls the code 239*635a8641SAndroid Build Coastguard Worker #: generation by the compiler. 240*635a8641SAndroid Build Coastguard Worker sandboxed = False 241*635a8641SAndroid Build Coastguard Worker 242*635a8641SAndroid Build Coastguard Worker #: True if the environment is just an overlay 243*635a8641SAndroid Build Coastguard Worker overlayed = False 244*635a8641SAndroid Build Coastguard Worker 245*635a8641SAndroid Build Coastguard Worker #: the environment this environment is linked to if it is an overlay 246*635a8641SAndroid Build Coastguard Worker linked_to = None 247*635a8641SAndroid Build Coastguard Worker 248*635a8641SAndroid Build Coastguard Worker #: shared environments have this set to `True`. A shared environment 249*635a8641SAndroid Build Coastguard Worker #: must not be modified 250*635a8641SAndroid Build Coastguard Worker shared = False 251*635a8641SAndroid Build Coastguard Worker 252*635a8641SAndroid Build Coastguard Worker #: these are currently EXPERIMENTAL undocumented features. 253*635a8641SAndroid Build Coastguard Worker exception_handler = None 254*635a8641SAndroid Build Coastguard Worker exception_formatter = None 255*635a8641SAndroid Build Coastguard Worker 256*635a8641SAndroid Build Coastguard Worker #: the class that is used for code generation. See 257*635a8641SAndroid Build Coastguard Worker #: :class:`~jinja2.compiler.CodeGenerator` for more information. 258*635a8641SAndroid Build Coastguard Worker code_generator_class = CodeGenerator 259*635a8641SAndroid Build Coastguard Worker 260*635a8641SAndroid Build Coastguard Worker #: the context class thatis used for templates. See 261*635a8641SAndroid Build Coastguard Worker #: :class:`~jinja2.runtime.Context` for more information. 262*635a8641SAndroid Build Coastguard Worker context_class = Context 263*635a8641SAndroid Build Coastguard Worker 264*635a8641SAndroid Build Coastguard Worker def __init__(self, 265*635a8641SAndroid Build Coastguard Worker block_start_string=BLOCK_START_STRING, 266*635a8641SAndroid Build Coastguard Worker block_end_string=BLOCK_END_STRING, 267*635a8641SAndroid Build Coastguard Worker variable_start_string=VARIABLE_START_STRING, 268*635a8641SAndroid Build Coastguard Worker variable_end_string=VARIABLE_END_STRING, 269*635a8641SAndroid Build Coastguard Worker comment_start_string=COMMENT_START_STRING, 270*635a8641SAndroid Build Coastguard Worker comment_end_string=COMMENT_END_STRING, 271*635a8641SAndroid Build Coastguard Worker line_statement_prefix=LINE_STATEMENT_PREFIX, 272*635a8641SAndroid Build Coastguard Worker line_comment_prefix=LINE_COMMENT_PREFIX, 273*635a8641SAndroid Build Coastguard Worker trim_blocks=TRIM_BLOCKS, 274*635a8641SAndroid Build Coastguard Worker lstrip_blocks=LSTRIP_BLOCKS, 275*635a8641SAndroid Build Coastguard Worker newline_sequence=NEWLINE_SEQUENCE, 276*635a8641SAndroid Build Coastguard Worker keep_trailing_newline=KEEP_TRAILING_NEWLINE, 277*635a8641SAndroid Build Coastguard Worker extensions=(), 278*635a8641SAndroid Build Coastguard Worker optimized=True, 279*635a8641SAndroid Build Coastguard Worker undefined=Undefined, 280*635a8641SAndroid Build Coastguard Worker finalize=None, 281*635a8641SAndroid Build Coastguard Worker autoescape=False, 282*635a8641SAndroid Build Coastguard Worker loader=None, 283*635a8641SAndroid Build Coastguard Worker cache_size=400, 284*635a8641SAndroid Build Coastguard Worker auto_reload=True, 285*635a8641SAndroid Build Coastguard Worker bytecode_cache=None, 286*635a8641SAndroid Build Coastguard Worker enable_async=False): 287*635a8641SAndroid Build Coastguard Worker # !!Important notice!! 288*635a8641SAndroid Build Coastguard Worker # The constructor accepts quite a few arguments that should be 289*635a8641SAndroid Build Coastguard Worker # passed by keyword rather than position. However it's important to 290*635a8641SAndroid Build Coastguard Worker # not change the order of arguments because it's used at least 291*635a8641SAndroid Build Coastguard Worker # internally in those cases: 292*635a8641SAndroid Build Coastguard Worker # - spontaneous environments (i18n extension and Template) 293*635a8641SAndroid Build Coastguard Worker # - unittests 294*635a8641SAndroid Build Coastguard Worker # If parameter changes are required only add parameters at the end 295*635a8641SAndroid Build Coastguard Worker # and don't change the arguments (or the defaults!) of the arguments 296*635a8641SAndroid Build Coastguard Worker # existing already. 297*635a8641SAndroid Build Coastguard Worker 298*635a8641SAndroid Build Coastguard Worker # lexer / parser information 299*635a8641SAndroid Build Coastguard Worker self.block_start_string = block_start_string 300*635a8641SAndroid Build Coastguard Worker self.block_end_string = block_end_string 301*635a8641SAndroid Build Coastguard Worker self.variable_start_string = variable_start_string 302*635a8641SAndroid Build Coastguard Worker self.variable_end_string = variable_end_string 303*635a8641SAndroid Build Coastguard Worker self.comment_start_string = comment_start_string 304*635a8641SAndroid Build Coastguard Worker self.comment_end_string = comment_end_string 305*635a8641SAndroid Build Coastguard Worker self.line_statement_prefix = line_statement_prefix 306*635a8641SAndroid Build Coastguard Worker self.line_comment_prefix = line_comment_prefix 307*635a8641SAndroid Build Coastguard Worker self.trim_blocks = trim_blocks 308*635a8641SAndroid Build Coastguard Worker self.lstrip_blocks = lstrip_blocks 309*635a8641SAndroid Build Coastguard Worker self.newline_sequence = newline_sequence 310*635a8641SAndroid Build Coastguard Worker self.keep_trailing_newline = keep_trailing_newline 311*635a8641SAndroid Build Coastguard Worker 312*635a8641SAndroid Build Coastguard Worker # runtime information 313*635a8641SAndroid Build Coastguard Worker self.undefined = undefined 314*635a8641SAndroid Build Coastguard Worker self.optimized = optimized 315*635a8641SAndroid Build Coastguard Worker self.finalize = finalize 316*635a8641SAndroid Build Coastguard Worker self.autoescape = autoescape 317*635a8641SAndroid Build Coastguard Worker 318*635a8641SAndroid Build Coastguard Worker # defaults 319*635a8641SAndroid Build Coastguard Worker self.filters = DEFAULT_FILTERS.copy() 320*635a8641SAndroid Build Coastguard Worker self.tests = DEFAULT_TESTS.copy() 321*635a8641SAndroid Build Coastguard Worker self.globals = DEFAULT_NAMESPACE.copy() 322*635a8641SAndroid Build Coastguard Worker 323*635a8641SAndroid Build Coastguard Worker # set the loader provided 324*635a8641SAndroid Build Coastguard Worker self.loader = loader 325*635a8641SAndroid Build Coastguard Worker self.cache = create_cache(cache_size) 326*635a8641SAndroid Build Coastguard Worker self.bytecode_cache = bytecode_cache 327*635a8641SAndroid Build Coastguard Worker self.auto_reload = auto_reload 328*635a8641SAndroid Build Coastguard Worker 329*635a8641SAndroid Build Coastguard Worker # configurable policies 330*635a8641SAndroid Build Coastguard Worker self.policies = DEFAULT_POLICIES.copy() 331*635a8641SAndroid Build Coastguard Worker 332*635a8641SAndroid Build Coastguard Worker # load extensions 333*635a8641SAndroid Build Coastguard Worker self.extensions = load_extensions(self, extensions) 334*635a8641SAndroid Build Coastguard Worker 335*635a8641SAndroid Build Coastguard Worker self.enable_async = enable_async 336*635a8641SAndroid Build Coastguard Worker self.is_async = self.enable_async and have_async_gen 337*635a8641SAndroid Build Coastguard Worker 338*635a8641SAndroid Build Coastguard Worker _environment_sanity_check(self) 339*635a8641SAndroid Build Coastguard Worker 340*635a8641SAndroid Build Coastguard Worker def add_extension(self, extension): 341*635a8641SAndroid Build Coastguard Worker """Adds an extension after the environment was created. 342*635a8641SAndroid Build Coastguard Worker 343*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.5 344*635a8641SAndroid Build Coastguard Worker """ 345*635a8641SAndroid Build Coastguard Worker self.extensions.update(load_extensions(self, [extension])) 346*635a8641SAndroid Build Coastguard Worker 347*635a8641SAndroid Build Coastguard Worker def extend(self, **attributes): 348*635a8641SAndroid Build Coastguard Worker """Add the items to the instance of the environment if they do not exist 349*635a8641SAndroid Build Coastguard Worker yet. This is used by :ref:`extensions <writing-extensions>` to register 350*635a8641SAndroid Build Coastguard Worker callbacks and configuration values without breaking inheritance. 351*635a8641SAndroid Build Coastguard Worker """ 352*635a8641SAndroid Build Coastguard Worker for key, value in iteritems(attributes): 353*635a8641SAndroid Build Coastguard Worker if not hasattr(self, key): 354*635a8641SAndroid Build Coastguard Worker setattr(self, key, value) 355*635a8641SAndroid Build Coastguard Worker 356*635a8641SAndroid Build Coastguard Worker def overlay(self, block_start_string=missing, block_end_string=missing, 357*635a8641SAndroid Build Coastguard Worker variable_start_string=missing, variable_end_string=missing, 358*635a8641SAndroid Build Coastguard Worker comment_start_string=missing, comment_end_string=missing, 359*635a8641SAndroid Build Coastguard Worker line_statement_prefix=missing, line_comment_prefix=missing, 360*635a8641SAndroid Build Coastguard Worker trim_blocks=missing, lstrip_blocks=missing, 361*635a8641SAndroid Build Coastguard Worker extensions=missing, optimized=missing, 362*635a8641SAndroid Build Coastguard Worker undefined=missing, finalize=missing, autoescape=missing, 363*635a8641SAndroid Build Coastguard Worker loader=missing, cache_size=missing, auto_reload=missing, 364*635a8641SAndroid Build Coastguard Worker bytecode_cache=missing): 365*635a8641SAndroid Build Coastguard Worker """Create a new overlay environment that shares all the data with the 366*635a8641SAndroid Build Coastguard Worker current environment except for cache and the overridden attributes. 367*635a8641SAndroid Build Coastguard Worker Extensions cannot be removed for an overlayed environment. An overlayed 368*635a8641SAndroid Build Coastguard Worker environment automatically gets all the extensions of the environment it 369*635a8641SAndroid Build Coastguard Worker is linked to plus optional extra extensions. 370*635a8641SAndroid Build Coastguard Worker 371*635a8641SAndroid Build Coastguard Worker Creating overlays should happen after the initial environment was set 372*635a8641SAndroid Build Coastguard Worker up completely. Not all attributes are truly linked, some are just 373*635a8641SAndroid Build Coastguard Worker copied over so modifications on the original environment may not shine 374*635a8641SAndroid Build Coastguard Worker through. 375*635a8641SAndroid Build Coastguard Worker """ 376*635a8641SAndroid Build Coastguard Worker args = dict(locals()) 377*635a8641SAndroid Build Coastguard Worker del args['self'], args['cache_size'], args['extensions'] 378*635a8641SAndroid Build Coastguard Worker 379*635a8641SAndroid Build Coastguard Worker rv = object.__new__(self.__class__) 380*635a8641SAndroid Build Coastguard Worker rv.__dict__.update(self.__dict__) 381*635a8641SAndroid Build Coastguard Worker rv.overlayed = True 382*635a8641SAndroid Build Coastguard Worker rv.linked_to = self 383*635a8641SAndroid Build Coastguard Worker 384*635a8641SAndroid Build Coastguard Worker for key, value in iteritems(args): 385*635a8641SAndroid Build Coastguard Worker if value is not missing: 386*635a8641SAndroid Build Coastguard Worker setattr(rv, key, value) 387*635a8641SAndroid Build Coastguard Worker 388*635a8641SAndroid Build Coastguard Worker if cache_size is not missing: 389*635a8641SAndroid Build Coastguard Worker rv.cache = create_cache(cache_size) 390*635a8641SAndroid Build Coastguard Worker else: 391*635a8641SAndroid Build Coastguard Worker rv.cache = copy_cache(self.cache) 392*635a8641SAndroid Build Coastguard Worker 393*635a8641SAndroid Build Coastguard Worker rv.extensions = {} 394*635a8641SAndroid Build Coastguard Worker for key, value in iteritems(self.extensions): 395*635a8641SAndroid Build Coastguard Worker rv.extensions[key] = value.bind(rv) 396*635a8641SAndroid Build Coastguard Worker if extensions is not missing: 397*635a8641SAndroid Build Coastguard Worker rv.extensions.update(load_extensions(rv, extensions)) 398*635a8641SAndroid Build Coastguard Worker 399*635a8641SAndroid Build Coastguard Worker return _environment_sanity_check(rv) 400*635a8641SAndroid Build Coastguard Worker 401*635a8641SAndroid Build Coastguard Worker lexer = property(get_lexer, doc="The lexer for this environment.") 402*635a8641SAndroid Build Coastguard Worker 403*635a8641SAndroid Build Coastguard Worker def iter_extensions(self): 404*635a8641SAndroid Build Coastguard Worker """Iterates over the extensions by priority.""" 405*635a8641SAndroid Build Coastguard Worker return iter(sorted(self.extensions.values(), 406*635a8641SAndroid Build Coastguard Worker key=lambda x: x.priority)) 407*635a8641SAndroid Build Coastguard Worker 408*635a8641SAndroid Build Coastguard Worker def getitem(self, obj, argument): 409*635a8641SAndroid Build Coastguard Worker """Get an item or attribute of an object but prefer the item.""" 410*635a8641SAndroid Build Coastguard Worker try: 411*635a8641SAndroid Build Coastguard Worker return obj[argument] 412*635a8641SAndroid Build Coastguard Worker except (AttributeError, TypeError, LookupError): 413*635a8641SAndroid Build Coastguard Worker if isinstance(argument, string_types): 414*635a8641SAndroid Build Coastguard Worker try: 415*635a8641SAndroid Build Coastguard Worker attr = str(argument) 416*635a8641SAndroid Build Coastguard Worker except Exception: 417*635a8641SAndroid Build Coastguard Worker pass 418*635a8641SAndroid Build Coastguard Worker else: 419*635a8641SAndroid Build Coastguard Worker try: 420*635a8641SAndroid Build Coastguard Worker return getattr(obj, attr) 421*635a8641SAndroid Build Coastguard Worker except AttributeError: 422*635a8641SAndroid Build Coastguard Worker pass 423*635a8641SAndroid Build Coastguard Worker return self.undefined(obj=obj, name=argument) 424*635a8641SAndroid Build Coastguard Worker 425*635a8641SAndroid Build Coastguard Worker def getattr(self, obj, attribute): 426*635a8641SAndroid Build Coastguard Worker """Get an item or attribute of an object but prefer the attribute. 427*635a8641SAndroid Build Coastguard Worker Unlike :meth:`getitem` the attribute *must* be a bytestring. 428*635a8641SAndroid Build Coastguard Worker """ 429*635a8641SAndroid Build Coastguard Worker try: 430*635a8641SAndroid Build Coastguard Worker return getattr(obj, attribute) 431*635a8641SAndroid Build Coastguard Worker except AttributeError: 432*635a8641SAndroid Build Coastguard Worker pass 433*635a8641SAndroid Build Coastguard Worker try: 434*635a8641SAndroid Build Coastguard Worker return obj[attribute] 435*635a8641SAndroid Build Coastguard Worker except (TypeError, LookupError, AttributeError): 436*635a8641SAndroid Build Coastguard Worker return self.undefined(obj=obj, name=attribute) 437*635a8641SAndroid Build Coastguard Worker 438*635a8641SAndroid Build Coastguard Worker def call_filter(self, name, value, args=None, kwargs=None, 439*635a8641SAndroid Build Coastguard Worker context=None, eval_ctx=None): 440*635a8641SAndroid Build Coastguard Worker """Invokes a filter on a value the same way the compiler does it. 441*635a8641SAndroid Build Coastguard Worker 442*635a8641SAndroid Build Coastguard Worker Note that on Python 3 this might return a coroutine in case the 443*635a8641SAndroid Build Coastguard Worker filter is running from an environment in async mode and the filter 444*635a8641SAndroid Build Coastguard Worker supports async execution. It's your responsibility to await this 445*635a8641SAndroid Build Coastguard Worker if needed. 446*635a8641SAndroid Build Coastguard Worker 447*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.7 448*635a8641SAndroid Build Coastguard Worker """ 449*635a8641SAndroid Build Coastguard Worker func = self.filters.get(name) 450*635a8641SAndroid Build Coastguard Worker if func is None: 451*635a8641SAndroid Build Coastguard Worker fail_for_missing_callable('no filter named %r', name) 452*635a8641SAndroid Build Coastguard Worker args = [value] + list(args or ()) 453*635a8641SAndroid Build Coastguard Worker if getattr(func, 'contextfilter', False): 454*635a8641SAndroid Build Coastguard Worker if context is None: 455*635a8641SAndroid Build Coastguard Worker raise TemplateRuntimeError('Attempted to invoke context ' 456*635a8641SAndroid Build Coastguard Worker 'filter without context') 457*635a8641SAndroid Build Coastguard Worker args.insert(0, context) 458*635a8641SAndroid Build Coastguard Worker elif getattr(func, 'evalcontextfilter', False): 459*635a8641SAndroid Build Coastguard Worker if eval_ctx is None: 460*635a8641SAndroid Build Coastguard Worker if context is not None: 461*635a8641SAndroid Build Coastguard Worker eval_ctx = context.eval_ctx 462*635a8641SAndroid Build Coastguard Worker else: 463*635a8641SAndroid Build Coastguard Worker eval_ctx = EvalContext(self) 464*635a8641SAndroid Build Coastguard Worker args.insert(0, eval_ctx) 465*635a8641SAndroid Build Coastguard Worker elif getattr(func, 'environmentfilter', False): 466*635a8641SAndroid Build Coastguard Worker args.insert(0, self) 467*635a8641SAndroid Build Coastguard Worker return func(*args, **(kwargs or {})) 468*635a8641SAndroid Build Coastguard Worker 469*635a8641SAndroid Build Coastguard Worker def call_test(self, name, value, args=None, kwargs=None): 470*635a8641SAndroid Build Coastguard Worker """Invokes a test on a value the same way the compiler does it. 471*635a8641SAndroid Build Coastguard Worker 472*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.7 473*635a8641SAndroid Build Coastguard Worker """ 474*635a8641SAndroid Build Coastguard Worker func = self.tests.get(name) 475*635a8641SAndroid Build Coastguard Worker if func is None: 476*635a8641SAndroid Build Coastguard Worker fail_for_missing_callable('no test named %r', name) 477*635a8641SAndroid Build Coastguard Worker return func(value, *(args or ()), **(kwargs or {})) 478*635a8641SAndroid Build Coastguard Worker 479*635a8641SAndroid Build Coastguard Worker @internalcode 480*635a8641SAndroid Build Coastguard Worker def parse(self, source, name=None, filename=None): 481*635a8641SAndroid Build Coastguard Worker """Parse the sourcecode and return the abstract syntax tree. This 482*635a8641SAndroid Build Coastguard Worker tree of nodes is used by the compiler to convert the template into 483*635a8641SAndroid Build Coastguard Worker executable source- or bytecode. This is useful for debugging or to 484*635a8641SAndroid Build Coastguard Worker extract information from templates. 485*635a8641SAndroid Build Coastguard Worker 486*635a8641SAndroid Build Coastguard Worker If you are :ref:`developing Jinja2 extensions <writing-extensions>` 487*635a8641SAndroid Build Coastguard Worker this gives you a good overview of the node tree generated. 488*635a8641SAndroid Build Coastguard Worker """ 489*635a8641SAndroid Build Coastguard Worker try: 490*635a8641SAndroid Build Coastguard Worker return self._parse(source, name, filename) 491*635a8641SAndroid Build Coastguard Worker except TemplateSyntaxError: 492*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 493*635a8641SAndroid Build Coastguard Worker self.handle_exception(exc_info, source_hint=source) 494*635a8641SAndroid Build Coastguard Worker 495*635a8641SAndroid Build Coastguard Worker def _parse(self, source, name, filename): 496*635a8641SAndroid Build Coastguard Worker """Internal parsing function used by `parse` and `compile`.""" 497*635a8641SAndroid Build Coastguard Worker return Parser(self, source, name, encode_filename(filename)).parse() 498*635a8641SAndroid Build Coastguard Worker 499*635a8641SAndroid Build Coastguard Worker def lex(self, source, name=None, filename=None): 500*635a8641SAndroid Build Coastguard Worker """Lex the given sourcecode and return a generator that yields 501*635a8641SAndroid Build Coastguard Worker tokens as tuples in the form ``(lineno, token_type, value)``. 502*635a8641SAndroid Build Coastguard Worker This can be useful for :ref:`extension development <writing-extensions>` 503*635a8641SAndroid Build Coastguard Worker and debugging templates. 504*635a8641SAndroid Build Coastguard Worker 505*635a8641SAndroid Build Coastguard Worker This does not perform preprocessing. If you want the preprocessing 506*635a8641SAndroid Build Coastguard Worker of the extensions to be applied you have to filter source through 507*635a8641SAndroid Build Coastguard Worker the :meth:`preprocess` method. 508*635a8641SAndroid Build Coastguard Worker """ 509*635a8641SAndroid Build Coastguard Worker source = text_type(source) 510*635a8641SAndroid Build Coastguard Worker try: 511*635a8641SAndroid Build Coastguard Worker return self.lexer.tokeniter(source, name, filename) 512*635a8641SAndroid Build Coastguard Worker except TemplateSyntaxError: 513*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 514*635a8641SAndroid Build Coastguard Worker self.handle_exception(exc_info, source_hint=source) 515*635a8641SAndroid Build Coastguard Worker 516*635a8641SAndroid Build Coastguard Worker def preprocess(self, source, name=None, filename=None): 517*635a8641SAndroid Build Coastguard Worker """Preprocesses the source with all extensions. This is automatically 518*635a8641SAndroid Build Coastguard Worker called for all parsing and compiling methods but *not* for :meth:`lex` 519*635a8641SAndroid Build Coastguard Worker because there you usually only want the actual source tokenized. 520*635a8641SAndroid Build Coastguard Worker """ 521*635a8641SAndroid Build Coastguard Worker return reduce(lambda s, e: e.preprocess(s, name, filename), 522*635a8641SAndroid Build Coastguard Worker self.iter_extensions(), text_type(source)) 523*635a8641SAndroid Build Coastguard Worker 524*635a8641SAndroid Build Coastguard Worker def _tokenize(self, source, name, filename=None, state=None): 525*635a8641SAndroid Build Coastguard Worker """Called by the parser to do the preprocessing and filtering 526*635a8641SAndroid Build Coastguard Worker for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. 527*635a8641SAndroid Build Coastguard Worker """ 528*635a8641SAndroid Build Coastguard Worker source = self.preprocess(source, name, filename) 529*635a8641SAndroid Build Coastguard Worker stream = self.lexer.tokenize(source, name, filename, state) 530*635a8641SAndroid Build Coastguard Worker for ext in self.iter_extensions(): 531*635a8641SAndroid Build Coastguard Worker stream = ext.filter_stream(stream) 532*635a8641SAndroid Build Coastguard Worker if not isinstance(stream, TokenStream): 533*635a8641SAndroid Build Coastguard Worker stream = TokenStream(stream, name, filename) 534*635a8641SAndroid Build Coastguard Worker return stream 535*635a8641SAndroid Build Coastguard Worker 536*635a8641SAndroid Build Coastguard Worker def _generate(self, source, name, filename, defer_init=False): 537*635a8641SAndroid Build Coastguard Worker """Internal hook that can be overridden to hook a different generate 538*635a8641SAndroid Build Coastguard Worker method in. 539*635a8641SAndroid Build Coastguard Worker 540*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.5 541*635a8641SAndroid Build Coastguard Worker """ 542*635a8641SAndroid Build Coastguard Worker return generate(source, self, name, filename, defer_init=defer_init, 543*635a8641SAndroid Build Coastguard Worker optimized=self.optimized) 544*635a8641SAndroid Build Coastguard Worker 545*635a8641SAndroid Build Coastguard Worker def _compile(self, source, filename): 546*635a8641SAndroid Build Coastguard Worker """Internal hook that can be overridden to hook a different compile 547*635a8641SAndroid Build Coastguard Worker method in. 548*635a8641SAndroid Build Coastguard Worker 549*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.5 550*635a8641SAndroid Build Coastguard Worker """ 551*635a8641SAndroid Build Coastguard Worker return compile(source, filename, 'exec') 552*635a8641SAndroid Build Coastguard Worker 553*635a8641SAndroid Build Coastguard Worker @internalcode 554*635a8641SAndroid Build Coastguard Worker def compile(self, source, name=None, filename=None, raw=False, 555*635a8641SAndroid Build Coastguard Worker defer_init=False): 556*635a8641SAndroid Build Coastguard Worker """Compile a node or template source code. The `name` parameter is 557*635a8641SAndroid Build Coastguard Worker the load name of the template after it was joined using 558*635a8641SAndroid Build Coastguard Worker :meth:`join_path` if necessary, not the filename on the file system. 559*635a8641SAndroid Build Coastguard Worker the `filename` parameter is the estimated filename of the template on 560*635a8641SAndroid Build Coastguard Worker the file system. If the template came from a database or memory this 561*635a8641SAndroid Build Coastguard Worker can be omitted. 562*635a8641SAndroid Build Coastguard Worker 563*635a8641SAndroid Build Coastguard Worker The return value of this method is a python code object. If the `raw` 564*635a8641SAndroid Build Coastguard Worker parameter is `True` the return value will be a string with python 565*635a8641SAndroid Build Coastguard Worker code equivalent to the bytecode returned otherwise. This method is 566*635a8641SAndroid Build Coastguard Worker mainly used internally. 567*635a8641SAndroid Build Coastguard Worker 568*635a8641SAndroid Build Coastguard Worker `defer_init` is use internally to aid the module code generator. This 569*635a8641SAndroid Build Coastguard Worker causes the generated code to be able to import without the global 570*635a8641SAndroid Build Coastguard Worker environment variable to be set. 571*635a8641SAndroid Build Coastguard Worker 572*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.4 573*635a8641SAndroid Build Coastguard Worker `defer_init` parameter added. 574*635a8641SAndroid Build Coastguard Worker """ 575*635a8641SAndroid Build Coastguard Worker source_hint = None 576*635a8641SAndroid Build Coastguard Worker try: 577*635a8641SAndroid Build Coastguard Worker if isinstance(source, string_types): 578*635a8641SAndroid Build Coastguard Worker source_hint = source 579*635a8641SAndroid Build Coastguard Worker source = self._parse(source, name, filename) 580*635a8641SAndroid Build Coastguard Worker source = self._generate(source, name, filename, 581*635a8641SAndroid Build Coastguard Worker defer_init=defer_init) 582*635a8641SAndroid Build Coastguard Worker if raw: 583*635a8641SAndroid Build Coastguard Worker return source 584*635a8641SAndroid Build Coastguard Worker if filename is None: 585*635a8641SAndroid Build Coastguard Worker filename = '<template>' 586*635a8641SAndroid Build Coastguard Worker else: 587*635a8641SAndroid Build Coastguard Worker filename = encode_filename(filename) 588*635a8641SAndroid Build Coastguard Worker return self._compile(source, filename) 589*635a8641SAndroid Build Coastguard Worker except TemplateSyntaxError: 590*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 591*635a8641SAndroid Build Coastguard Worker self.handle_exception(exc_info, source_hint=source_hint) 592*635a8641SAndroid Build Coastguard Worker 593*635a8641SAndroid Build Coastguard Worker def compile_expression(self, source, undefined_to_none=True): 594*635a8641SAndroid Build Coastguard Worker """A handy helper method that returns a callable that accepts keyword 595*635a8641SAndroid Build Coastguard Worker arguments that appear as variables in the expression. If called it 596*635a8641SAndroid Build Coastguard Worker returns the result of the expression. 597*635a8641SAndroid Build Coastguard Worker 598*635a8641SAndroid Build Coastguard Worker This is useful if applications want to use the same rules as Jinja 599*635a8641SAndroid Build Coastguard Worker in template "configuration files" or similar situations. 600*635a8641SAndroid Build Coastguard Worker 601*635a8641SAndroid Build Coastguard Worker Example usage: 602*635a8641SAndroid Build Coastguard Worker 603*635a8641SAndroid Build Coastguard Worker >>> env = Environment() 604*635a8641SAndroid Build Coastguard Worker >>> expr = env.compile_expression('foo == 42') 605*635a8641SAndroid Build Coastguard Worker >>> expr(foo=23) 606*635a8641SAndroid Build Coastguard Worker False 607*635a8641SAndroid Build Coastguard Worker >>> expr(foo=42) 608*635a8641SAndroid Build Coastguard Worker True 609*635a8641SAndroid Build Coastguard Worker 610*635a8641SAndroid Build Coastguard Worker Per default the return value is converted to `None` if the 611*635a8641SAndroid Build Coastguard Worker expression returns an undefined value. This can be changed 612*635a8641SAndroid Build Coastguard Worker by setting `undefined_to_none` to `False`. 613*635a8641SAndroid Build Coastguard Worker 614*635a8641SAndroid Build Coastguard Worker >>> env.compile_expression('var')() is None 615*635a8641SAndroid Build Coastguard Worker True 616*635a8641SAndroid Build Coastguard Worker >>> env.compile_expression('var', undefined_to_none=False)() 617*635a8641SAndroid Build Coastguard Worker Undefined 618*635a8641SAndroid Build Coastguard Worker 619*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.1 620*635a8641SAndroid Build Coastguard Worker """ 621*635a8641SAndroid Build Coastguard Worker parser = Parser(self, source, state='variable') 622*635a8641SAndroid Build Coastguard Worker exc_info = None 623*635a8641SAndroid Build Coastguard Worker try: 624*635a8641SAndroid Build Coastguard Worker expr = parser.parse_expression() 625*635a8641SAndroid Build Coastguard Worker if not parser.stream.eos: 626*635a8641SAndroid Build Coastguard Worker raise TemplateSyntaxError('chunk after expression', 627*635a8641SAndroid Build Coastguard Worker parser.stream.current.lineno, 628*635a8641SAndroid Build Coastguard Worker None, None) 629*635a8641SAndroid Build Coastguard Worker expr.set_environment(self) 630*635a8641SAndroid Build Coastguard Worker except TemplateSyntaxError: 631*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 632*635a8641SAndroid Build Coastguard Worker if exc_info is not None: 633*635a8641SAndroid Build Coastguard Worker self.handle_exception(exc_info, source_hint=source) 634*635a8641SAndroid Build Coastguard Worker body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] 635*635a8641SAndroid Build Coastguard Worker template = self.from_string(nodes.Template(body, lineno=1)) 636*635a8641SAndroid Build Coastguard Worker return TemplateExpression(template, undefined_to_none) 637*635a8641SAndroid Build Coastguard Worker 638*635a8641SAndroid Build Coastguard Worker def compile_templates(self, target, extensions=None, filter_func=None, 639*635a8641SAndroid Build Coastguard Worker zip='deflated', log_function=None, 640*635a8641SAndroid Build Coastguard Worker ignore_errors=True, py_compile=False): 641*635a8641SAndroid Build Coastguard Worker """Finds all the templates the loader can find, compiles them 642*635a8641SAndroid Build Coastguard Worker and stores them in `target`. If `zip` is `None`, instead of in a 643*635a8641SAndroid Build Coastguard Worker zipfile, the templates will be stored in a directory. 644*635a8641SAndroid Build Coastguard Worker By default a deflate zip algorithm is used. To switch to 645*635a8641SAndroid Build Coastguard Worker the stored algorithm, `zip` can be set to ``'stored'``. 646*635a8641SAndroid Build Coastguard Worker 647*635a8641SAndroid Build Coastguard Worker `extensions` and `filter_func` are passed to :meth:`list_templates`. 648*635a8641SAndroid Build Coastguard Worker Each template returned will be compiled to the target folder or 649*635a8641SAndroid Build Coastguard Worker zipfile. 650*635a8641SAndroid Build Coastguard Worker 651*635a8641SAndroid Build Coastguard Worker By default template compilation errors are ignored. In case a 652*635a8641SAndroid Build Coastguard Worker log function is provided, errors are logged. If you want template 653*635a8641SAndroid Build Coastguard Worker syntax errors to abort the compilation you can set `ignore_errors` 654*635a8641SAndroid Build Coastguard Worker to `False` and you will get an exception on syntax errors. 655*635a8641SAndroid Build Coastguard Worker 656*635a8641SAndroid Build Coastguard Worker If `py_compile` is set to `True` .pyc files will be written to the 657*635a8641SAndroid Build Coastguard Worker target instead of standard .py files. This flag does not do anything 658*635a8641SAndroid Build Coastguard Worker on pypy and Python 3 where pyc files are not picked up by itself and 659*635a8641SAndroid Build Coastguard Worker don't give much benefit. 660*635a8641SAndroid Build Coastguard Worker 661*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.4 662*635a8641SAndroid Build Coastguard Worker """ 663*635a8641SAndroid Build Coastguard Worker from jinja2.loaders import ModuleLoader 664*635a8641SAndroid Build Coastguard Worker 665*635a8641SAndroid Build Coastguard Worker if log_function is None: 666*635a8641SAndroid Build Coastguard Worker log_function = lambda x: None 667*635a8641SAndroid Build Coastguard Worker 668*635a8641SAndroid Build Coastguard Worker if py_compile: 669*635a8641SAndroid Build Coastguard Worker if not PY2 or PYPY: 670*635a8641SAndroid Build Coastguard Worker from warnings import warn 671*635a8641SAndroid Build Coastguard Worker warn(Warning('py_compile has no effect on pypy or Python 3')) 672*635a8641SAndroid Build Coastguard Worker py_compile = False 673*635a8641SAndroid Build Coastguard Worker else: 674*635a8641SAndroid Build Coastguard Worker import imp 675*635a8641SAndroid Build Coastguard Worker import marshal 676*635a8641SAndroid Build Coastguard Worker py_header = imp.get_magic() + \ 677*635a8641SAndroid Build Coastguard Worker u'\xff\xff\xff\xff'.encode('iso-8859-15') 678*635a8641SAndroid Build Coastguard Worker 679*635a8641SAndroid Build Coastguard Worker # Python 3.3 added a source filesize to the header 680*635a8641SAndroid Build Coastguard Worker if sys.version_info >= (3, 3): 681*635a8641SAndroid Build Coastguard Worker py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15') 682*635a8641SAndroid Build Coastguard Worker 683*635a8641SAndroid Build Coastguard Worker def write_file(filename, data, mode): 684*635a8641SAndroid Build Coastguard Worker if zip: 685*635a8641SAndroid Build Coastguard Worker info = ZipInfo(filename) 686*635a8641SAndroid Build Coastguard Worker info.external_attr = 0o755 << 16 687*635a8641SAndroid Build Coastguard Worker zip_file.writestr(info, data) 688*635a8641SAndroid Build Coastguard Worker else: 689*635a8641SAndroid Build Coastguard Worker f = open(os.path.join(target, filename), mode) 690*635a8641SAndroid Build Coastguard Worker try: 691*635a8641SAndroid Build Coastguard Worker f.write(data) 692*635a8641SAndroid Build Coastguard Worker finally: 693*635a8641SAndroid Build Coastguard Worker f.close() 694*635a8641SAndroid Build Coastguard Worker 695*635a8641SAndroid Build Coastguard Worker if zip is not None: 696*635a8641SAndroid Build Coastguard Worker from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED 697*635a8641SAndroid Build Coastguard Worker zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED, 698*635a8641SAndroid Build Coastguard Worker stored=ZIP_STORED)[zip]) 699*635a8641SAndroid Build Coastguard Worker log_function('Compiling into Zip archive "%s"' % target) 700*635a8641SAndroid Build Coastguard Worker else: 701*635a8641SAndroid Build Coastguard Worker if not os.path.isdir(target): 702*635a8641SAndroid Build Coastguard Worker os.makedirs(target) 703*635a8641SAndroid Build Coastguard Worker log_function('Compiling into folder "%s"' % target) 704*635a8641SAndroid Build Coastguard Worker 705*635a8641SAndroid Build Coastguard Worker try: 706*635a8641SAndroid Build Coastguard Worker for name in self.list_templates(extensions, filter_func): 707*635a8641SAndroid Build Coastguard Worker source, filename, _ = self.loader.get_source(self, name) 708*635a8641SAndroid Build Coastguard Worker try: 709*635a8641SAndroid Build Coastguard Worker code = self.compile(source, name, filename, True, True) 710*635a8641SAndroid Build Coastguard Worker except TemplateSyntaxError as e: 711*635a8641SAndroid Build Coastguard Worker if not ignore_errors: 712*635a8641SAndroid Build Coastguard Worker raise 713*635a8641SAndroid Build Coastguard Worker log_function('Could not compile "%s": %s' % (name, e)) 714*635a8641SAndroid Build Coastguard Worker continue 715*635a8641SAndroid Build Coastguard Worker 716*635a8641SAndroid Build Coastguard Worker filename = ModuleLoader.get_module_filename(name) 717*635a8641SAndroid Build Coastguard Worker 718*635a8641SAndroid Build Coastguard Worker if py_compile: 719*635a8641SAndroid Build Coastguard Worker c = self._compile(code, encode_filename(filename)) 720*635a8641SAndroid Build Coastguard Worker write_file(filename + 'c', py_header + 721*635a8641SAndroid Build Coastguard Worker marshal.dumps(c), 'wb') 722*635a8641SAndroid Build Coastguard Worker log_function('Byte-compiled "%s" as %s' % 723*635a8641SAndroid Build Coastguard Worker (name, filename + 'c')) 724*635a8641SAndroid Build Coastguard Worker else: 725*635a8641SAndroid Build Coastguard Worker write_file(filename, code, 'w') 726*635a8641SAndroid Build Coastguard Worker log_function('Compiled "%s" as %s' % (name, filename)) 727*635a8641SAndroid Build Coastguard Worker finally: 728*635a8641SAndroid Build Coastguard Worker if zip: 729*635a8641SAndroid Build Coastguard Worker zip_file.close() 730*635a8641SAndroid Build Coastguard Worker 731*635a8641SAndroid Build Coastguard Worker log_function('Finished compiling templates') 732*635a8641SAndroid Build Coastguard Worker 733*635a8641SAndroid Build Coastguard Worker def list_templates(self, extensions=None, filter_func=None): 734*635a8641SAndroid Build Coastguard Worker """Returns a list of templates for this environment. This requires 735*635a8641SAndroid Build Coastguard Worker that the loader supports the loader's 736*635a8641SAndroid Build Coastguard Worker :meth:`~BaseLoader.list_templates` method. 737*635a8641SAndroid Build Coastguard Worker 738*635a8641SAndroid Build Coastguard Worker If there are other files in the template folder besides the 739*635a8641SAndroid Build Coastguard Worker actual templates, the returned list can be filtered. There are two 740*635a8641SAndroid Build Coastguard Worker ways: either `extensions` is set to a list of file extensions for 741*635a8641SAndroid Build Coastguard Worker templates, or a `filter_func` can be provided which is a callable that 742*635a8641SAndroid Build Coastguard Worker is passed a template name and should return `True` if it should end up 743*635a8641SAndroid Build Coastguard Worker in the result list. 744*635a8641SAndroid Build Coastguard Worker 745*635a8641SAndroid Build Coastguard Worker If the loader does not support that, a :exc:`TypeError` is raised. 746*635a8641SAndroid Build Coastguard Worker 747*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.4 748*635a8641SAndroid Build Coastguard Worker """ 749*635a8641SAndroid Build Coastguard Worker x = self.loader.list_templates() 750*635a8641SAndroid Build Coastguard Worker if extensions is not None: 751*635a8641SAndroid Build Coastguard Worker if filter_func is not None: 752*635a8641SAndroid Build Coastguard Worker raise TypeError('either extensions or filter_func ' 753*635a8641SAndroid Build Coastguard Worker 'can be passed, but not both') 754*635a8641SAndroid Build Coastguard Worker filter_func = lambda x: '.' in x and \ 755*635a8641SAndroid Build Coastguard Worker x.rsplit('.', 1)[1] in extensions 756*635a8641SAndroid Build Coastguard Worker if filter_func is not None: 757*635a8641SAndroid Build Coastguard Worker x = list(ifilter(filter_func, x)) 758*635a8641SAndroid Build Coastguard Worker return x 759*635a8641SAndroid Build Coastguard Worker 760*635a8641SAndroid Build Coastguard Worker def handle_exception(self, exc_info=None, rendered=False, source_hint=None): 761*635a8641SAndroid Build Coastguard Worker """Exception handling helper. This is used internally to either raise 762*635a8641SAndroid Build Coastguard Worker rewritten exceptions or return a rendered traceback for the template. 763*635a8641SAndroid Build Coastguard Worker """ 764*635a8641SAndroid Build Coastguard Worker global _make_traceback 765*635a8641SAndroid Build Coastguard Worker if exc_info is None: 766*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 767*635a8641SAndroid Build Coastguard Worker 768*635a8641SAndroid Build Coastguard Worker # the debugging module is imported when it's used for the first time. 769*635a8641SAndroid Build Coastguard Worker # we're doing a lot of stuff there and for applications that do not 770*635a8641SAndroid Build Coastguard Worker # get any exceptions in template rendering there is no need to load 771*635a8641SAndroid Build Coastguard Worker # all of that. 772*635a8641SAndroid Build Coastguard Worker if _make_traceback is None: 773*635a8641SAndroid Build Coastguard Worker from jinja2.debug import make_traceback as _make_traceback 774*635a8641SAndroid Build Coastguard Worker traceback = _make_traceback(exc_info, source_hint) 775*635a8641SAndroid Build Coastguard Worker if rendered and self.exception_formatter is not None: 776*635a8641SAndroid Build Coastguard Worker return self.exception_formatter(traceback) 777*635a8641SAndroid Build Coastguard Worker if self.exception_handler is not None: 778*635a8641SAndroid Build Coastguard Worker self.exception_handler(traceback) 779*635a8641SAndroid Build Coastguard Worker exc_type, exc_value, tb = traceback.standard_exc_info 780*635a8641SAndroid Build Coastguard Worker reraise(exc_type, exc_value, tb) 781*635a8641SAndroid Build Coastguard Worker 782*635a8641SAndroid Build Coastguard Worker def join_path(self, template, parent): 783*635a8641SAndroid Build Coastguard Worker """Join a template with the parent. By default all the lookups are 784*635a8641SAndroid Build Coastguard Worker relative to the loader root so this method returns the `template` 785*635a8641SAndroid Build Coastguard Worker parameter unchanged, but if the paths should be relative to the 786*635a8641SAndroid Build Coastguard Worker parent template, this function can be used to calculate the real 787*635a8641SAndroid Build Coastguard Worker template name. 788*635a8641SAndroid Build Coastguard Worker 789*635a8641SAndroid Build Coastguard Worker Subclasses may override this method and implement template path 790*635a8641SAndroid Build Coastguard Worker joining here. 791*635a8641SAndroid Build Coastguard Worker """ 792*635a8641SAndroid Build Coastguard Worker return template 793*635a8641SAndroid Build Coastguard Worker 794*635a8641SAndroid Build Coastguard Worker @internalcode 795*635a8641SAndroid Build Coastguard Worker def _load_template(self, name, globals): 796*635a8641SAndroid Build Coastguard Worker if self.loader is None: 797*635a8641SAndroid Build Coastguard Worker raise TypeError('no loader for this environment specified') 798*635a8641SAndroid Build Coastguard Worker cache_key = (weakref.ref(self.loader), name) 799*635a8641SAndroid Build Coastguard Worker if self.cache is not None: 800*635a8641SAndroid Build Coastguard Worker template = self.cache.get(cache_key) 801*635a8641SAndroid Build Coastguard Worker if template is not None and (not self.auto_reload or 802*635a8641SAndroid Build Coastguard Worker template.is_up_to_date): 803*635a8641SAndroid Build Coastguard Worker return template 804*635a8641SAndroid Build Coastguard Worker template = self.loader.load(self, name, globals) 805*635a8641SAndroid Build Coastguard Worker if self.cache is not None: 806*635a8641SAndroid Build Coastguard Worker self.cache[cache_key] = template 807*635a8641SAndroid Build Coastguard Worker return template 808*635a8641SAndroid Build Coastguard Worker 809*635a8641SAndroid Build Coastguard Worker @internalcode 810*635a8641SAndroid Build Coastguard Worker def get_template(self, name, parent=None, globals=None): 811*635a8641SAndroid Build Coastguard Worker """Load a template from the loader. If a loader is configured this 812*635a8641SAndroid Build Coastguard Worker method asks the loader for the template and returns a :class:`Template`. 813*635a8641SAndroid Build Coastguard Worker If the `parent` parameter is not `None`, :meth:`join_path` is called 814*635a8641SAndroid Build Coastguard Worker to get the real template name before loading. 815*635a8641SAndroid Build Coastguard Worker 816*635a8641SAndroid Build Coastguard Worker The `globals` parameter can be used to provide template wide globals. 817*635a8641SAndroid Build Coastguard Worker These variables are available in the context at render time. 818*635a8641SAndroid Build Coastguard Worker 819*635a8641SAndroid Build Coastguard Worker If the template does not exist a :exc:`TemplateNotFound` exception is 820*635a8641SAndroid Build Coastguard Worker raised. 821*635a8641SAndroid Build Coastguard Worker 822*635a8641SAndroid Build Coastguard Worker .. versionchanged:: 2.4 823*635a8641SAndroid Build Coastguard Worker If `name` is a :class:`Template` object it is returned from the 824*635a8641SAndroid Build Coastguard Worker function unchanged. 825*635a8641SAndroid Build Coastguard Worker """ 826*635a8641SAndroid Build Coastguard Worker if isinstance(name, Template): 827*635a8641SAndroid Build Coastguard Worker return name 828*635a8641SAndroid Build Coastguard Worker if parent is not None: 829*635a8641SAndroid Build Coastguard Worker name = self.join_path(name, parent) 830*635a8641SAndroid Build Coastguard Worker return self._load_template(name, self.make_globals(globals)) 831*635a8641SAndroid Build Coastguard Worker 832*635a8641SAndroid Build Coastguard Worker @internalcode 833*635a8641SAndroid Build Coastguard Worker def select_template(self, names, parent=None, globals=None): 834*635a8641SAndroid Build Coastguard Worker """Works like :meth:`get_template` but tries a number of templates 835*635a8641SAndroid Build Coastguard Worker before it fails. If it cannot find any of the templates, it will 836*635a8641SAndroid Build Coastguard Worker raise a :exc:`TemplatesNotFound` exception. 837*635a8641SAndroid Build Coastguard Worker 838*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.3 839*635a8641SAndroid Build Coastguard Worker 840*635a8641SAndroid Build Coastguard Worker .. versionchanged:: 2.4 841*635a8641SAndroid Build Coastguard Worker If `names` contains a :class:`Template` object it is returned 842*635a8641SAndroid Build Coastguard Worker from the function unchanged. 843*635a8641SAndroid Build Coastguard Worker """ 844*635a8641SAndroid Build Coastguard Worker if not names: 845*635a8641SAndroid Build Coastguard Worker raise TemplatesNotFound(message=u'Tried to select from an empty list ' 846*635a8641SAndroid Build Coastguard Worker u'of templates.') 847*635a8641SAndroid Build Coastguard Worker globals = self.make_globals(globals) 848*635a8641SAndroid Build Coastguard Worker for name in names: 849*635a8641SAndroid Build Coastguard Worker if isinstance(name, Template): 850*635a8641SAndroid Build Coastguard Worker return name 851*635a8641SAndroid Build Coastguard Worker if parent is not None: 852*635a8641SAndroid Build Coastguard Worker name = self.join_path(name, parent) 853*635a8641SAndroid Build Coastguard Worker try: 854*635a8641SAndroid Build Coastguard Worker return self._load_template(name, globals) 855*635a8641SAndroid Build Coastguard Worker except TemplateNotFound: 856*635a8641SAndroid Build Coastguard Worker pass 857*635a8641SAndroid Build Coastguard Worker raise TemplatesNotFound(names) 858*635a8641SAndroid Build Coastguard Worker 859*635a8641SAndroid Build Coastguard Worker @internalcode 860*635a8641SAndroid Build Coastguard Worker def get_or_select_template(self, template_name_or_list, 861*635a8641SAndroid Build Coastguard Worker parent=None, globals=None): 862*635a8641SAndroid Build Coastguard Worker """Does a typecheck and dispatches to :meth:`select_template` 863*635a8641SAndroid Build Coastguard Worker if an iterable of template names is given, otherwise to 864*635a8641SAndroid Build Coastguard Worker :meth:`get_template`. 865*635a8641SAndroid Build Coastguard Worker 866*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.3 867*635a8641SAndroid Build Coastguard Worker """ 868*635a8641SAndroid Build Coastguard Worker if isinstance(template_name_or_list, string_types): 869*635a8641SAndroid Build Coastguard Worker return self.get_template(template_name_or_list, parent, globals) 870*635a8641SAndroid Build Coastguard Worker elif isinstance(template_name_or_list, Template): 871*635a8641SAndroid Build Coastguard Worker return template_name_or_list 872*635a8641SAndroid Build Coastguard Worker return self.select_template(template_name_or_list, parent, globals) 873*635a8641SAndroid Build Coastguard Worker 874*635a8641SAndroid Build Coastguard Worker def from_string(self, source, globals=None, template_class=None): 875*635a8641SAndroid Build Coastguard Worker """Load a template from a string. This parses the source given and 876*635a8641SAndroid Build Coastguard Worker returns a :class:`Template` object. 877*635a8641SAndroid Build Coastguard Worker """ 878*635a8641SAndroid Build Coastguard Worker globals = self.make_globals(globals) 879*635a8641SAndroid Build Coastguard Worker cls = template_class or self.template_class 880*635a8641SAndroid Build Coastguard Worker return cls.from_code(self, self.compile(source), globals, None) 881*635a8641SAndroid Build Coastguard Worker 882*635a8641SAndroid Build Coastguard Worker def make_globals(self, d): 883*635a8641SAndroid Build Coastguard Worker """Return a dict for the globals.""" 884*635a8641SAndroid Build Coastguard Worker if not d: 885*635a8641SAndroid Build Coastguard Worker return self.globals 886*635a8641SAndroid Build Coastguard Worker return dict(self.globals, **d) 887*635a8641SAndroid Build Coastguard Worker 888*635a8641SAndroid Build Coastguard Worker 889*635a8641SAndroid Build Coastguard Workerclass Template(object): 890*635a8641SAndroid Build Coastguard Worker """The central template object. This class represents a compiled template 891*635a8641SAndroid Build Coastguard Worker and is used to evaluate it. 892*635a8641SAndroid Build Coastguard Worker 893*635a8641SAndroid Build Coastguard Worker Normally the template object is generated from an :class:`Environment` but 894*635a8641SAndroid Build Coastguard Worker it also has a constructor that makes it possible to create a template 895*635a8641SAndroid Build Coastguard Worker instance directly using the constructor. It takes the same arguments as 896*635a8641SAndroid Build Coastguard Worker the environment constructor but it's not possible to specify a loader. 897*635a8641SAndroid Build Coastguard Worker 898*635a8641SAndroid Build Coastguard Worker Every template object has a few methods and members that are guaranteed 899*635a8641SAndroid Build Coastguard Worker to exist. However it's important that a template object should be 900*635a8641SAndroid Build Coastguard Worker considered immutable. Modifications on the object are not supported. 901*635a8641SAndroid Build Coastguard Worker 902*635a8641SAndroid Build Coastguard Worker Template objects created from the constructor rather than an environment 903*635a8641SAndroid Build Coastguard Worker do have an `environment` attribute that points to a temporary environment 904*635a8641SAndroid Build Coastguard Worker that is probably shared with other templates created with the constructor 905*635a8641SAndroid Build Coastguard Worker and compatible settings. 906*635a8641SAndroid Build Coastguard Worker 907*635a8641SAndroid Build Coastguard Worker >>> template = Template('Hello {{ name }}!') 908*635a8641SAndroid Build Coastguard Worker >>> template.render(name='John Doe') == u'Hello John Doe!' 909*635a8641SAndroid Build Coastguard Worker True 910*635a8641SAndroid Build Coastguard Worker >>> stream = template.stream(name='John Doe') 911*635a8641SAndroid Build Coastguard Worker >>> next(stream) == u'Hello John Doe!' 912*635a8641SAndroid Build Coastguard Worker True 913*635a8641SAndroid Build Coastguard Worker >>> next(stream) 914*635a8641SAndroid Build Coastguard Worker Traceback (most recent call last): 915*635a8641SAndroid Build Coastguard Worker ... 916*635a8641SAndroid Build Coastguard Worker StopIteration 917*635a8641SAndroid Build Coastguard Worker """ 918*635a8641SAndroid Build Coastguard Worker 919*635a8641SAndroid Build Coastguard Worker def __new__(cls, source, 920*635a8641SAndroid Build Coastguard Worker block_start_string=BLOCK_START_STRING, 921*635a8641SAndroid Build Coastguard Worker block_end_string=BLOCK_END_STRING, 922*635a8641SAndroid Build Coastguard Worker variable_start_string=VARIABLE_START_STRING, 923*635a8641SAndroid Build Coastguard Worker variable_end_string=VARIABLE_END_STRING, 924*635a8641SAndroid Build Coastguard Worker comment_start_string=COMMENT_START_STRING, 925*635a8641SAndroid Build Coastguard Worker comment_end_string=COMMENT_END_STRING, 926*635a8641SAndroid Build Coastguard Worker line_statement_prefix=LINE_STATEMENT_PREFIX, 927*635a8641SAndroid Build Coastguard Worker line_comment_prefix=LINE_COMMENT_PREFIX, 928*635a8641SAndroid Build Coastguard Worker trim_blocks=TRIM_BLOCKS, 929*635a8641SAndroid Build Coastguard Worker lstrip_blocks=LSTRIP_BLOCKS, 930*635a8641SAndroid Build Coastguard Worker newline_sequence=NEWLINE_SEQUENCE, 931*635a8641SAndroid Build Coastguard Worker keep_trailing_newline=KEEP_TRAILING_NEWLINE, 932*635a8641SAndroid Build Coastguard Worker extensions=(), 933*635a8641SAndroid Build Coastguard Worker optimized=True, 934*635a8641SAndroid Build Coastguard Worker undefined=Undefined, 935*635a8641SAndroid Build Coastguard Worker finalize=None, 936*635a8641SAndroid Build Coastguard Worker autoescape=False, 937*635a8641SAndroid Build Coastguard Worker enable_async=False): 938*635a8641SAndroid Build Coastguard Worker env = get_spontaneous_environment( 939*635a8641SAndroid Build Coastguard Worker block_start_string, block_end_string, variable_start_string, 940*635a8641SAndroid Build Coastguard Worker variable_end_string, comment_start_string, comment_end_string, 941*635a8641SAndroid Build Coastguard Worker line_statement_prefix, line_comment_prefix, trim_blocks, 942*635a8641SAndroid Build Coastguard Worker lstrip_blocks, newline_sequence, keep_trailing_newline, 943*635a8641SAndroid Build Coastguard Worker frozenset(extensions), optimized, undefined, finalize, autoescape, 944*635a8641SAndroid Build Coastguard Worker None, 0, False, None, enable_async) 945*635a8641SAndroid Build Coastguard Worker return env.from_string(source, template_class=cls) 946*635a8641SAndroid Build Coastguard Worker 947*635a8641SAndroid Build Coastguard Worker @classmethod 948*635a8641SAndroid Build Coastguard Worker def from_code(cls, environment, code, globals, uptodate=None): 949*635a8641SAndroid Build Coastguard Worker """Creates a template object from compiled code and the globals. This 950*635a8641SAndroid Build Coastguard Worker is used by the loaders and environment to create a template object. 951*635a8641SAndroid Build Coastguard Worker """ 952*635a8641SAndroid Build Coastguard Worker namespace = { 953*635a8641SAndroid Build Coastguard Worker 'environment': environment, 954*635a8641SAndroid Build Coastguard Worker '__file__': code.co_filename 955*635a8641SAndroid Build Coastguard Worker } 956*635a8641SAndroid Build Coastguard Worker exec(code, namespace) 957*635a8641SAndroid Build Coastguard Worker rv = cls._from_namespace(environment, namespace, globals) 958*635a8641SAndroid Build Coastguard Worker rv._uptodate = uptodate 959*635a8641SAndroid Build Coastguard Worker return rv 960*635a8641SAndroid Build Coastguard Worker 961*635a8641SAndroid Build Coastguard Worker @classmethod 962*635a8641SAndroid Build Coastguard Worker def from_module_dict(cls, environment, module_dict, globals): 963*635a8641SAndroid Build Coastguard Worker """Creates a template object from a module. This is used by the 964*635a8641SAndroid Build Coastguard Worker module loader to create a template object. 965*635a8641SAndroid Build Coastguard Worker 966*635a8641SAndroid Build Coastguard Worker .. versionadded:: 2.4 967*635a8641SAndroid Build Coastguard Worker """ 968*635a8641SAndroid Build Coastguard Worker return cls._from_namespace(environment, module_dict, globals) 969*635a8641SAndroid Build Coastguard Worker 970*635a8641SAndroid Build Coastguard Worker @classmethod 971*635a8641SAndroid Build Coastguard Worker def _from_namespace(cls, environment, namespace, globals): 972*635a8641SAndroid Build Coastguard Worker t = object.__new__(cls) 973*635a8641SAndroid Build Coastguard Worker t.environment = environment 974*635a8641SAndroid Build Coastguard Worker t.globals = globals 975*635a8641SAndroid Build Coastguard Worker t.name = namespace['name'] 976*635a8641SAndroid Build Coastguard Worker t.filename = namespace['__file__'] 977*635a8641SAndroid Build Coastguard Worker t.blocks = namespace['blocks'] 978*635a8641SAndroid Build Coastguard Worker 979*635a8641SAndroid Build Coastguard Worker # render function and module 980*635a8641SAndroid Build Coastguard Worker t.root_render_func = namespace['root'] 981*635a8641SAndroid Build Coastguard Worker t._module = None 982*635a8641SAndroid Build Coastguard Worker 983*635a8641SAndroid Build Coastguard Worker # debug and loader helpers 984*635a8641SAndroid Build Coastguard Worker t._debug_info = namespace['debug_info'] 985*635a8641SAndroid Build Coastguard Worker t._uptodate = None 986*635a8641SAndroid Build Coastguard Worker 987*635a8641SAndroid Build Coastguard Worker # store the reference 988*635a8641SAndroid Build Coastguard Worker namespace['environment'] = environment 989*635a8641SAndroid Build Coastguard Worker namespace['__jinja_template__'] = t 990*635a8641SAndroid Build Coastguard Worker 991*635a8641SAndroid Build Coastguard Worker return t 992*635a8641SAndroid Build Coastguard Worker 993*635a8641SAndroid Build Coastguard Worker def render(self, *args, **kwargs): 994*635a8641SAndroid Build Coastguard Worker """This method accepts the same arguments as the `dict` constructor: 995*635a8641SAndroid Build Coastguard Worker A dict, a dict subclass or some keyword arguments. If no arguments 996*635a8641SAndroid Build Coastguard Worker are given the context will be empty. These two calls do the same:: 997*635a8641SAndroid Build Coastguard Worker 998*635a8641SAndroid Build Coastguard Worker template.render(knights='that say nih') 999*635a8641SAndroid Build Coastguard Worker template.render({'knights': 'that say nih'}) 1000*635a8641SAndroid Build Coastguard Worker 1001*635a8641SAndroid Build Coastguard Worker This will return the rendered template as unicode string. 1002*635a8641SAndroid Build Coastguard Worker """ 1003*635a8641SAndroid Build Coastguard Worker vars = dict(*args, **kwargs) 1004*635a8641SAndroid Build Coastguard Worker try: 1005*635a8641SAndroid Build Coastguard Worker return concat(self.root_render_func(self.new_context(vars))) 1006*635a8641SAndroid Build Coastguard Worker except Exception: 1007*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 1008*635a8641SAndroid Build Coastguard Worker return self.environment.handle_exception(exc_info, True) 1009*635a8641SAndroid Build Coastguard Worker 1010*635a8641SAndroid Build Coastguard Worker def render_async(self, *args, **kwargs): 1011*635a8641SAndroid Build Coastguard Worker """This works similar to :meth:`render` but returns a coroutine 1012*635a8641SAndroid Build Coastguard Worker that when awaited returns the entire rendered template string. This 1013*635a8641SAndroid Build Coastguard Worker requires the async feature to be enabled. 1014*635a8641SAndroid Build Coastguard Worker 1015*635a8641SAndroid Build Coastguard Worker Example usage:: 1016*635a8641SAndroid Build Coastguard Worker 1017*635a8641SAndroid Build Coastguard Worker await template.render_async(knights='that say nih; asynchronously') 1018*635a8641SAndroid Build Coastguard Worker """ 1019*635a8641SAndroid Build Coastguard Worker # see asyncsupport for the actual implementation 1020*635a8641SAndroid Build Coastguard Worker raise NotImplementedError('This feature is not available for this ' 1021*635a8641SAndroid Build Coastguard Worker 'version of Python') 1022*635a8641SAndroid Build Coastguard Worker 1023*635a8641SAndroid Build Coastguard Worker def stream(self, *args, **kwargs): 1024*635a8641SAndroid Build Coastguard Worker """Works exactly like :meth:`generate` but returns a 1025*635a8641SAndroid Build Coastguard Worker :class:`TemplateStream`. 1026*635a8641SAndroid Build Coastguard Worker """ 1027*635a8641SAndroid Build Coastguard Worker return TemplateStream(self.generate(*args, **kwargs)) 1028*635a8641SAndroid Build Coastguard Worker 1029*635a8641SAndroid Build Coastguard Worker def generate(self, *args, **kwargs): 1030*635a8641SAndroid Build Coastguard Worker """For very large templates it can be useful to not render the whole 1031*635a8641SAndroid Build Coastguard Worker template at once but evaluate each statement after another and yield 1032*635a8641SAndroid Build Coastguard Worker piece for piece. This method basically does exactly that and returns 1033*635a8641SAndroid Build Coastguard Worker a generator that yields one item after another as unicode strings. 1034*635a8641SAndroid Build Coastguard Worker 1035*635a8641SAndroid Build Coastguard Worker It accepts the same arguments as :meth:`render`. 1036*635a8641SAndroid Build Coastguard Worker """ 1037*635a8641SAndroid Build Coastguard Worker vars = dict(*args, **kwargs) 1038*635a8641SAndroid Build Coastguard Worker try: 1039*635a8641SAndroid Build Coastguard Worker for event in self.root_render_func(self.new_context(vars)): 1040*635a8641SAndroid Build Coastguard Worker yield event 1041*635a8641SAndroid Build Coastguard Worker except Exception: 1042*635a8641SAndroid Build Coastguard Worker exc_info = sys.exc_info() 1043*635a8641SAndroid Build Coastguard Worker else: 1044*635a8641SAndroid Build Coastguard Worker return 1045*635a8641SAndroid Build Coastguard Worker yield self.environment.handle_exception(exc_info, True) 1046*635a8641SAndroid Build Coastguard Worker 1047*635a8641SAndroid Build Coastguard Worker def generate_async(self, *args, **kwargs): 1048*635a8641SAndroid Build Coastguard Worker """An async version of :meth:`generate`. Works very similarly but 1049*635a8641SAndroid Build Coastguard Worker returns an async iterator instead. 1050*635a8641SAndroid Build Coastguard Worker """ 1051*635a8641SAndroid Build Coastguard Worker # see asyncsupport for the actual implementation 1052*635a8641SAndroid Build Coastguard Worker raise NotImplementedError('This feature is not available for this ' 1053*635a8641SAndroid Build Coastguard Worker 'version of Python') 1054*635a8641SAndroid Build Coastguard Worker 1055*635a8641SAndroid Build Coastguard Worker def new_context(self, vars=None, shared=False, locals=None): 1056*635a8641SAndroid Build Coastguard Worker """Create a new :class:`Context` for this template. The vars 1057*635a8641SAndroid Build Coastguard Worker provided will be passed to the template. Per default the globals 1058*635a8641SAndroid Build Coastguard Worker are added to the context. If shared is set to `True` the data 1059*635a8641SAndroid Build Coastguard Worker is passed as it to the context without adding the globals. 1060*635a8641SAndroid Build Coastguard Worker 1061*635a8641SAndroid Build Coastguard Worker `locals` can be a dict of local variables for internal usage. 1062*635a8641SAndroid Build Coastguard Worker """ 1063*635a8641SAndroid Build Coastguard Worker return new_context(self.environment, self.name, self.blocks, 1064*635a8641SAndroid Build Coastguard Worker vars, shared, self.globals, locals) 1065*635a8641SAndroid Build Coastguard Worker 1066*635a8641SAndroid Build Coastguard Worker def make_module(self, vars=None, shared=False, locals=None): 1067*635a8641SAndroid Build Coastguard Worker """This method works like the :attr:`module` attribute when called 1068*635a8641SAndroid Build Coastguard Worker without arguments but it will evaluate the template on every call 1069*635a8641SAndroid Build Coastguard Worker rather than caching it. It's also possible to provide 1070*635a8641SAndroid Build Coastguard Worker a dict which is then used as context. The arguments are the same 1071*635a8641SAndroid Build Coastguard Worker as for the :meth:`new_context` method. 1072*635a8641SAndroid Build Coastguard Worker """ 1073*635a8641SAndroid Build Coastguard Worker return TemplateModule(self, self.new_context(vars, shared, locals)) 1074*635a8641SAndroid Build Coastguard Worker 1075*635a8641SAndroid Build Coastguard Worker def make_module_async(self, vars=None, shared=False, locals=None): 1076*635a8641SAndroid Build Coastguard Worker """As template module creation can invoke template code for 1077*635a8641SAndroid Build Coastguard Worker asynchronous exections this method must be used instead of the 1078*635a8641SAndroid Build Coastguard Worker normal :meth:`make_module` one. Likewise the module attribute 1079*635a8641SAndroid Build Coastguard Worker becomes unavailable in async mode. 1080*635a8641SAndroid Build Coastguard Worker """ 1081*635a8641SAndroid Build Coastguard Worker # see asyncsupport for the actual implementation 1082*635a8641SAndroid Build Coastguard Worker raise NotImplementedError('This feature is not available for this ' 1083*635a8641SAndroid Build Coastguard Worker 'version of Python') 1084*635a8641SAndroid Build Coastguard Worker 1085*635a8641SAndroid Build Coastguard Worker @internalcode 1086*635a8641SAndroid Build Coastguard Worker def _get_default_module(self): 1087*635a8641SAndroid Build Coastguard Worker if self._module is not None: 1088*635a8641SAndroid Build Coastguard Worker return self._module 1089*635a8641SAndroid Build Coastguard Worker self._module = rv = self.make_module() 1090*635a8641SAndroid Build Coastguard Worker return rv 1091*635a8641SAndroid Build Coastguard Worker 1092*635a8641SAndroid Build Coastguard Worker @property 1093*635a8641SAndroid Build Coastguard Worker def module(self): 1094*635a8641SAndroid Build Coastguard Worker """The template as module. This is used for imports in the 1095*635a8641SAndroid Build Coastguard Worker template runtime but is also useful if one wants to access 1096*635a8641SAndroid Build Coastguard Worker exported template variables from the Python layer: 1097*635a8641SAndroid Build Coastguard Worker 1098*635a8641SAndroid Build Coastguard Worker >>> t = Template('{% macro foo() %}42{% endmacro %}23') 1099*635a8641SAndroid Build Coastguard Worker >>> str(t.module) 1100*635a8641SAndroid Build Coastguard Worker '23' 1101*635a8641SAndroid Build Coastguard Worker >>> t.module.foo() == u'42' 1102*635a8641SAndroid Build Coastguard Worker True 1103*635a8641SAndroid Build Coastguard Worker 1104*635a8641SAndroid Build Coastguard Worker This attribute is not available if async mode is enabled. 1105*635a8641SAndroid Build Coastguard Worker """ 1106*635a8641SAndroid Build Coastguard Worker return self._get_default_module() 1107*635a8641SAndroid Build Coastguard Worker 1108*635a8641SAndroid Build Coastguard Worker def get_corresponding_lineno(self, lineno): 1109*635a8641SAndroid Build Coastguard Worker """Return the source line number of a line number in the 1110*635a8641SAndroid Build Coastguard Worker generated bytecode as they are not in sync. 1111*635a8641SAndroid Build Coastguard Worker """ 1112*635a8641SAndroid Build Coastguard Worker for template_line, code_line in reversed(self.debug_info): 1113*635a8641SAndroid Build Coastguard Worker if code_line <= lineno: 1114*635a8641SAndroid Build Coastguard Worker return template_line 1115*635a8641SAndroid Build Coastguard Worker return 1 1116*635a8641SAndroid Build Coastguard Worker 1117*635a8641SAndroid Build Coastguard Worker @property 1118*635a8641SAndroid Build Coastguard Worker def is_up_to_date(self): 1119*635a8641SAndroid Build Coastguard Worker """If this variable is `False` there is a newer version available.""" 1120*635a8641SAndroid Build Coastguard Worker if self._uptodate is None: 1121*635a8641SAndroid Build Coastguard Worker return True 1122*635a8641SAndroid Build Coastguard Worker return self._uptodate() 1123*635a8641SAndroid Build Coastguard Worker 1124*635a8641SAndroid Build Coastguard Worker @property 1125*635a8641SAndroid Build Coastguard Worker def debug_info(self): 1126*635a8641SAndroid Build Coastguard Worker """The debug info mapping.""" 1127*635a8641SAndroid Build Coastguard Worker return [tuple(imap(int, x.split('='))) for x in 1128*635a8641SAndroid Build Coastguard Worker self._debug_info.split('&')] 1129*635a8641SAndroid Build Coastguard Worker 1130*635a8641SAndroid Build Coastguard Worker def __repr__(self): 1131*635a8641SAndroid Build Coastguard Worker if self.name is None: 1132*635a8641SAndroid Build Coastguard Worker name = 'memory:%x' % id(self) 1133*635a8641SAndroid Build Coastguard Worker else: 1134*635a8641SAndroid Build Coastguard Worker name = repr(self.name) 1135*635a8641SAndroid Build Coastguard Worker return '<%s %s>' % (self.__class__.__name__, name) 1136*635a8641SAndroid Build Coastguard Worker 1137*635a8641SAndroid Build Coastguard Worker 1138*635a8641SAndroid Build Coastguard Worker@implements_to_string 1139*635a8641SAndroid Build Coastguard Workerclass TemplateModule(object): 1140*635a8641SAndroid Build Coastguard Worker """Represents an imported template. All the exported names of the 1141*635a8641SAndroid Build Coastguard Worker template are available as attributes on this object. Additionally 1142*635a8641SAndroid Build Coastguard Worker converting it into an unicode- or bytestrings renders the contents. 1143*635a8641SAndroid Build Coastguard Worker """ 1144*635a8641SAndroid Build Coastguard Worker 1145*635a8641SAndroid Build Coastguard Worker def __init__(self, template, context, body_stream=None): 1146*635a8641SAndroid Build Coastguard Worker if body_stream is None: 1147*635a8641SAndroid Build Coastguard Worker if context.environment.is_async: 1148*635a8641SAndroid Build Coastguard Worker raise RuntimeError('Async mode requires a body stream ' 1149*635a8641SAndroid Build Coastguard Worker 'to be passed to a template module. Use ' 1150*635a8641SAndroid Build Coastguard Worker 'the async methods of the API you are ' 1151*635a8641SAndroid Build Coastguard Worker 'using.') 1152*635a8641SAndroid Build Coastguard Worker body_stream = list(template.root_render_func(context)) 1153*635a8641SAndroid Build Coastguard Worker self._body_stream = body_stream 1154*635a8641SAndroid Build Coastguard Worker self.__dict__.update(context.get_exported()) 1155*635a8641SAndroid Build Coastguard Worker self.__name__ = template.name 1156*635a8641SAndroid Build Coastguard Worker 1157*635a8641SAndroid Build Coastguard Worker def __html__(self): 1158*635a8641SAndroid Build Coastguard Worker return Markup(concat(self._body_stream)) 1159*635a8641SAndroid Build Coastguard Worker 1160*635a8641SAndroid Build Coastguard Worker def __str__(self): 1161*635a8641SAndroid Build Coastguard Worker return concat(self._body_stream) 1162*635a8641SAndroid Build Coastguard Worker 1163*635a8641SAndroid Build Coastguard Worker def __repr__(self): 1164*635a8641SAndroid Build Coastguard Worker if self.__name__ is None: 1165*635a8641SAndroid Build Coastguard Worker name = 'memory:%x' % id(self) 1166*635a8641SAndroid Build Coastguard Worker else: 1167*635a8641SAndroid Build Coastguard Worker name = repr(self.__name__) 1168*635a8641SAndroid Build Coastguard Worker return '<%s %s>' % (self.__class__.__name__, name) 1169*635a8641SAndroid Build Coastguard Worker 1170*635a8641SAndroid Build Coastguard Worker 1171*635a8641SAndroid Build Coastguard Workerclass TemplateExpression(object): 1172*635a8641SAndroid Build Coastguard Worker """The :meth:`jinja2.Environment.compile_expression` method returns an 1173*635a8641SAndroid Build Coastguard Worker instance of this object. It encapsulates the expression-like access 1174*635a8641SAndroid Build Coastguard Worker to the template with an expression it wraps. 1175*635a8641SAndroid Build Coastguard Worker """ 1176*635a8641SAndroid Build Coastguard Worker 1177*635a8641SAndroid Build Coastguard Worker def __init__(self, template, undefined_to_none): 1178*635a8641SAndroid Build Coastguard Worker self._template = template 1179*635a8641SAndroid Build Coastguard Worker self._undefined_to_none = undefined_to_none 1180*635a8641SAndroid Build Coastguard Worker 1181*635a8641SAndroid Build Coastguard Worker def __call__(self, *args, **kwargs): 1182*635a8641SAndroid Build Coastguard Worker context = self._template.new_context(dict(*args, **kwargs)) 1183*635a8641SAndroid Build Coastguard Worker consume(self._template.root_render_func(context)) 1184*635a8641SAndroid Build Coastguard Worker rv = context.vars['result'] 1185*635a8641SAndroid Build Coastguard Worker if self._undefined_to_none and isinstance(rv, Undefined): 1186*635a8641SAndroid Build Coastguard Worker rv = None 1187*635a8641SAndroid Build Coastguard Worker return rv 1188*635a8641SAndroid Build Coastguard Worker 1189*635a8641SAndroid Build Coastguard Worker 1190*635a8641SAndroid Build Coastguard Worker@implements_iterator 1191*635a8641SAndroid Build Coastguard Workerclass TemplateStream(object): 1192*635a8641SAndroid Build Coastguard Worker """A template stream works pretty much like an ordinary python generator 1193*635a8641SAndroid Build Coastguard Worker but it can buffer multiple items to reduce the number of total iterations. 1194*635a8641SAndroid Build Coastguard Worker Per default the output is unbuffered which means that for every unbuffered 1195*635a8641SAndroid Build Coastguard Worker instruction in the template one unicode string is yielded. 1196*635a8641SAndroid Build Coastguard Worker 1197*635a8641SAndroid Build Coastguard Worker If buffering is enabled with a buffer size of 5, five items are combined 1198*635a8641SAndroid Build Coastguard Worker into a new unicode string. This is mainly useful if you are streaming 1199*635a8641SAndroid Build Coastguard Worker big templates to a client via WSGI which flushes after each iteration. 1200*635a8641SAndroid Build Coastguard Worker """ 1201*635a8641SAndroid Build Coastguard Worker 1202*635a8641SAndroid Build Coastguard Worker def __init__(self, gen): 1203*635a8641SAndroid Build Coastguard Worker self._gen = gen 1204*635a8641SAndroid Build Coastguard Worker self.disable_buffering() 1205*635a8641SAndroid Build Coastguard Worker 1206*635a8641SAndroid Build Coastguard Worker def dump(self, fp, encoding=None, errors='strict'): 1207*635a8641SAndroid Build Coastguard Worker """Dump the complete stream into a file or file-like object. 1208*635a8641SAndroid Build Coastguard Worker Per default unicode strings are written, if you want to encode 1209*635a8641SAndroid Build Coastguard Worker before writing specify an `encoding`. 1210*635a8641SAndroid Build Coastguard Worker 1211*635a8641SAndroid Build Coastguard Worker Example usage:: 1212*635a8641SAndroid Build Coastguard Worker 1213*635a8641SAndroid Build Coastguard Worker Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') 1214*635a8641SAndroid Build Coastguard Worker """ 1215*635a8641SAndroid Build Coastguard Worker close = False 1216*635a8641SAndroid Build Coastguard Worker if isinstance(fp, string_types): 1217*635a8641SAndroid Build Coastguard Worker if encoding is None: 1218*635a8641SAndroid Build Coastguard Worker encoding = 'utf-8' 1219*635a8641SAndroid Build Coastguard Worker fp = open(fp, 'wb') 1220*635a8641SAndroid Build Coastguard Worker close = True 1221*635a8641SAndroid Build Coastguard Worker try: 1222*635a8641SAndroid Build Coastguard Worker if encoding is not None: 1223*635a8641SAndroid Build Coastguard Worker iterable = (x.encode(encoding, errors) for x in self) 1224*635a8641SAndroid Build Coastguard Worker else: 1225*635a8641SAndroid Build Coastguard Worker iterable = self 1226*635a8641SAndroid Build Coastguard Worker if hasattr(fp, 'writelines'): 1227*635a8641SAndroid Build Coastguard Worker fp.writelines(iterable) 1228*635a8641SAndroid Build Coastguard Worker else: 1229*635a8641SAndroid Build Coastguard Worker for item in iterable: 1230*635a8641SAndroid Build Coastguard Worker fp.write(item) 1231*635a8641SAndroid Build Coastguard Worker finally: 1232*635a8641SAndroid Build Coastguard Worker if close: 1233*635a8641SAndroid Build Coastguard Worker fp.close() 1234*635a8641SAndroid Build Coastguard Worker 1235*635a8641SAndroid Build Coastguard Worker def disable_buffering(self): 1236*635a8641SAndroid Build Coastguard Worker """Disable the output buffering.""" 1237*635a8641SAndroid Build Coastguard Worker self._next = partial(next, self._gen) 1238*635a8641SAndroid Build Coastguard Worker self.buffered = False 1239*635a8641SAndroid Build Coastguard Worker 1240*635a8641SAndroid Build Coastguard Worker def _buffered_generator(self, size): 1241*635a8641SAndroid Build Coastguard Worker buf = [] 1242*635a8641SAndroid Build Coastguard Worker c_size = 0 1243*635a8641SAndroid Build Coastguard Worker push = buf.append 1244*635a8641SAndroid Build Coastguard Worker 1245*635a8641SAndroid Build Coastguard Worker while 1: 1246*635a8641SAndroid Build Coastguard Worker try: 1247*635a8641SAndroid Build Coastguard Worker while c_size < size: 1248*635a8641SAndroid Build Coastguard Worker c = next(self._gen) 1249*635a8641SAndroid Build Coastguard Worker push(c) 1250*635a8641SAndroid Build Coastguard Worker if c: 1251*635a8641SAndroid Build Coastguard Worker c_size += 1 1252*635a8641SAndroid Build Coastguard Worker except StopIteration: 1253*635a8641SAndroid Build Coastguard Worker if not c_size: 1254*635a8641SAndroid Build Coastguard Worker return 1255*635a8641SAndroid Build Coastguard Worker yield concat(buf) 1256*635a8641SAndroid Build Coastguard Worker del buf[:] 1257*635a8641SAndroid Build Coastguard Worker c_size = 0 1258*635a8641SAndroid Build Coastguard Worker 1259*635a8641SAndroid Build Coastguard Worker def enable_buffering(self, size=5): 1260*635a8641SAndroid Build Coastguard Worker """Enable buffering. Buffer `size` items before yielding them.""" 1261*635a8641SAndroid Build Coastguard Worker if size <= 1: 1262*635a8641SAndroid Build Coastguard Worker raise ValueError('buffer size too small') 1263*635a8641SAndroid Build Coastguard Worker 1264*635a8641SAndroid Build Coastguard Worker self.buffered = True 1265*635a8641SAndroid Build Coastguard Worker self._next = partial(next, self._buffered_generator(size)) 1266*635a8641SAndroid Build Coastguard Worker 1267*635a8641SAndroid Build Coastguard Worker def __iter__(self): 1268*635a8641SAndroid Build Coastguard Worker return self 1269*635a8641SAndroid Build Coastguard Worker 1270*635a8641SAndroid Build Coastguard Worker def __next__(self): 1271*635a8641SAndroid Build Coastguard Worker return self._next() 1272*635a8641SAndroid Build Coastguard Worker 1273*635a8641SAndroid Build Coastguard Worker 1274*635a8641SAndroid Build Coastguard Worker# hook in default template class. if anyone reads this comment: ignore that 1275*635a8641SAndroid Build Coastguard Worker# it's possible to use custom templates ;-) 1276*635a8641SAndroid Build Coastguard WorkerEnvironment.template_class = Template 1277