PyFoam.ThirdParty.pyratemp module¶
Small, simple and powerful template-engine for python.
A template-engine for python, which is very simple, easy to use, small, fast, powerful, modular, extensible, well documented and pythonic.
See documentation for a list of features, template-syntax etc.
Version: | 0.2.0 |
---|---|
Usage: | see class |
Example: |
|
Author: | Roland Koebler (rk at simple-is-better dot org) |
Copyright: | Roland Koebler |
License: | MIT/X11-like, see __license__ |
-
class
PyFoam.ThirdParty.pyratemp.
EvalPseudoSandbox
[source]¶ An eval-pseudo-sandbox.
The pseudo-sandbox restricts the available functions/objects, so the code can only access:
- some of the builtin python-functions, which are considered “safe” (see safe_builtins)
- some additional functions (exists(), default(), setvar())
- the passed objects incl. their methods.
Additionally, names beginning with “_” are forbidden. This is to prevent things like ‘0 .__class__’, with which you could easily break out of a “sandbox”.
Be careful to only pass “safe” objects/functions to the template, because any unsafe function/method could break the sandbox! For maximum security, restrict the access to as few objects/functions as possible!
Warning: Note that this is no real sandbox! (And although I don’t know any way to break out of the sandbox without passing-in an unsafe object, I cannot guarantee that there is no such way. So use with care.)
Take care if you want to use it for untrusted code!!
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
compile
(expr)[source]¶ Compile a python-eval-expression.
- Use a compile-cache.
- Raise a NameError if expr contains a name beginning with
_
.
Returns: the compiled expr
Exceptions: - SyntaxError: for compile-errors
- NameError: if expr contains a name beginning with
_
-
eval
(expr, locals)[source]¶ Eval a python-eval-expression.
Sets
self.locals_ptr
tolocales
and compiles the code before evaluating.
-
f_default
(expr, default=None)[source]¶ default()
for the sandboxed code.Try to evaluate an expression and return the result or a fallback-/default-value; the default-value is used if expr does not exist/is invalid/results in None.
This is very useful for optional data.
Parameter: - expr: eval-expression
- default: fallback-falue if eval(expr) fails or is None.
Returns: the eval-result or the “fallback”-value.
Note: the eval-expression has to be quoted! (like in eval)
Example: see module-docstring
-
f_exists
(varname)[source]¶ exists()
for the sandboxed code.Test if the variable varname exists in the current locals-namespace.
This only works for single variable names. If you want to test complicated expressions, use i.e. default. (i.e. default(“expr”,False))
Note: the variable-name has to be quoted! (like in eval) Example: see module-docstring
-
f_import
(name, *args, **kwargs)[source]¶ import
/__import__()
for the sandboxed code.Since “import” is insecure, the PseudoSandbox does not allow to import other modules. But since some functions need to import other modules (e.g. “datetime.datetime.strftime” imports “time”), this function replaces the builtin “import” and allows to use modules which are already accessible by the sandboxed code.
Note: - This probably only works for rather simple imports.
- For security, it may be better to avoid such (complex) modules which import other modules. (e.g. use time.localtime and time.strftime instead of datetime.datetime.strftime)
Example: >>> from datetime import datetime >>> import pyratemp >>> t = pyratemp.Template('@!mytime.strftime("%H:%M:%S")!@') >>> print t(mytime=datetime.now()) Traceback (most recent call last): ... ImportError: import not allowed in pseudo-sandbox; try to import 'time' yourself and pass it to the sandbox/template >>> import time >>> print t(mytime=datetime.strptime("13:40:54", "%H:%M:%S"), time=time) 13:40:54
# >>> print t(mytime=datetime.now(), time=time) # 13:40:54
-
f_setvar
(name, expr)[source]¶ setvar()
for the sandboxed code.Set a variable.
Example: see module-docstring
-
register
(name, obj)[source]¶ Add an object to the “allowed eval-globals”.
Mainly useful to add user-defined functions to the pseudo-sandbox.
-
safe_builtins
= {'abs': <built-in function abs>, 'bool': <type 'bool'>, 'chr': <built-in function chr>, 'complex': <type 'complex'>, 'dict': <type 'dict'>, 'divmod': <built-in function divmod>, 'enumerate': <type 'enumerate'>, 'float': <type 'float'>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'int': <type 'int'>, 'len': <built-in function len>, 'list': <type 'list'>, 'max': <built-in function max>, 'min': <built-in function min>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'range': <built-in function range>, 'reversed': <type 'reversed'>, 'round': <built-in function round>, 'sorted': <built-in function sorted>, 'str': <type 'str'>, 'sum': <built-in function sum>, 'tuple': <type 'tuple'>, 'zip': <built-in function zip>}¶
-
safe_builtins_python2
= {'False': '__builtin__.False', 'None': '__builtin__.None', 'True': '__builtin__.True', 'cmp': '__builtin__.cmp', 'long': '__builtin__.long', 'unichr': '__builtin__.unichr', 'unicode': '__builtin__.unicode', 'xrange': '__builtin__.xrange'}¶
-
class
PyFoam.ThirdParty.pyratemp.
LoaderFile
(allowed_path=None, encoding='utf-8')[source]¶ Load template from a file.
When loading a template from a file, it’s possible to including other templates (by using ‘include’ in the template). But for simplicity and security, all included templates have to be in the same directory! (see
allowed_path
)-
__init__
(allowed_path=None, encoding='utf-8')[source]¶ Init the loader.
Parameters: - allowed_path: path of the template-files
- encoding: encoding of the template-files
Exceptions: - ValueError: if allowed_path is not a directory
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
-
class
PyFoam.ThirdParty.pyratemp.
LoaderString
(encoding='utf-8')[source]¶ Load template from a string/unicode.
Note that ‘include’ is not possible in such templates.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
-
class
PyFoam.ThirdParty.pyratemp.
Parser
(loadfunc=None, testexpr=None, escape=1)[source]¶ Bases:
object
Parse a template into a parse-tree.
Includes a syntax-check, an optional expression-check and verbose error-messages.
See documentation for a description of the parse-tree.
-
__dict__
= dict_proxy({'_parse_sub': <function _parse_sub>, '__module__': 'PyFoam.ThirdParty.pyratemp', '_sub_start': '$!', '_strBlock': '\n ^(?P<mEnd>[ \\t]*)\\<\\!\\-\\-\\(end\\)\\-\\-\\>(?P<meIgnored>.*)\\r?\\n? # multi-line end (^ <!--(end)-->IGNORED_TEXT\\n)\n |\n (?P<sEnd>)\\<\\!\\-\\-\\(end\\)\\-\\-\\> # single-line end (<!--(end)-->)\n |\n (?P<sSpace>[ \\t]*) # single-line tag (no nesting)\n \\<\\!\\-\\-\\((?P<sKeyw>\\w+)[ \\t]*(?P<sParam>.*?)\\)\\-\\-\\>\n (?P<sContent>.*?)\n (?=(?:\\<\\!\\-\\-\\(.*?\\)\\-\\-\\>.*?)??\\<\\!\\-\\-\\(end\\)\\-\\-\\>) # (match until end or i.e. <!--(elif/else...)-->)\n |\n # multi-line tag, nested by whitespace indentation\n ^(?P<indent>[ \\t]*) # save indentation of start tag\n \\<\\!\\-\\-\\((?P<mKeyw>\\w+)\\s*(?P<mParam>.*?)\\)\\-\\-\\>(?P<mIgnored>.*)\\r?\\n\n (?P<mContent>(?:.*\\n)*?)\n (?=(?P=indent)\\<\\!\\-\\-\\((?:.|\\s)*?\\)\\-\\-\\>) # match indentation\n ', '_testexpr': <function _testexpr>, '_reSubstitution': <_sre.SRE_Pattern object>, '_subesc_start': '@!', '_strForParam': '^(?P<names>\\w+(?:\\s*,\\s*\\w+)*)\\s+in\\s+(?P<iter>.+)$', '_reMacroParam': <_sre.SRE_Pattern object>, '_subesc_end': '!@', '_strComment': '\\#\\!(?P<content>.*?)(?P<end>\\!\\#|\\n|$)', '__dict__': <attribute '__dict__' of 'Parser' objects>, '_parse': <function _parse>, '_block_start': '<!--(', '__weakref__': <attribute '__weakref__' of 'Parser' objects>, '_comment_start': '#!', '__init__': <function __init__>, 'parse': <function parse>, '_comment_end': '!#', '_reBlock': <_sre.SRE_Pattern object>, '_s': '\\<\\!\\-\\-\\(', '_block_end': ')-->', '_errpos': <function _errpos>, '_strSubstitution': '\n (\n \\$\\!\\s*(?P<sub>.*?)\\s*(?P<end>\\!\\$|$) #substitution\n |\n \\@\\!\\s*(?P<escsub>.*?)\\s*(?P<escend>\\!\\@|$) #escaped substitution\n )\n ', '_reComment': <_sre.SRE_Pattern object>, '_reForParam': <_sre.SRE_Pattern object>, '_sub_end': '!$', '_e': '\\)\\-\\-\\>', '__doc__': 'Parse a template into a parse-tree.\n\n Includes a syntax-check, an optional expression-check and verbose\n error-messages.\n\n See documentation for a description of the parse-tree.\n '})¶
-
__init__
(loadfunc=None, testexpr=None, escape=1)[source]¶ Init the parser.
Parameters: - loadfunc: function to load included templates
(i.e.
LoaderFile(...).load
) - testexpr: function to test if a template-expressions is valid
(i.e.
EvalPseudoSandbox().compile
) - escape: default-escaping (may be modified by the template)
Exceptions: - ValueError: if testexpr or escape is invalid.
- loadfunc: function to load included templates
(i.e.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
_block_end
= ')-->'¶
-
_block_start
= '<!--('¶
-
_comment_end
= '!#'¶
-
_comment_start
= '#!'¶
-
_e
= '\\)\\-\\-\\>'¶
-
_parse
(template, fpos=0)[source]¶ Recursive part of parse().
Parameters: - template
- fpos: position of
template
in the complete template (for error-messages)
-
_parse_sub
(parsetree, text, fpos=0)[source]¶ Parse substitutions, and append them to the parse-tree.
Additionally, remove comments.
-
_reBlock
= <_sre.SRE_Pattern object>¶
-
_reComment
= <_sre.SRE_Pattern object>¶
-
_reForParam
= <_sre.SRE_Pattern object>¶
-
_reMacroParam
= <_sre.SRE_Pattern object>¶
-
_reSubstitution
= <_sre.SRE_Pattern object>¶
-
_s
= '\\<\\!\\-\\-\\('¶
-
_strBlock
= '\n ^(?P<mEnd>[ \\t]*)\\<\\!\\-\\-\\(end\\)\\-\\-\\>(?P<meIgnored>.*)\\r?\\n? # multi-line end (^ <!--(end)-->IGNORED_TEXT\\n)\n |\n (?P<sEnd>)\\<\\!\\-\\-\\(end\\)\\-\\-\\> # single-line end (<!--(end)-->)\n |\n (?P<sSpace>[ \\t]*) # single-line tag (no nesting)\n \\<\\!\\-\\-\\((?P<sKeyw>\\w+)[ \\t]*(?P<sParam>.*?)\\)\\-\\-\\>\n (?P<sContent>.*?)\n (?=(?:\\<\\!\\-\\-\\(.*?\\)\\-\\-\\>.*?)??\\<\\!\\-\\-\\(end\\)\\-\\-\\>) # (match until end or i.e. <!--(elif/else...)-->)\n |\n # multi-line tag, nested by whitespace indentation\n ^(?P<indent>[ \\t]*) # save indentation of start tag\n \\<\\!\\-\\-\\((?P<mKeyw>\\w+)\\s*(?P<mParam>.*?)\\)\\-\\-\\>(?P<mIgnored>.*)\\r?\\n\n (?P<mContent>(?:.*\\n)*?)\n (?=(?P=indent)\\<\\!\\-\\-\\((?:.|\\s)*?\\)\\-\\-\\>) # match indentation\n '¶
-
_strComment
= '\\#\\!(?P<content>.*?)(?P<end>\\!\\#|\\n|$)'¶
-
_strForParam
= '^(?P<names>\\w+(?:\\s*,\\s*\\w+)*)\\s+in\\s+(?P<iter>.+)$'¶
-
_strSubstitution
= '\n (\n \\$\\!\\s*(?P<sub>.*?)\\s*(?P<end>\\!\\$|$) #substitution\n |\n \\@\\!\\s*(?P<escsub>.*?)\\s*(?P<escend>\\!\\@|$) #escaped substitution\n )\n '¶
-
_sub_end
= '!$'¶
-
_sub_start
= '$!'¶
-
_subesc_end
= '!@'¶
-
_subesc_start
= '@!'¶
-
-
class
PyFoam.ThirdParty.pyratemp.
Renderer
(evalfunc, escapefunc)[source]¶ Bases:
object
Render a template-parse-tree.
Uses: TemplateBase for macros -
__dict__
= dict_proxy({'__module__': 'PyFoam.ThirdParty.pyratemp', 'render': <function render>, '__dict__': <attribute '__dict__' of 'Renderer' objects>, '_eval': <function _eval>, '__weakref__': <attribute '__weakref__' of 'Renderer' objects>, '__doc__': 'Render a template-parse-tree.\n\n :Uses: `TemplateBase` for macros\n ', '__init__': <function __init__>})¶
-
__init__
(evalfunc, escapefunc)[source]¶ Init the renderer.
Parameters: - evalfunc: function for template-expression-evaluation
(i.e.
EvalPseudoSandbox().eval
) - escapefunc: function for escaping special characters (i.e. escape)
- evalfunc: function for template-expression-evaluation
(i.e.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
PyFoam.ThirdParty.pyratemp.
Template
(string=None, filename=None, parsetree=None, encoding='utf-8', data=None, escape=1, loader_class=<class PyFoam.ThirdParty.pyratemp.LoaderFile>, parser_class=<class 'PyFoam.ThirdParty.pyratemp.Parser'>, renderer_class=<class 'PyFoam.ThirdParty.pyratemp.Renderer'>, eval_class=<class PyFoam.ThirdParty.pyratemp.EvalPseudoSandbox>, escape_func=<function escape>)[source]¶ Bases:
PyFoam.ThirdParty.pyratemp.TemplateBase
Template-User-Interface.
Usage: - ::
t = Template(…) (<- see __init__) output = t(…) (<- see TemplateBase.__call__)
Example: see module-docstring
-
__init__
(string=None, filename=None, parsetree=None, encoding='utf-8', data=None, escape=1, loader_class=<class PyFoam.ThirdParty.pyratemp.LoaderFile>, parser_class=<class 'PyFoam.ThirdParty.pyratemp.Parser'>, renderer_class=<class 'PyFoam.ThirdParty.pyratemp.Renderer'>, eval_class=<class PyFoam.ThirdParty.pyratemp.EvalPseudoSandbox>, escape_func=<function escape>)[source]¶ Load (+parse) a template.
Parameters: - string,filename,parsetree: a template-string,
- filename of a template to load, or a template-parsetree. (only one of these 3 is allowed)
- encoding: encoding of the template-files (only used for “filename”)
- data: data to fill into the template by default (dictionary).
- This data may later be overridden when rendering the template.
- escape: default-escaping for the template, may be overwritten by the template!
- loader_class
- parser_class
- renderer_class
- eval_class
- escapefunc
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
class
PyFoam.ThirdParty.pyratemp.
TemplateBase
(parsetree, renderfunc, data=None)[source]¶ Basic template-class.
Used both for the template itself and for ‘macro’s (“subtemplates”) in the template.
-
__call__
(**override)[source]¶ Fill out/render the template.
Parameters: - override: objects to add to the data-namespace, overriding the “default”-data.
Returns: the filled template (in unicode)
Note: This is also called when invoking macros (i.e.
$!mymacro()!$
).
-
__init__
(parsetree, renderfunc, data=None)[source]¶ Create the Template/Subtemplate/Macro.
Parameters: - parsetree: parse-tree of the template/subtemplate/macro
- renderfunc: render-function
- data: data to fill into the template by default (dictionary). This data may later be overridden when rendering the template.
Exceptions: - TypeError: if data is not a dictionary
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
-
exception
PyFoam.ThirdParty.pyratemp.
TemplateException
[source]¶ Bases:
exceptions.Exception
Base class for template-exceptions.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
exception
PyFoam.ThirdParty.pyratemp.
TemplateIncludeError
(err, errpos)[source]¶ Bases:
PyFoam.ThirdParty.pyratemp.TemplateParseError
Template ‘include’ failed.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
-
exception
PyFoam.ThirdParty.pyratemp.
TemplateParseError
(err, errpos)[source]¶ Bases:
PyFoam.ThirdParty.pyratemp.TemplateException
Template parsing failed.
-
__init__
(err, errpos)[source]¶ Parameters: - err: error-message or exception to wrap
- errpos:
(filename,row,col)
where the error occured.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
-
exception
PyFoam.ThirdParty.pyratemp.
TemplateRenderError
[source]¶ Bases:
PyFoam.ThirdParty.pyratemp.TemplateException
Template rendering failed.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
-
exception
PyFoam.ThirdParty.pyratemp.
TemplateSyntaxError
(err, errpos)[source]¶ Bases:
PyFoam.ThirdParty.pyratemp.TemplateParseError
,exceptions.SyntaxError
Template syntax-error.
-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
-
class
PyFoam.ThirdParty.pyratemp.
_dontescape
[source]¶ Bases:
unicode
Unicode-string which should not be escaped.
If
isinstance(object,_dontescape)
, then don’t escape the object in@!...!@
. It’s useful for not double-escaping macros, and it’s automatically used for macros/subtemplates.Note: This only works if the object is used on its own in @!...!@
. It i.e. does not work in@!object*2!@
or@!object + "hi"!@
.-
__module__
= 'PyFoam.ThirdParty.pyratemp'¶
-
__slots__
= []¶
-
-
PyFoam.ThirdParty.pyratemp.
dummy_raise
(exception, value)[source]¶ Create an exception-raising dummy function.
Returns: dummy function, raising exception(value)
-
PyFoam.ThirdParty.pyratemp.
escape
(s, format=1)[source]¶ Replace special characters by their escape sequence.
Parameters: - s: string or unicode-string to escape
- format:
- NONE: nothing is replaced
- HTML: replace &<>’” by &…;
- LATEX: replace #$%&_{} (TODO! - this is very incomplete!)
Returns: the escaped string in unicode
Exceptions: - ValueError: if format is invalid.
TODO: complete LaTeX-escaping, optimize speed
-
PyFoam.ThirdParty.pyratemp.
scol
(string, i)[source]¶ Get column number of
string[i]
in string.Returns: column, starting at 1 (but may be <1 if i<0) Note: This works for text-strings with \n
or\r\n
.
-
PyFoam.ThirdParty.pyratemp.
sindex
(string, row, col)[source]¶ Get index of the character at row/col in string.
Parameters: - row: row number, starting at 1.
- col: column number, starting at 1.
Returns: i
, starting at 0 (but may be <1 if row/col<0)Note: This works for text-strings with ‘n’ or ‘rn’.