Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
[context] Improved flexibility of configuration variables
Now the form {{var_name}} is allowed too.
- Loading branch information
Showing
with
13 additions
and
4 deletions.
-
+1
−2
docs/source/general/basics.rst
-
+3
−2
netjsonconfig/utils.py
-
+9
−0
tests/test_utils.py
|
@@ -354,8 +354,7 @@ Let's see the result with: |
|
|
.. warning:: |
|
|
**When using variables, keep in mind the following rules**: |
|
|
|
|
|
* variables must be written in the form of ``{{ var_name }}``, including |
|
|
spaces around ``var_name``; |
|
|
* variables must be written in the form of ``{{ var_name }}`` or ``{{var_name}}``; |
|
|
* variable names can contain only alphanumeric characters and underscores; |
|
|
* unrecognized variables will be ignored; |
|
|
|
|
|
|
@@ -37,7 +37,7 @@ def sorted_dict(dictionary): |
|
|
return OrderedDict(sorted(dictionary.items())) |
|
|
|
|
|
|
|
|
var_pattern = re.compile(r'\{\{\s(\w*)\s\}\}') |
|
|
var_pattern = re.compile(r'\{\{(.*)\}\}') |
|
|
|
|
|
|
|
|
def evaluate_vars(data, context={}): |
|
@@ -58,8 +58,9 @@ def evaluate_vars(data, context={}): |
|
|
data[key] = evaluate_vars(value, context) |
|
|
elif isinstance(data, six.string_types): |
|
|
for var in var_pattern.findall(data): |
|
|
var = var.strip() |
|
|
if var in context: |
|
|
data = data.replace('{{ %s }}' % var, context[var]) |
|
|
data = re.sub(var_pattern, context[var], data) |
|
|
return data |
|
|
|
|
|
|
|
|
|
@@ -133,3 +133,12 @@ def test_evaluate_vars_list(self): |
|
|
def test_evaluate_vars_list_in_dict(self): |
|
|
val = evaluate_vars({'l': ['{{ a }}', '{{ b }}']}, {'a': '1', 'b': '2'}) |
|
|
self.assertEqual(val, {'l': ['1', '2']}) |
|
|
|
|
|
def test_evaluate_vars_nowhitespace(self): |
|
|
self.assertEqual(evaluate_vars('{{tz}}', {'tz': 'UTC'}), 'UTC') |
|
|
|
|
|
def test_evaluate_vars_doublewhitespace(self): |
|
|
self.assertEqual(evaluate_vars('{{ tz }}', {'tz': 'UTC'}), 'UTC') |
|
|
|
|
|
def test_evaluate_vars_strangewhitespace(self): |
|
|
self.assertEqual(evaluate_vars('{{ tz}}', {'tz': 'UTC'}), 'UTC') |