Esempio n. 1
0
def from_template(template, destination, values, jinja2=False):
    """
    Generate a `destination` file from a `template` file filled with `values`, method: string.format or jinja2!

    **Example usage**

    >>> open('config.template', 'w', 'utf-8').write('{{username={user}; password={pass}}}')

    The behavior when all keys are given (and even more):

    >>> from_template('config.template', 'config', {'user': '******', 'pass': '******', 'other': 10})
    >>> print(open('config', 'r', 'utf-8').read())
    {username=tabby; password=miaow}

    The behavior if a value for a key is missing:

    >>> from_template('config.template', 'config', {'pass': '******', 'other': 10})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    KeyError: ...'user'
    >>> print(open('config', 'r', 'utf-8').read())
    <BLANKLINE>

    >>> os.remove('config.template')
    >>> os.remove('config')
    """
    with open(template, 'r', 'utf-8') as template_file:
        with open(destination, 'w', 'utf-8') as destination_file:
            content = template_file.read()
            if jinja2:
                from jinja2 import Template
                content = Template(content).render(**values)
            else:
                content = content.format(**values)
            destination_file.write(content)
Esempio n. 2
0
def from_template(template, destination, values, jinja2=False):
    """
    Generate a `destination` file from a `template` file filled with `values`, method: string.format or jinja2!

    **Example usage**

    >>> open('config.template', 'w', 'utf-8').write('{{username={user}; password={pass}}}')

    The behavior when all keys are given (and even more):

    >>> from_template('config.template', 'config', {'user': '******', 'pass': '******', 'other': 10})
    >>> print(open('config', 'r', 'utf-8').read())
    {username=tabby; password=miaow}

    The behavior if a value for a key is missing:

    >>> from_template('config.template', 'config', {'pass': '******', 'other': 10})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    KeyError: ...'user'
    >>> print(open('config', 'r', 'utf-8').read())
    <BLANKLINE>

    >>> os.remove('config.template')
    >>> os.remove('config')
    """
    with open(template, 'r', 'utf-8') as template_file:
        with open(destination, 'w', 'utf-8') as destination_file:
            content = template_file.read()
            if jinja2:
                from jinja2 import Template
                content = Template(content).render(**values)
            else:
                content = content.format(**values)
            destination_file.write(content)
Esempio n. 3
0
def from_template(template, destination, values, is_file=True, jinja2=False, pre_func=None,
                  post_func=None):
    """
    Return a `template` rendered with `values` using string.format or jinja2 as the template engine.

    * Set `destination` to a filename to store the output, to a Falsy value to skip this feature.
    * Set `is_file` to False to use value of `template` as the content and not a filename to read.
    * Set `{pre,post}_func` to a callback function with the signature f(content, values, jinja2)

    **Example usage**

    >>> template = '{{username={user}; password={pass}}}'
    >>> values = {'user': '******', 'pass': '******', 'other': 10}
    >>> open('config.template', 'w', 'utf-8').write(template)

    The behavior when all keys are given (and even more):

    >>> _ = from_template('config.template', 'config', values)
    >>> print(open('config', 'r', 'utf-8').read())
    {username=tabby; password=miaow}

    >>> _ = from_template(template, 'config', values, is_file=False)
    >>> print(open('config', 'r', 'utf-8').read())
    {username=tabby; password=miaow}

    >>> def post_func(content, values, jinja2):
    ...     return content.replace('tabby', 'tikky')
    >>> print(from_template(template, None, values, is_file=False, post_func=post_func))
    {username=tikky; password=miaow}

    The behavior if a value for a key is missing:

    >>> from_template('config.template', 'config', {'pass': '******', 'other': 10})  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    KeyError: ...'user'
    >>> print(open('config', 'r', 'utf-8').read())
    {username=tabby; password=miaow}

    >>> os.remove('config.template')
    >>> os.remove('config')
    """
    content = open(template, 'r', 'utf-8').read() if is_file else template
    if pre_func:
        content = pre_func(content, values=values, jinja2=jinja2)
    if jinja2:
        from jinja2 import Template
        content = Template(content).render(**values)
    else:
        content = content.format(**values)
    if post_func:
        content = post_func(content, values=values, jinja2=jinja2)
    if destination:
        with open(destination, 'w', 'utf-8') as f:
            f.write(content)
    return content
Esempio n. 4
0
 def get_delete_from(self,
                     condition=None,
                     params=None,
                     using=None,
                     suffix=''):
     r = Template("""
         DELETE FROM {{ t.full_table_name(quoted=True, with_prefix=True, suffix=suffix) }}
         {%- if using %}
         USING {{ using }} AS u
         {%- endif %}
         {%- if condition %}
         WHERE {{ condition }}
         {%- endif %};
     """).render(t=self.table,
                 condition=condition,
                 using=using,
                 suffix=suffix)
     if params:
         return r.format(**(params or {}))
     return r
Esempio n. 5
0
import pandas as pd
from . import frameup

dirname = os.path.dirname(os.path.realpath(__file__))

try:
    from jinja2 import Template
    templ = os.path.join(dirname, 'templates/example.j2.html')
    print(f'Using Jinja2 template: {templ}')
    template = Template(open(templ).read())
    render = lambda **kw: template.render(**kw)
except ModuleNotFoundError:
    templ = os.path.join(dirname, 'templates/example.html')
    print(f'Using python template: {templ}')
    template = open(templ).read()
    render = lambda **kw: template.format(**kw)

HOST = 'localhost'
PORT = 8000

STATUS_OK = f'{HTTPStatus.OK} {HTTPStatus.OK.phrase}'


class Server(object):
    def serve(self, environ, start_response):
        data = self.df.frameup.data(environ.get('QUERY_STRING', ''),
                                    justify='center',
                                    index_names=False,
                                    classes='pure-table-striped')
        if 'text/html' in environ['HTTP_ACCEPT']:
            content_type = 'text/html; charset=utf-8'