U  e1]@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl m Z ddl m Z ddl mZddl mZdd lmZGd d d ZGd d d eZGdddeZGdddZddZddZddZddZddZdS)zProvides the Template class, a facade for parsing, generating and executing template strings, as well as template runtime operations.N)cache)codegen)compat) exceptions)runtime)util)Lexerc@seZdZdZeZd,dd Zejd d Z d d Z ddZ e ddZ e ddZejddZe ddZe ddZe ddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Ze d*d+ZdS)-Templatea|Represents a compiled template. :class:`.Template` includes a reference to the original template source (via the :attr:`.source` attribute) as well as the source code of the generated Python module (i.e. the :attr:`.code` attribute), as well as a reference to an actual Python module. :class:`.Template` is constructed using either a literal string representing the template text, or a filename representing a filesystem path to a source file. :param text: textual template source. This argument is mutually exclusive versus the ``filename`` parameter. :param filename: filename of the source template. This argument is mutually exclusive versus the ``text`` parameter. :param buffer_filters: string list of filters to be applied to the output of ``%def``\ s which are buffered, cached, or otherwise filtered, after all filters defined with the ``%def`` itself have been applied. Allows the creation of default expression filters that let the output of return-valued ``%def``\ s "opt out" of that filtering via passing special attributes or objects. :param cache_args: Dictionary of cache configuration arguments that will be passed to the :class:`.CacheImpl`. See :ref:`caching_toplevel`. :param cache_dir: .. deprecated:: 0.6 Use the ``'dir'`` argument in the ``cache_args`` dictionary. See :ref:`caching_toplevel`. :param cache_enabled: Boolean flag which enables caching of this template. See :ref:`caching_toplevel`. :param cache_impl: String name of a :class:`.CacheImpl` caching implementation to use. Defaults to ``'beaker'``. :param cache_type: .. deprecated:: 0.6 Use the ``'type'`` argument in the ``cache_args`` dictionary. See :ref:`caching_toplevel`. :param cache_url: .. deprecated:: 0.6 Use the ``'url'`` argument in the ``cache_args`` dictionary. See :ref:`caching_toplevel`. :param default_filters: List of string filter names that will be applied to all expressions. See :ref:`filtering_default_filters`. :param enable_loop: When ``True``, enable the ``loop`` context variable. This can be set to ``False`` to support templates that may be making usage of the name "``loop``". Individual templates can re-enable the "loop" context by placing the directive ``enable_loop="True"`` inside the ``<%page>`` tag -- see :ref:`migrating_loop`. :param encoding_errors: Error parameter passed to ``encode()`` when string encoding is performed. See :ref:`usage_unicode`. :param error_handler: Python callable which is called whenever compile or runtime exceptions occur. The callable is passed the current context as well as the exception. If the callable returns ``True``, the exception is considered to be handled, else it is re-raised after the function completes. Is used to provide custom error-rendering functions. .. seealso:: :paramref:`.Template.include_error_handler` - include-specific error handler function :param format_exceptions: if ``True``, exceptions which occur during the render phase of this template will be caught and formatted into an HTML error page, which then becomes the rendered result of the :meth:`.render` call. Otherwise, runtime exceptions are propagated outwards. :param imports: String list of Python statements, typically individual "import" lines, which will be placed into the module level preamble of all generated Python modules. See the example in :ref:`filtering_default_filters`. :param future_imports: String list of names to import from `__future__`. These will be concatenated into a comma-separated string and inserted into the beginning of the template, e.g. ``futures_imports=['FOO', 'BAR']`` results in ``from __future__ import FOO, BAR``. If you're interested in using features like the new division operator, you must use future_imports to convey that to the renderer, as otherwise the import will not appear as the first executed statement in the generated code and will therefore not have the desired effect. :param include_error_handler: An error handler that runs when this template is included within another one via the ``<%include>`` tag, and raises an error. Compare to the :paramref:`.Template.error_handler` option. .. versionadded:: 1.0.6 .. seealso:: :paramref:`.Template.error_handler` - top-level error handler function :param input_encoding: Encoding of the template's source code. Can be used in lieu of the coding comment. See :ref:`usage_unicode` as well as :ref:`unicode_toplevel` for details on source encoding. :param lookup: a :class:`.TemplateLookup` instance that will be used for all file lookups via the ``<%namespace>``, ``<%include>``, and ``<%inherit>`` tags. See :ref:`usage_templatelookup`. :param module_directory: Filesystem location where generated Python module files will be placed. :param module_filename: Overrides the filename of the generated Python module file. For advanced usage only. :param module_writer: A callable which overrides how the Python module is written entirely. The callable is passed the encoded source content of the module and the destination path to be written to. The default behavior of module writing uses a tempfile in conjunction with a file move in order to make the operation atomic. So a user-defined module writing function that mimics the default behavior would be: .. sourcecode:: python import tempfile import os import shutil def module_writer(source, outputpath): (dest, name) = \\ tempfile.mkstemp( dir=os.path.dirname(outputpath) ) os.write(dest, source) os.close(dest) shutil.move(name, outputpath) from mako.template import Template mytemplate = Template( filename="index.html", module_directory="/path/to/modules", module_writer=module_writer ) The function is provided for unusual configurations where certain platform-specific permissions or other special steps are needed. :param output_encoding: The encoding to use when :meth:`.render` is called. See :ref:`usage_unicode` as well as :ref:`unicode_toplevel`. :param preprocessor: Python callable which will be passed the full template source before it is parsed. The return result of the callable will be used as the template source code. :param lexer_cls: A :class:`.Lexer` class used to parse the template. The :class:`.Lexer` class is used by default. .. versionadded:: 0.7.4 :param strict_undefined: Replaces the automatic usage of ``UNDEFINED`` for any undeclared variables not located in the :class:`.Context` with an immediate raise of ``NameError``. The advantage is immediate reporting of missing variables which include the name. .. versionadded:: 0.3.6 :param uri: string URI or other identifier for this template. If not provided, the ``uri`` is generated from the filesystem path, or from the in-memory identity of a non-file-based template. The primary usage of the ``uri`` is to provide a key within :class:`.TemplateLookup`, as well as to generate the file path of the generated Python module file, if ``module_directory`` is specified. NFstrictbeakerTc!Cs |rtdd||_||_n^|r`tdd||_tj|\}}tj|tjj d}||_ndt t ||_|j|_|j}| dr|dd}tj|}| drt d|j||_||_||_||_||_||_|dkrdg|_n||_||_||_||_||_|dk r ||_|dk r\t|||\}} ||_||_t| d|||||nd|dk r|dk rv|}n2| dk rtjtj tj| |d }nd}|!||} n t "d | |_#||_$|j#j%|_&||_'||_(||_)||_*| |_+|,| | | | ||dS) N\W_/zmemory:z..zNTemplate uri "%s" is invalid - it cannot be relative outside of the root path.strz.pyz"Template requires text or filename)-resub module_iduriospath splitdrivenormpathreplacesephexid startswithrZTemplateLookupExceptioninput_encodingoutput_encodingencoding_errors enable_loopstrict_undefined module_writerdefault_filtersbuffer_filtersimportsfuture_imports preprocessor lexer_cls _compile_text_code_source ModuleInfoabspathjoin_compile_from_fileZRuntimeExceptionmodulefilename render_body callable_format_exceptions error_handlerinclude_error_handlerlookupmodule_directory_setup_cache_args)!selftextr3rr6r7r9r r!r: cache_args cache_impl cache_enabled cache_type cache_dir cache_urlmodule_filenamerr$r%r&r#r'r(r"r)r*r8driverZu_normcoder2r r ;/opt/hc_python/lib/python3.8/site-packages/mako/template.py__init__s            zTemplate.__init__cCs|jr tjStjdgSdS)Nloop)r"rZRESERVED_NAMES differencer<r r rGreserved_namesUszTemplate.reserved_namescCsD||_||_|pi|_|r$||jd<|r2||jd<|r@||jd<dS)Ntypedirurl)r?r@r>)r<r?r@r>rArBrCr r rGr;\s    zTemplate._setup_cache_argscCs|dk rttj|t|tj}tj|rJt|tj|krft|}t |||||j t |j |}|jtjkrt|}t |||||j t |j |}t||||dddn:t|}t|||\}}d|_||_t|d|||dd|SN)rZverify_directoryrrdirnamestatST_MTIMEexists read_file_compile_module_filer$r load_modulerZ _magic_numberr MAGIC_NUMBERr.r+r-r,)r<rr3Z filemtimedatar2rFr r rGr1psB     zTemplate._compile_from_filecCs t|jjS)zrKr r rGrBszTemplate.cache_dircCs |jdS)NrOr]rKr r rGrCszTemplate.cache_urlcCs |jdS)NrMr]rKr r rGrAszTemplate.cache_typecOst||j||S)aRender the output of this template as a string. If the template specifies an output encoding, the string will be encoded accordingly, else the output is raw (raw output uses `StringIO` and can't handle multibyte characters). A :class:`.Context` object is created corresponding to the given data. Arguments that are explicitly declared by this template's internal rendering method are also pulled from the given ``*args``, ``**data`` members. r_renderr5r<argsrYr r rGrenders zTemplate.rendercOstj||j||ddS)z7Render the output of this template as a unicode object.T)Z as_unicoder^r`r r rGrender_unicodeszTemplate.render_unicodecOs6t|dddkr||tj||j|f||dS)zvRender this :class:`.Template` with the given context. The data is written to the context's buffer. Z_with_templateN)getattrZ_set_with_templaterZ_render_contextr5)r<contextrakwargsr r rGrender_contexts zTemplate.render_contextcCst|jd|SN render_%s)hasattrr2r<namer r rGhas_defszTemplate.has_defcCst|t|jd|S)z9Return a def of this template as a :class:`.DefTemplate`.ri) DefTemplaterdr2rkr r rGget_defszTemplate.get_defcCsddt|jDS)zQreturn a list of defs in the template. .. versionadded:: 1.0.4 cSs(g|] }|dddkr|ddqS)NZrender_r ).0ir r rG sz&Template.list_defs..)rNr2rKr r rG list_defsszTemplate.list_defscCst|jd|Srh)rdr2rkr r rG_get_def_callableszTemplate._get_def_callablecCs|jjSrP)r2Z_modified_timerKr r rG last_modifiedszTemplate.last_modified)NNNFNNNr NNr TNNNNNNNr FNNTNNN)__name__ __module__ __qualname____doc__rr*rHrZmemoized_propertyrLr;r1propertyr[rFrrBrCrArbrcrgrmrortrurvr r r rGr spB u        r c@seZdZdZd ddZdS) ModuleTemplatea-A Template which is constructed given an existing Python module. e.g.:: t = Template("this is a template") f = file("mymodule.py", "w") f.write(t.code) f.close() import mymodule t = ModuleTemplate(mymodule) print(t.render()) Nr Fr TcCstdd|j|_|j|_|j|_||_||_|j |_ ||_ ||_ t |||||||j|j j|_| |_| |_||_| |_|| || |||dS)Nr r)rrZ _template_urirr_source_encodingrr r!Z _enable_loopr"r2r3r.r4r5r6r7r8r9r;)r<r2rDtemplatetemplate_filename module_sourcetemplate_sourcer r!r6r7r9r>r?r@rArBrCr8r r rGrHs< zModuleTemplate.__init__)NNNNNNr FNNNr TNNNN)rwrxryrzrHr r r rGr|s&r|c@s eZdZdZddZddZdS)rnzNA :class:`.Template` which represents a callable def in a parent template.cCsP||_||_|j|_|j|_|j|_|j|_|j|_|j|_|j|_|j |_ dSrP) parentr5r r2r!r6r7r8r"r9)r<rr5r r rGrH/szDefTemplate.__init__cCs |j|SrP)rrorkr r rGro;szDefTemplate.get_defN)rwrxryrzrHror r r rGrn*s rnc@sFeZdZdZeZddZed ddZ e ddZ e d d Z d S) r.zStores information about a module currently loaded into memory, provides reverse lookups of template source, module source code based on a module's identifier. cCsH||_||_||_||_||_||_||j|j<|_|rD||j|<dSrP) r2rDrrr template_uri_modulesrwZ_mmarker)r<r2rDr~rrrrr r rGrHIs zModuleInfo.__init__FcCstd|tjd}t|}dd|dD|d<|rg}|d<|d}d}tdt|D]}||krx||}| |qd|S)Nz'__M_BEGIN_METADATA(.+?)__M_END_METADATArcSsi|]\}}t|t|qSr )int)rqkvr r rG csz9ModuleInfo.get_module_source_metadata..line_map full_line_map) rsearchSgroupjsonloadsitemsrangemaxappend)clsrrZ source_mapZ f_line_maprZcurr_templ_lineZmod_liner r rGget_module_source_metadata]s(    z%ModuleInfo.get_module_source_metadatacCs |jdk r|jSt|jSdSrP)rrZread_python_filerDrKr r rGrFqs zModuleInfo.codecCs`|jdkr2t|j}|jjr,||jjS|Sn*|jjrVt|jtsV|j|jjS|jSdSrP) rrrUrr2r}decode isinstancer)r<rYr r rGr[xs   zModuleInfo.sourceN)F) rwrxryrzweakrefWeakValueDictionaryrrH classmethodrr{rFr[r r r rGr.?s  r.cCsZ|j|||j|jd}|}tj||j||j|j|j |j |j ||j |j |jd }||fS)N)rr)) r%r&r'r(Zsource_encodinggenerate_magic_commentr#r"rL)r*rr)parsercompilerr%r&r'r(encodingr#r"rL)r~r=r3rlexernoder[r r rG_compiles,rc CsL|j}t|||dd\}}|}t|}t||d}t||j|j||fS)NFrexec)rrtypes ModuleTyperr__dict__) r~r=r3 identifierr[rZcidr2rFr r rGr+s   r+c Cs|t|||dd\}}t|tr.||jp*d}|r>|||n:tjtj |d\}}t ||t |t ||dS)NTrascii)rN)rrrencodertempfilemkstemprrrQwritecloseshutilmove) r~r=r3Z outputpathr$r[rdestrlr r rGrVs     rVcCst|jdS)Nrw)_get_module_info __globals__)r5r r rGrZsrZcCs tj|SrP)r.r)r3r r rGrsr)rzrrrrrRrrrmakorrrrrrZ mako.lexerrr r|rnr.rr+rVrZrr r r rGs6       HIJ