yaml和json的模板引擎

emrichen的Python项目详细描述


emrichen–yaml&json的模板引擎

Build StatusPyPI version

emrichen接受用yaml或json编写的模板,处理诸如变量替换之类的标记,并输出yaml或json。

与基于文本的模板系统相比,emrichen更好地生成yaml或json的原因是它在yaml(或json)中工作

有没有试过将一个列表或dict替换成一个yaml文档仅仅是为了遇到缩进问题?好可怕!处理引号和双反斜杠转义符?不!

在emrichen中,变量被输入到熟悉的json类型中,这使得这些不成问题。emrichen是一种实用而强大的生成yaml和json的方法。

考虑以下生成最小kubernetes部署的模板:

!Defaultstag:latestimage:!Format"nginx:{tag}"replicas:3---apiVersion:apps/v1kind:Deploymentmetadata:name:nginxspec:selector:matchLabels:app:nginxreplicas:!Varreplicastemplate:metadata:labels:app:nginxspec:containers:-name:nginximage:!Varimageports:-containerPort:80

这个小模板已经演示了emrichen的三个强大标记:!Defaults为变量提供默认值;!Var执行简单的变量替换;以及!Format执行字符串格式。

把它放到一个文件中,比如说,nginx.in.yaml(我们使用.in.yaml来表示模板),然后使用这个命令来呈现它:

emrichen nginx.in.yaml

更喜欢json输出?

emrichen --output-format json nginx.in.yaml

想换个标签吗?

emrichen --define tag=1-alpine nginx.in.yaml

注意image是如何被惰性地计算的–您不需要重写image只需更改tag

有关支持的标记的表,请参见下文。有很多。如果您需要一个还没有的,请向我们拍摄一个问题或公关。

安装

需要Python3.5+版本。python 2不受支持,也将不受支持。

pip3 install emrichen

支持的标记

TagArgumentsExampleDescription
^{}An iterable^{}Returns true iff all the items of the iterable argument are truthy.
^{}An iterable^{}Returns true iff at least one of the items of the iterable argument is truthy.
^{}The value to encode^{}Encodes the value (or a string representation thereof) into base64.
^{}^{}: The value to apply tags on
^{}: A list of tag names to apply, latest first
^{}Used internally to implement tag composition.
Usually not used in the spelt-out form.
See Tag composition below.
^{}A list of lists^{}Concatenates lists.
^{}Anything, really^{}Enriches its argument, outputs it to stderr and returns it. Useful to check the value
of some expression deep in a big template, perhaps even one that doesn't even fully render.
^{}A dict of variable definitionsSee ^{}Defines default values for variables. These will be overridden by any other variable source.
NOTE: ^{} must appear in a document of its own in the template file (ie. separated by ^{}). The document containing ^{} will be erased from the output.
^{}Error message^{}If the ^{} tag is present in the template after resolving all conditionals,
it will cause the template rendering to exit with error emitting the specified error message.
^{}JSONPath expression^{}Returns ^{} if the JSONPath expression returns one or more matches, ^{} otherwise.
^{}^{}, ^{}See ^{}Takes in a list and only returns elements that pass a predicate.
^{}Format string^{}Interpolate strings using Python format strings.
JSONPath supported in variable lookup (eg. ^{} will do the right thing).
NOTE: When the format string starts with ^{}, you need to quote it in order to avoid being interpreted as a YAML object.
^{}Accepts the same arguments as ^{}, except ^{} is optional (default identity), plus the following:
^{}: (required) An expression used to determine the key for the current value
^{}: (optional, string) When evaluating ^{}, the enriched ^{} is available under this name.
TBDMakes a dict out of a list. Keys are determined by ^{}. Items with the same key are grouped in a list.
^{}^{}, ^{}, ^{}See ^{}Returns one of two values based on a condition.
^{}Path to a template to include^{}Renders the requested template at this location. Both absolute and relative paths work.
^{}Path to a binary file^{}Loads the given binary file and returns the contents encoded as Base64.
^{}Path to a binary file^{}Loads the given binary file and returns the contents as bytes. This is practically only useful for hashing.
^{}Path to an UTF-8 text file^{}Loads the given UTF-8 text file and returns the contents as a string.
^{}Accepts the same arguments as ^{}, except ^{} is optional (default identity), plus the following:
^{}: (required) An expression used to determine the key for the current value
^{}: (optional, string) When evaluating ^{}, the enriched ^{} is available under this name.
^{}: (optional, default ^{}) ^{}, ^{} or ^{} duplicate values.
TBDMakes a dict out of a list. Keys are determined by ^{}.
^{}Data to typecheck.^{}Returns True if the value enriched is of the given type, False otherwise.
^{}Data to typecheck.^{}Returns True if the value enriched is of the given type, False otherwise.
^{}Data to typecheck.^{}Returns True if the value enriched is of the given type, False otherwise.
^{}Data to typecheck.^{}Returns True if the value enriched is of the given type, False otherwise.
^{}Data to typecheck.^{}Returns True if the value enriched is None (null) or Void, False otherwise.
^{}Data to typecheck.^{}Returns True if the value enriched is of the given type, False otherwise.
^{}Data to typecheck.^{}Returns True if the value enriched is of the given type, False otherwise.
^{}^{}: (required) A list of items to be joined together.
^{}: (optional, default space) The separator to place between the items.
OR
a list of items to be joined together with a space as the separator.
^{}
^{}
Joins a list of items together with a separator. The result is always a string.
^{}JSONPath expression^{}Performs a JSONPath lookup returning the first match. If there is no match, an error is raised.
^{}JSONPath expression^{}Performs a JSONPath lookup returning all matches as a list. If no matches are found, the empty list ^{} is returned.
^{}^{}: (required) The data to iterate over (a literal list or dict, or !Var)
^{}: (optional, default ^{}) The variable name given to the current value
^{}: (optional) The variable name given to the loop index. If over is a list, this is a numeric index starting from ^{}. If over is a dict, this is the dict key.
^{}: (optional, default ^{}) First index, for eg. 1-based indexing.
^{}: (optional) The variable name given to the previous value. On the first iteration of the loop, the previous value is ^{}. Added in 0.2.0
^{}: (required) The template to process for each iteration of the loop.
^{}: (optional) Whether to "unfold" the output of this loop into separate YAML documents when writing YAML. Only has an effect at the top level of a template.
See ^{}.Loops over a list or dict and renders a template for each iteration. The output is always a list.
^{}Data to hash^{}Hashes the given data using the MD5 algorithm. If the data is not binary, it is converted to UTF-8 bytes.
^{}A list of dicts^{}Merges objects. For overlapping keys the last one takes precedence.
^{}a value^{}Logically negates the given value (in Python semantics).
^{}^{}, ^{}, ^{}See ^{}Performs binary operators. Especially useful with ^{} to implement greater-than etc.
^{}Data to hash^{}Hashes the given data using the SHA1 algorithm. If the data is not binary, it is converted to UTF-8 bytes.
^{}Data to hash^{}Hashes the given data using the SHA256 algorithm. If the data is not binary, it is converted to UTF-8 bytes.
^{}A string to encode
OR
^{}: The URL to combine query parameters into
^{}: An object of query string parameters to add.
^{}
^{}
Encodes strings for safe inclusion in a URL, or combines query string parameters into a URL.
^{}Variable name^{}Replaced with the value of the variable.
^{}Anything or nothing^{}The dict key, list item or YAML document that resolves to ^{} is removed from the output.
^{}^{}: A dict of variable definitions.
^{}: The template to process with the variables defined.
See ^{}.Binds local variables that are only visible within ^{}. Useful for giving a name for common sub-expressions.

json中的标记

json没有本机标记构造。相反,使用一个带有一个键的对象,该键是标记的名称(包括bang,例如!Var)。例如:

{"foo":{"!Var":"foo"}}

json支持的局限性:

  • 不支持以!开头的对象键。
  • 呈现为json的模板只能包含一个文档。
    • json模板总是只有一个文档。
    • yaml模板只能包含一个非!Void,非!Defaults文档。
  • 由于!Defaults必须出现在自己的文档中,因此json模板不支持它。改用var文件。

标签组成

由于yaml,您不能执行!Base64 !Var foo。我们提供了一个方便的解决方案:!Base64,Var foo

cli

usage: emrichen [-h] [--template-format {yaml,json}] [--var-file VAR_FILE]
                [--define VAR=VALUE] [--output-file OUTPUT_FILE]
                [--output-format {yaml,json}] [--include-env]
                [template_file]

A YAML to YAML preprocessor.

positional arguments:
  template_file         The YAML template to process. If unspecified, the
                        template is read from stdin.

optional arguments:
  -h, --help            show this help message and exit
  --template-format {yaml,json}
                        Template format. If unspecified, attempted to be
                        autodetected from the input filename (but defaults to
                        YAML).
  --var-file VAR_FILE, -f VAR_FILE
                        A YAML file containing an object whose top-level keys
                        will be defined as variables. May be specified
                        multiple times.
  --define VAR=VALUE, -D VAR=VALUE
                        Defines a single variable. May be specified multiple
                        times.
  --output-file OUTPUT_FILE, -o OUTPUT_FILE
                        Output file. If unspecified, the template output is
                        written into stdout.
  --output-format {yaml,json}
                        Output format. If unspecified, attempted to be
                        autodetected from the output filename (but defaults to
                        YAML).
  --include-env, -e     Expose process environment variables to the template.

Variable precedence: -D > -e > -f > !Defaults

示例

cd examples/kubernetes
emrichen -f vars.yml -D tag=build-256 deployment.in.yml

python api

待办事项

emrichen(template, *variable_sources, **override_variables)

Context(*variable_sources, **override_variables)

Template(template_source)

许可证

The MIT License (MIT)

Copyright © 2018–2019 Santtu Pajukanta
Copyright © 2018–2019 Aarni Koskela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java文件分块,获取长度字节   java嵌入式Tomcat不执行jsf页面   java我的数据库中有2个实体,但hibernate返回其中6个。   java如何基于逗号拆分字符串   java取消已经运行的CompletableFutures的预期模式是什么   java如何在informix中从另一个数据库复制表ddl和数据   为什么图片是黑色的?   java根据字符串数组中的单词筛选列表   Java8的集合。平行流有效吗?   Kotlin中的java静态内部类   java如何在GUI中生成一列字符串   javafx如何正确使用高对比度主题?   带空格的javascript Httpurlconnection参数   java如何设置GridBagLayout的约束   java如何在一个线程可能尚未初始化时关闭另一个线程   java将简单时间格式转换为特殊时间格式(hhmmt)   安卓/java阵列重复过滤器的问题   java在队列的链接实现下,入队和出队是如何工作的   java更新sql外键约束