Render complex sub-objects using json.dumps
Normally pystache will just use the python unicode representation of objects. This is not very useful programatically. Rendering using json makes these values more useful.
This commit is contained in:
parent
9883a86228
commit
e34be4df0f
@ -2,7 +2,6 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pystache
|
||||
import sys
|
||||
from argparse import ArgumentParser
|
||||
from pystache.context import KeyNotFoundError
|
||||
@ -10,6 +9,7 @@ from subprocess import Popen, PIPE
|
||||
from tempfile import NamedTemporaryFile
|
||||
from value_types import ensure_type
|
||||
from config_exception import ConfigException
|
||||
from renderers import JsonRenderer
|
||||
|
||||
TEMPLATES_DIR = os.environ.get('OS_CONFIG_APPLIER_TEMPLATES',
|
||||
'/opt/stack/os-config-applier/templates')
|
||||
@ -76,7 +76,7 @@ def is_executable(path):
|
||||
|
||||
|
||||
def render_moustache(text, config):
|
||||
r = pystache.Renderer(missing_tags='strict')
|
||||
r = JsonRenderer(missing_tags='strict')
|
||||
return r.render(text, config)
|
||||
|
||||
|
||||
|
26
os_config_applier/renderers.py
Normal file
26
os_config_applier/renderers.py
Normal file
@ -0,0 +1,26 @@
|
||||
import json
|
||||
|
||||
from pystache import Renderer
|
||||
|
||||
|
||||
class JsonRenderer(Renderer):
|
||||
def __init__(self,
|
||||
file_encoding=None,
|
||||
string_encoding=None,
|
||||
decode_errors=None,
|
||||
search_dirs=None,
|
||||
file_extension=None,
|
||||
escape=None,
|
||||
partials=None,
|
||||
missing_tags=None):
|
||||
# json would be html escaped otherwise
|
||||
if escape is None:
|
||||
escape = lambda u: u
|
||||
return super(JsonRenderer, self).__init__(file_encoding,
|
||||
string_encoding,
|
||||
decode_errors, search_dirs,
|
||||
file_extension, escape,
|
||||
partials, missing_tags)
|
||||
|
||||
def str_coerce(self, val):
|
||||
return json.dumps(val)
|
19
tests/json_renderer_tests.py
Normal file
19
tests/json_renderer_tests.py
Normal file
@ -0,0 +1,19 @@
|
||||
import json
|
||||
|
||||
from nose.tools import assert_equals
|
||||
from os_config_applier.renderers import JsonRenderer
|
||||
|
||||
TEST_JSON = '{"a":{"b":[1,2,3,"foo"],"c": "the quick brown fox"}}'
|
||||
|
||||
|
||||
def test_json_renderer():
|
||||
context = json.loads(TEST_JSON)
|
||||
x = JsonRenderer()
|
||||
result = x.render('{{a.b}}', context)
|
||||
print result
|
||||
result_structure = json.loads(result)
|
||||
desire_structure = json.loads('[1,2,3,"foo"]')
|
||||
assert_equals(desire_structure, result_structure)
|
||||
result = x.render('{{a.c}}', context)
|
||||
print result
|
||||
assert_equals(u'the quick brown fox', result)
|
Loading…
x
Reference in New Issue
Block a user