From bc8b8647aa7d05f582cad2af3d1ec30694c108f8 Mon Sep 17 00:00:00 2001 From: Marcio Mazza Date: Fri, 26 Feb 2016 19:00:18 -0300 Subject: [PATCH] Adiciona leitura de layout a partir de yaml --- crispy_layout_mixin.py | 30 ++++++++++++++++++++++++++++++ requirements/requirements.txt | 1 + test_crispy_layout_mixin.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 test_crispy_layout_mixin.py diff --git a/crispy_layout_mixin.py b/crispy_layout_mixin.py index f9150dda7..1bb2eac49 100644 --- a/crispy_layout_mixin.py +++ b/crispy_layout_mixin.py @@ -1,3 +1,6 @@ +from math import ceil + +import rtyaml from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, Div, Fieldset, Layout, Submit @@ -99,3 +102,30 @@ class CrispyLayoutFormMixin(object): for fieldname, span in row] for row in rows] } for legend, *rows in self.layout] + + +# TODO cache this +def read_yaml_from_file(filename): + with open(filename, 'r') as yamlfile: + return rtyaml.load(yamlfile) + + +def read_layout_from_yaml(filename, key): + # TODO cache this + yaml = read_yaml_from_file(filename) + base = yaml[key] + + def line_to_namespans(line): + split = [cell.split(':') for cell in line.split()] + namespans = [[s[0], int(s[1]) if len(s) > 1 else 0] for s in split] + remaining = 12 - sum(s for n, s in namespans) + nondefined = [ns for ns in namespans if not ns[1]] + while nondefined: + span = ceil(remaining / len(nondefined)) + namespan = nondefined.pop(0) + namespan[1] = span + remaining = remaining - span + return list(map(tuple, namespans)) + + return [(legend, [line_to_namespans(l) for l in lines]) + for legend, lines in base.items()] diff --git a/requirements/requirements.txt b/requirements/requirements.txt index a09461be4..cdf73800b 100644 --- a/requirements/requirements.txt +++ b/requirements/requirements.txt @@ -15,4 +15,5 @@ libsass psycopg2 pytz pyyaml +rtyaml unipath diff --git a/test_crispy_layout_mixin.py b/test_crispy_layout_mixin.py new file mode 100644 index 000000000..d7d422b06 --- /dev/null +++ b/test_crispy_layout_mixin.py @@ -0,0 +1,29 @@ +from crispy_layout_mixin import read_layout_from_yaml + + +def test_read_layout_from_yaml(tmpdir): + + contents = ''' +ModelName: + Cool Legend: + - name:9 place tiny + - field nature:2 + - kind:1 date unit:5 status + More data: + - equalA equalB equalC + - highlander ''' + file = tmpdir.join('zzz.yaml') + file.write(contents) + + expected = [ + ('Cool Legend', [ + [('name', 9), ('place', 2), ('tiny', 1)], + [('field', 10), ('nature', 2)], + [('kind', 1), ('date', 3), ('unit', 5), ('status', 3)], + ]), + ('More data', [ + [('equalA', 4), ('equalB', 4), ('equalC', 4)], + [('highlander', 12)], + ]), + ] + assert read_layout_from_yaml(file.strpath, 'ModelName') == expected