U  el@sHdZddlZddlZddlZddlmZddlmZddlmZGdddZGdd d e Z Gd d d Z e Z d Z Gd ddZGdddZGdddZGdddZGdddeZGdddeZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd6d'd(Zd7d*d+Zd,d-Zd.d/Zd0d1Zd8d2d3Z d4d5Z!dS)9zdprovides runtime services for templates, including Context, Namespace, and various helper functions.N)compat) exceptions)utilc@seZdZdZddZddZeddZedd Zd d Z d d Z ddZ ddZ ddZ ddZddZddZd'ddZddZdd Zd!d"Zd#d$Zd%d&ZdS)(ContextzProvides runtime namespace, output buffer, and various callstacks for templates. See :ref:`runtime_toplevel` for detail on the usage of :class:`.Context`. cKsR|g|_||_||_d|_d|_i|_tt ||jd<t |_ |jd<dS)Ncapturecaller) _buffer_stack_datacopy_kwargs_with_template_outputting_as_unicode namespaces functoolspartialr CallerStack caller_stack)selfbufferdatar:/opt/hc_python/lib/python3.8/site-packages/mako/runtime.py__init__s zContext.__init__cCs0||_|j|j}|r,tdd|dS)Nz%Reserved words passed to render(): %sz, )r reserved_names intersectionr rZNameConflictErrorjoin)rtZ illegal_namesrrr_set_with_template.szContext._set_with_templatecCs|jjS)z]Return the :class:`.TemplateLookup` associated with this :class:`.Context`. )r lookuprrrrr7szContext.lookupcCs |jS)a]Return the dictionary of top level keyword arguments associated with this :class:`.Context`. This dictionary only includes the top-level arguments passed to :meth:`.Template.render`. It does not include names produced within the template execution such as local variable names or special names such as ``self``, ``next``, etc. The purpose of this dictionary is primarily for the case that a :class:`.Template` accepts arguments via its ``<%page>`` tag, which are normally expected to be passed via :meth:`.Template.render`, except the template is being called in an inheritance context, using the ``body()`` method. :attr:`.Context.kwargs` can then be used to propagate these arguments to the inheriting template:: ${next.body(**context.kwargs)} )r r rrrrkwargs?szContext.kwargscCs|j|dS)zQPush a ``caller`` callable onto the callstack for this :class:`.Context`.N)rappend)rrrrr push_callerUszContext.push_callercCs |jd=dS)zPPop a ``caller`` callable onto the callstack for this :class:`.Context`.N)rrrrr pop_caller[szContext.pop_callercCst|jS)zAReturn a list of all names established in this :class:`.Context`.)listr keysrrrrr&asz Context.keyscCs"||jkr|j|Stj|SdSN)r builtins__dict__rkeyrrr __getitem__fs  zContext.__getitem__cCst}|j||jS)zUpush a capturing buffer onto this Context and return the new writer function.)rFastEncodingBufferrr!writerbufrrr _push_writerls zContext._push_writercCs|j}||jdjfS)zupop the most recent capturing buffer from this Context and return the current writer after the pop. r#)rpopr.r/rrr_pop_buffer_and_writerts zContext._pop_buffer_and_writercCs |dS)z*push a capturing buffer onto this Context.N)r1rrrr _push_buffer}szContext._push_buffercCs |jS)z7pop the most recent capturing buffer from this Context.)rr2rrrr _pop_bufferszContext._pop_bufferNcCs|j|tj||S)z+Return a value from this :class:`.Context`.)r getr(r))rr+defaultrrrr6sz Context.getcCs|jd|dS)zSWrite a string to this :class:`.Context` object's underlying output buffer.r#Nrr.)rstringrrrr.sz Context.writecCs |jdjS)z#Return the current writer function.r#r8rrrrwriterszContext.writercCsJtt}|j|_|j|_|j|_|j|_|j|_|j|_|j |_ |Sr') r__new__rr r r r r rr)rcrrr_copys  z Context._copycCs |s|S|}|j||S)zCreate a new :class:`.Context` with a copy of this :class:`.Context`'s current state, updated with the given dictionary. The :attr:`.Context.kwargs` collection remains unaffected. )r=r update)rdr<rrr_localss  zContext._localscCs6|}|j}|dd|dd|dd|S)zfcreate a new copy of this :class:`.Context`. with tokens related to inheritance state removed.rNparentnext)r=r r2)rr<xrrr_clean_inheritance_tokenss    z!Context._clean_inheritance_tokens)N)__name__ __module__ __qualname____doc__rrpropertyrr r"r$r&r,r1r3r4r5r6r.r:r=r@rDrrrrrs*      rc@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)rcCs d|_dSr') nextcallerrrrrrszCallerStack.__init__cCs|Sr'__bool__rrrr __nonzero__szCallerStack.__nonzero__cCst|r|rdpdS)NTF)len _get_callerrrrrrLszCallerStack.__bool__cCs|dSNr#rrrrrrOszCallerStack._get_callercCst||Sr')getattrrOr*rrr __getattr__szCallerStack.__getattr__cCs|jpd}||d|_|Sr')rJr!)rframerrr _push_frames  zCallerStack._push_framecCs||_dSr')r2rJrrrr _pop_frameszCallerStack._pop_frameN) rErFrGrrMrLrOrRrTrUrrrrrsrc@s(eZdZdZddZddZddZdS) UndefinedzRepresents an undefined value in a template. All template modules have a constant value ``UNDEFINED`` present which is an instance of this object. cCs tddS)NrV) NameErrorrrrr__str__szUndefined.__str__cCs|Sr'rKrrrrrMszUndefined.__nonzero__cCsdS)NFrrrrrrLszUndefined.__bool__N)rErFrGrHrXrMrLrrrrrVsrVc@sTeZdZdZddZddZddZedd Zd d Z d d Z ddZ ddZ dS) LoopStackza stack for LoopContexts that implements the context manager protocol to automatically pop off the top of the stack on context exit cCs g|_dSr'stackrrrrrszLoopStack.__init__cCs|||jSr')_push_topriterablerrr_enters zLoopStack._entercCs||jSr')_popr^rrrr_exitszLoopStack._exitcCs|jr|jdS|SdSrPr[rrrrr^s zLoopStack._topcCs |jSr')r\r2rrrrrb szLoopStack._popcCs&t|}|jr|jd|_|j|SrP) LoopContextr\rAr!)rr`newrrrr]s zLoopStack._pushcCstddS)NzNo loop context is established)rRuntimeExceptionr*rrrrRszLoopStack.__getattr__cCs t|jSr')iterr^rrrr__iter__szLoopStack.__iter__N) rErFrGrHrrarcrIr^rbr]rRrhrrrrrZs rZc@sreZdZdZddZddZejddZe dd Z e d d Z e d d Z e ddZ e ddZddZdS)rdaA magic loop variable. Automatically accessible in any ``% for`` block. See the section :ref:`loop_context` for usage notes. :attr:`parent` -> :class:`.LoopContext` or ``None`` The parent loop, if one exists. :attr:`index` -> `int` The 0-based iteration count. :attr:`reverse_index` -> `int` The number of iterations remaining. :attr:`first` -> `bool` ``True`` on the first iteration, ``False`` otherwise. :attr:`last` -> `bool` ``True`` on the last iteration, ``False`` otherwise. :attr:`even` -> `bool` ``True`` when ``index`` is even. :attr:`odd` -> `bool` ``True`` when ``index`` is odd. cCs||_d|_d|_dSNr) _iterableindexrAr_rrrr3szLoopContext.__init__ccs$|jD]}|V|jd7_qdSN)rjrk)rirrrrh8s zLoopContext.__iter__cCs t|jSr')rNrjrrrr__len__=szLoopContext.__len__cCst||jdSrl)rNrkrrrr reverse_indexAszLoopContext.reverse_indexcCs |jdkSri)rkrrrrfirstEszLoopContext.firstcCs|jt|dkSrl)rkrNrrrrlastIszLoopContext.lastcCs|j Sr')oddrrrrevenMszLoopContext.evencCst|jdS)N)boolrkrrrrrsQszLoopContext.oddcGs|s td||jt|S)z,Cycle through values as the loop progresses.z(You must provide values to cycle through) ValueErrorrkrN)rvaluesrrrcycleUszLoopContext.cycleN)rErFrGrHrrhrZmemoized_instancemethodrorIrprqrrrtrsryrrrrrds       rdc@seZdZddZddZdS)_NSAttrcCs ||_dSr')_NSAttr__parent)rrArrrr]sz_NSAttr.__init__cCs6|j}|r*t|j|r"t|j|S|j}qt|dSr')r{hasattrmodulerQinheritsAttributeError)rr+nsrrrrR`s   z_NSAttr.__getattr__N)rErFrGrrRrrrrrz\srzc@seZdZdZdddZdZdZdZdZdZ dZ dZ e j ddZd d Zd d Zd dZeddZddZddZddZddZdS) NamespaceaProvides access to collections of rendering methods, which can be local, from other templates, or from imported modules. To access a particular rendering method referenced by a :class:`.Namespace`, use plain attribute access: .. sourcecode:: mako ${some_namespace.foo(x, y, z)} :class:`.Namespace` also contains several built-in attributes described here. NTcCs.||_||_||_|dk r*dd|D|_dS)NcSsi|] }|j|qSrrE.0r<rrr sz&Namespace.__init__..)namecontextr~ callables)rrrrr~ populate_self calling_urirrrr{s zNamespace.__init__rcCst|S)a-Access module level attributes by name. This accessor allows templates to supply "scalar" attributes which are particularly handy in inheritance relationships. .. seealso:: :ref:`inheritance_attr` :ref:`namespace_attr_for_includes` )rzrrrrattrszNamespace.attrcCsH||f}||jjkr |jj|St||j||jd}||jj|<|S)a]Return a :class:`.Namespace` corresponding to the given ``uri``. If the given ``uri`` is a relative URI (i.e. it does not contain a leading slash ``/``), the ``uri`` is adjusted to be relative to the ``uri`` of the namespace itself. This method is therefore mostly useful off of the built-in ``local`` namespace, described in :ref:`namespace_local`. In most cases, a template wouldn't need this function, and should instead use the ``<%namespace>`` tag to load namespaces. However, since all ``<%namespace>`` tags are evaluated before the body of a template ever runs, this method can be used to locate namespaces using expressions that were generated within the body code of the template, or to conditionally use a particular namespace. ) templateurir)rrTemplateNamespacer= _templateuri)rurir+rrrr get_namespaces   zNamespace.get_namespacecCst|j||jS)zReturn a :class:`.Template` from the given ``uri``. The ``uri`` resolution is relative to the ``uri`` of this :class:`.Namespace` object's :class:`.Template`. )_lookup_templaterr)rrrrr get_templateszNamespace.get_templatecKs|jj|f|S)aReturn a value from the :class:`.Cache` referenced by this :class:`.Namespace` object's :class:`.Template`. The advantage to this method versus direct access to the :class:`.Cache` is that the configuration parameters declared in ``<%page>`` take effect here, thereby calling up the same configured backend as that configured by ``<%page>``. )cacher6)rr+r rrr get_cacheds zNamespace.get_cachedcCs|jjS)zReturn the :class:`.Cache` object referenced by this :class:`.Namespace` object's :class:`.Template`. )templaterrrrrrszNamespace.cachecKst|j||jf|dS)z$Include a file at the given ``uri``.N) _include_filerr)rrr rrr include_file szNamespace.include_filecCs@|D]6}|dkr,|D]\}}|||<qqt||||<qdS)N*) _get_starrQ)rr?lidentkvrrr _populates  zNamespace._populateccs&|jr"|jD]}||j|fVq dSr')rr*rrrrs zNamespace._get_starcCsL||jkr|j|}n&|jr*t|j|}ntd|j|ft||||SNz!Namespace '%s' has no member '%s')rr~rQrrsetattr)rr+valrrrrRs    zNamespace.__getattr__)NNTN)rErFrGrHrrr}rrfilenamerrrZmemoized_propertyrrrrrIrrrrrRrrrrrjs0         rc@sNeZdZdZdddZeddZedd Zed d Zd d Z ddZ dS)rz@A :class:`.Namespace` specific to a :class:`.Template` instance.NTc Cs||_||_||_|dk r*dd|D|_|dk rNt||||_|jjj|_n"|dk rh||_|jj|_nt d|rt ||j|d\} } dS)NcSsi|] }|j|qSrrrrrrr?sz.TemplateNamespace.__init__..z 'template' argument is required.)self_ns) rrr~rrrr}Z _template_urir TypeError_populate_self_namespace) rrrrrrr~rrZ lclcallable lclcontextrrrr0s$  zTemplateNamespace.__init__cCs|jjS)zThe Python module referenced by this :class:`.Namespace`. If the namespace references a :class:`.Template`, then this module is the equivalent of ``template.module``, i.e. the generated module for the template. )rr}rrrrr}Os zTemplateNamespace.modulecCs|jjSzhThe path of the filesystem file used for this :class:`.Namespace`'s module or template. )rrrrrrrZszTemplateNamespace.filenamecCs|jjS)zThe URI for this :class:`.Namespace`'s template. I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`. This is the equivalent of :attr:`.Template.uri`. )rrrrrrras zTemplateNamespace.uric#sPjr"jD]}|j|fVq fdd}jjjD]}|||fVq8dS)Ncsj|}t|jSr')r_get_def_callablerrr)r+ callable_rrrr6qs z(TemplateNamespace._get_star..get)rrr}Z_exports)rr+r6rrrrrls   zTemplateNamespace._get_starcCst||jkr|j|}nN|j|r>|j|}t||j}n&|jrRt|j|}nt d|j |ft ||||Sr) rrZhas_defrrrrr~rQrrrrr+rrrrrrRxs      zTemplateNamespace.__getattr__)NNNNTN) rErFrGrHrrIr}rrrrRrrrrr,s      rc@s6eZdZdZd ddZeddZdd Zd d ZdS) ModuleNamespacez;A :class:`.Namespace` specific to a Python module instance.NTc Cs^||_||_||_|dk r*dd|D|_t|}|dddD]} t|| }qD||_dS)NcSsi|] }|j|qSrrrrrrrsz,ModuleNamespace.__init__...rm)rrr~r __import__splitrQr}) rrrr}rr~rrmodtokenrrrrs  zModuleNamespace.__init__cCs|jjSr)r}__file__rrrrrszModuleNamespace.filenameccsj|jr"|jD]}||j|fVq t|jD]8}|ddkr,t|j|}t|r,|t||jfVq,dS)Nr_)rdirr}rQcallablerrr)rr+rrrrrs   zModuleNamespace._get_starcCst||jkr|j|}nNt|j|r>t|j|}t||j}n&|jrRt|j|}ntd|j |ft ||||Sr) rr|r}rQrrrr~rrrrrrrrRs      zModuleNamespace.__getattr__)NNTN) rErFrGrHrrIrrrRrrrrrs   rcsfdd}|S)zApply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`. cs0|jz|f||WS|jXdSr')rrTrU)rargsr funcrrwrap_stackframes z(supports_caller..wrap_stackframer)rrrrrsupports_callers rcOs<t|std|z|||W5|}X|S)zExecute the given template def, capturing the output into a buffer. See the example in :ref:`namespaces_python_modules`. z[capture() function expects a callable as its argument (i.e. capture(func, *args, **kwargs)))rrrfr4r5getvalue)rrrr r0rrrrs rcsfdd}|S)Ncsfdd}|S)NcsLfdd}zjdd|_Wntk r6YnX|f||S)Ncsf||Sr'rrkw)r render_fnrryszB_decorate_toplevel..decorate_render..go..y)rEr)rrrr)fnr)rrgos z7_decorate_toplevel..decorate_render..gorrrr)rrdecorate_renders z+_decorate_toplevel..decorate_renderr)rrrrr_decorate_toplevels rcsfdd}|S)Ncs|fdd}|S)Ncsf||Sr'rr)rdecrrrsz5_decorate_inline..decorate_render..gorrrr)rrrsz)_decorate_inline..decorate_renderr)rrrrrr_decorate_inlinesrcKst|||}t||\}}t||jf|}|jrrz||f|Wq~tk rn||t}|sjYq~Xn ||f|dS)zPlocate the template from the given uri and include it in the current output.N) rrrD_kwargs_for_includer Zinclude_error_handler Exceptionr exception_as)rrrr rrctxresultrrrrs  rc Cs|dkr dSt|||}|d}|}|jdk r6|j}q$|d|i}td|j||dd|_|j|jd<|jd<t|jd d}|dk r|||}|r|St|jd d} | dk r| ||j|fS) zcalled by the _inherit method in template modules to set up the inheritance chain at the start of a template's execution.NrrBself:%sFrrrAlocal _mako_inheritZ_mako_generate_namespaces) rr~r@rrr rQr}r) rrrrrZihrrretZgen_nsrrr _inherit_froms0   rc Csx|jj}|dkr"td|jj|||}z ||WStjk rr}zttt |W5d}~XYnXdS)Nz.Template '%s' has no TemplateLookup associated) r rrZTemplateLookupExceptionrZ adjust_urirZTopLevelLookupExceptionstrrr)rrZ relativetorerrrr<s    rcCs^|dkrtd|j||dd}||jd<|jd<t|jdrT|j||}|rT|S|j|fS)NrFrrrr)rrr r|r}rr)rrrrrrrrLs rFcCsb|rt}ntj|j|jd}t|f|}||_||t|||f|t||| S)z^create a Context and return the string output of the given template and template callable.)encodingerrors) rr-output_encodingencoding_errorsrr r_render_context_kwargs_for_callabler5r)rrrrZ as_unicoder0rrrr_render\s&   rcCsjt|}|dr|S|ddd|ddD}i}|D](}|dkr<||kr<||kr<||||<q<|S)NrurcSsg|]}|dk r|qSr'rrrrrr {sz(_kwargs_for_callable..rmrrZinspect_getargspec)rrargspec namedargsr argrrrrts rcKsZt|}|ddd|ddD}|D](}|dkr,||kr,||kr,||||<q,|S)NrcSsg|]}|dk r|qSr'rrrrrrsz'_kwargs_for_include..rmrrr)rrr rrrrrrrs  rcOs\ddlm}t||js8t||\}}t||||dn t||j\}}t||||ddS)Nr)rr )Z mako.templater isinstanceZ DefTemplater_exec_templaterA)tmplrrrr rinheritrrrrrs   rcCs|j}|dk rx|js|jrxz||f||Wqtk rRt||tYqtd}t|||YqXn||f||dS)zexecute a rendering callable given the callable, a Context, and optional explicit arguments the contextual Template will be located if it exists, and the error handling options specified on that Template will be interpreted here. Nr) r Zformat_exceptions error_handlerr _render_errorrrsysexc_info)rrrr rrrrrrs rcCs|jr>|||}|st\}}}|r8|r8||q|nXt}|jrbtg|j dd<nt|j |j g|j dd<| ||j ||ddS)N)error)rrrwith_tracebackrZhtml_error_templater rr-rrrrZrender_context)rrrrtpvaluetbZerror_templaterrrrs"   r)N)F)NN)"rHr(rrmakorrrrr%rrV UNDEFINEDZSTOP_RENDERINGrZrdrzrrrrrrrrrrrrrrrrrrrrrsB   -(AC]: