json.py 2.93 KB
Newer Older
1
from jinja2 import Environment, BaseLoader, Template
2 3
from textwrap import dedent

4 5
from . import directives

6 7 8 9
# set locale in order to have french date for output string
import locale
locale.setlocale(locale.LC_TIME, "fr_FR.UTF-8")

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
def jinja2_splitlines(s):
    """ Split string by lines """
    return s.splitlines()

def jinja2_rst_options(options):
    """ Return lines of rst representation of given options """
    for key, value in options.items():
        yield f":{key}: {list_head(value)}"
        for line in list_tail(value):
            yield f"    {line}"

def list_head(l):
    """ Return first element of a list, itself if it is not a list """
    if isinstance(l, list):
        return l[0] if len(l) > 0 else None
    else:
        return l

def list_tail(l):
    """ Return elements other than the first of a list, empty list if it is not a list """
    if isinstance(l, list):
        return l[1:]
    else:
        return []

def filter_options(directive, options):
    """ Filters keys of given dict depending on option_sep of the directive """
    return dict(((key, value) for key, value in options.items() if key.lower() in directive.option_spec))

def build_meso(meso):
    """ Filters and formats attributes of a meso depending on the Meso directive """
    return {
        'name': meso['name'],
        'options': filter_options(directives.Meso, meso),
        'content': meso['fullDescription'],
    }

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
def json_mesolist_to_rst(url):
    """
    Parses a json file containing the list of mesocenters and returns an rst like describing them.

    Parameters
    ----------
    url: url
        url of the json file

    Returns
    -------
    string: the list of the mesocenters in a rst format

    """
    from datetime import datetime, date, time
    import maya
    import collections
    from urllib.request import urlopen
    import json

    response = urlopen(url).read()
    data = json.loads(response.decode('utf-8'))

70 71 72
    meso_list = {}
    for meso in data['mesocentreList']:
        region = meso['location']
73 74 75 76 77
        meso_list.setdefault(region, []).append(build_meso(meso))

    return _json_mesolist_rst_template.render(meso_by_region=meso_list)


78
# Pre-loading Jinja2 template as static variable
79 80 81 82 83 84 85 86
_json_mesolist_rst_env = Environment(loader=BaseLoader)
_json_mesolist_rst_env.filters.update({
    'splitlines': jinja2_splitlines,
    'rst_options': jinja2_rst_options,
})
_json_mesolist_rst_template = _json_mesolist_rst_env.from_string(dedent("""
            {% for region, mesolist in meso_by_region.items() -%}
            .. region:: {{ region }}
87

88 89 90 91
                {% for meso in mesolist %}
                .. meso:: {{ meso['name'] }}
                    {%- for l in meso["options"] | rst_options %}
                    {{ l }}
92
                    {%- endfor %}
93 94 95

                    {% for l in meso["content"] | splitlines %}
                    {{ l }}
96
                    {%- endfor %}
97 98 99 100 101

                {%- endfor %}

            {% endfor %}
"""))