def test_code():
    """Template code block"""
    t = Template('''<%py
        a = 'A'
        b = 'B'
    %>$a$b''')
    assert t.render() == 'AB'
Exemple #2
0
def test_multidict():
    """Template multidict behavior"""
    t = Template('$a|$b')
    assert t.render(MultiDict(dict(
        a=[1, 2],
        b=2
    ))) == '1|2'
Exemple #3
0
def test_code():
    """Template code block"""
    t = Template('''<%py
        a = 'A'
        b = 'B'
    %>$a$b''')
    assert t.render() == 'AB'
def test_multidict():
    """Template multidict behavior"""
    t = Template('$a|$b')
    assert t.render(MultiDict(dict(
        a=[1, 2],
        b=2
    ))) == '1|2'
Exemple #5
0
def test_if():
    """Template if condition"""
    t = Template('<% if idx == 1 %>ONE<% elif idx == 2 %>TWO<% elif '
                 'idx == 3 %>THREE<% else %>OMGWTF<% endif %>')
    assert t.render(idx=0) == 'OMGWTF'
    assert t.render(idx=1) == 'ONE'
    assert t.render(idx=2) == 'TWO'
    assert t.render(idx=3) == 'THREE'
def test_if():
    """Template if condition"""
    t = Template('<% if idx == 1 %>ONE<% elif idx == 2 %>TWO<% elif '
                 'idx == 3 %>THREE<% else %>OMGWTF<% endif %>')
    assert t.render(idx=0) == 'OMGWTF'
    assert t.render(idx=1) == 'ONE'
    assert t.render(idx=2) == 'TWO'
    assert t.render(idx=3) == 'THREE'
Exemple #7
0
 def render_template(self, template=None):
     if template is None:
         template = self.__class__.identifier + '.html'
     context = dict(self.__dict__)
     context.update(url_for=self.url_for, self=self)
     body_tmpl = Template.from_file(path.join(templates, template))
     layout_tmpl = Template.from_file(path.join(templates, 'layout.html'))
     context['body'] = body_tmpl.render(context)
     return layout_tmpl.render(context)
def test_interpolation():
    """Template variable interpolation"""
    t = Template('\n'.join([
        '$string', '${", ".join(string.upper().split(" AND "))}',
        '$string.replace("foo", "bar").title()', '${string}s', '${1, 2, 3}',
        '$string[0:3][::-1]'
    ]))
    assert t.render(string='foo and blah').splitlines() == [
        'foo and blah', 'FOO, BLAH', 'Bar And Blah', 'foo and blahs',
        '(1, 2, 3)', 'oof'
    ]
Exemple #9
0
 def get_template(self, name):
     """Get a template from a given name."""
     filename = path.join(self.search_path, *[p for p in name.split('/')
                                              if p and p[0] != '.'])
     if not path.exists(filename):
         raise TemplateNotFound(name)
     return Template.from_file(filename, self.encoding)
Exemple #10
0
 def get_template(self, name):
     """Get a template from a given name."""
     filename = path.join(self.search_path, *[p for p in name.split('/')
                                              if p and p[0] != '.'])
     if not path.exists(filename):
         raise TemplateNotFound(name)
     return Template.from_file(filename, self.encoding)
Exemple #11
0
 def generate(self, rsp, **kwargs):
     global settings
     kwargs['cfg_line'] = lambda s, d=None: s + ' = ' + repr(settings.get(s, d))
     for filename in ('launch.wsgi', 'app.py', 'settings.py', 'manage.py'):
         with open(in_cwd(filename), 'w') as f:
             # Template strips off trailing whitespace...
             f.write(Template.from_file(in_skeld(filename + '.tmpl')).render(**kwargs) + '\n')
     os.chmod(in_cwd('manage.py'), 0755)
def test_interpolation():
    """Template variable interpolation"""
    t = Template('\n'.join([
        '$string',
        '${", ".join(string.upper().split(" AND "))}',
        '$string.replace("foo", "bar").title()',
        '${string}s',
        '${1, 2, 3}',
        '$string[0:3][::-1]'
    ]))
    assert t.render(string='foo and blah').splitlines() == [
        'foo and blah',
        'FOO, BLAH',
        'Bar And Blah',
        'foo and blahs',
        '(1, 2, 3)',
        'oof'
    ]
Exemple #13
0
def test_from_file_with_filename():
    """Template from_file where file parameter is a filename"""
    fd, filename = tempfile.mkstemp()
    try:
        os.write(fd, "Hello ${you}!")
    finally:
        os.close(fd)
    try:
        t = Template.from_file(filename)
        assert t.render(you="World") == "Hello World!"
    finally:
        os.unlink(filename)
Exemple #14
0
def test_from_file_with_filename():
    """Template from_file where file parameter is a filename"""
    fd, filename = tempfile.mkstemp()
    try:
        os.write(fd, "Hello ${you}!")
    finally:
        os.close(fd)
    try:
        t = Template.from_file(filename)
        assert t.render(you="World") == "Hello World!"
    finally:
        os.unlink(filename)
def test_break():
    """Template brake statement"""
    t = Template('<% for i in xrange(5) %><%py break %>$i<% endfor %>')
    assert t.render() == ''
Exemple #16
0
def test_print():
    """Template print helper"""
    t = Template('1 <%py print "2", %>3')
    t.render() == '1 2 3'
Exemple #17
0
def get_template(filename):
    return Template.from_file(join(dirname(__file__), 'templates', filename))
Exemple #18
0
def test_nl_trim():
    """Template newline trimming"""
    t = Template('<% if 1 %>1<% endif %>\n2')
    assert t.render() == '12'
Exemple #19
0
def test_substitute():
    """Templer rendering responds to substitute as well"""
    t = Template('<% if a %>1<% endif %>\n2')
    assert t.render(a=1) == t.substitute(a=1)
def test_unicode():
    """Template unicode modes"""
    t = Template(u'öäü$szlig')
    assert t.render(szlig='ß') == u'öäüß'
    t = Template(u'öäü$szlig', unicode_mode=False, charset='iso-8859-15')
    assert t.render(szlig='\xdf') == '\xf6\xe4\xfc\xdf'
Exemple #21
0
#Embedded file name: c:\depot\games\branches\release\EVE-TRANQUILITY\carbon\common\lib\werkzeug\testapp.py
import os
import sys
from werkzeug.templates import Template
from werkzeug.wrappers import BaseRequest as Request, BaseResponse as Response
logo = Response(
    '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\n='
    .decode('base64'),
    mimetype='image/png')
TEMPLATE = Template(
    u'\\\n<%py\n    import sys, os\n    from textwrap import wrap\n    import werkzeug\n    from werkzeug.testapp import iter_sys_path\n    try:\n        import pkg_resources\n    except ImportError:\n        eggs = None\n    else:\n        eggs = list(pkg_resources.working_set)\n        eggs.sort(lambda a, b: cmp(a.project_name.lower(),\n                                   b.project_name.lower()))\n    sorted_environ = req.environ.items()\n    sorted_environ.sort(lambda a, b: cmp(str(a[0]).lower(), str(b[0]).lower()))\n%>\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n  "http://www.w3.org/TR/html4/loose.dtd">\n<title>WSGI Information</title>\n<style type="text/css">\n  body       { font-family: \'Lucida Grande\', \'Lucida Sans Unicode\', \'Geneva\',\n               \'Verdana\', sans-serif; background-color: #AFC1C4; Color: #000;\n               text-align: center; margin: 1em; padding: 0; }\n  #logo      { float: right; padding: 10px; }\n  div.box    { text-align: left; width: 45em; padding: 1em; margin: auto;\n               border: 1px solid #aaa; background-color: white; }\n  h1         { color: #11557C; font-size: 2em; margin: 0 0 0.8em 0; }\n  h2         { font-size: 1.4em; margin: 1em 0 0.5em 0; }\n  table      { width: 100%; border-collapse: collapse; border: 1px solid #AFC5C9 }\n  Table th   { background-color: #AFC1C4; color: white; font-size: 0.72em;\n               font-weight: normal; width: 18em; vertical-align: top;\n               padding: 0.5em 0 0.1em 0.5em; }\n  table td   { border: 1px solid #AFC5C9; padding: 0.1em 0 0.1em 0.5em; }\n  code       { font-family: \'Consolas\', \'Monaco\', \'Bitstream Vera Sans Mono\',\n               monospace; font-size: 0.7em; }\n  ul li      { line-height: 1.5em; }\n  ul.path    { font-size: 0.7em; margin: 0; padding: 8px; list-style: none;\n               background: #E9F5F7; border: 1px solid #AFC5C9; }\n  ul.path li { line-height: 1.6em; }\n  li.virtual { color: #999; text-decoration: underline; }\n  li.exp     { background: white; }\n</style>\n<div class="box">\n  <img src="?resource=logo" id="logo" alt="[The Werkzeug Logo]" />\n  <h1>WSGI Information</h1>\n  <p>\n    This page displays all available information about the WSGI server and\n    the underlying Python interpreter.\n  <h2 id="python-interpreter">Python Interpreter</h2>\n  <table>\n    <tr>\n      <th>Python Version</th>\n      <td>${\'<br>\'.join(escape(sys.version).splitlines())}</td>\n    </tr>\n    <tr>\n      <th>Platform</th>\n      <td>$escape(sys.platform) [$escape(os.name)]</td>\n    </tr>\n    <tr>\n      <th>API Version</th>\n      <td>$sys.api_version</td>\n    </tr>\n    <tr>\n      <th>Byteorder</th>\n      <td>$sys.byteorder</td>\n    </tr>\n    <tr>\n      <th>Werkzeug Version</th>\n      <td>$escape(werkzeug.__version__)</td>\n    </tr>\n  </table>\n  <h2 id="wsgi-environment">WSGI Environment</h2>\n  <table>\n  <% for key, value in sorted_environ %>\n    <tr>\n      <th>$escape(str(key))</th>\n      <td><code>${\' \'.join(wrap(escape(repr(value))))}</code></td>\n    </tr>\n  <% endfor %>\n  </table>\n  <% if eggs %>\n  <h2 id="installed-eggs">Installed Eggs</h2>\n  <p>\n    The following python packages were installed on the system as\n    Python eggs:\n  <ul>\n  <% for egg in eggs %>\n    <li>$escape(egg.project_name) <small>[$escape(egg.version)]</small></li>\n  <% endfor %>\n  </ul>\n  <% endif %>\n  <h2 id="sys-path">Package Load Path</h2>\n  <p>\n    The following paths are the current contents of the load path.  The\n    following entries are looked up for Python packages.  Note that not\n    all items in this path are folders.  Gray and underlined items are\n    entries pointing to invalid resources or used by custom import hooks\n    such as the zip importer.\n  <p>\n    Items with a bright background were expanded for display from a relative\n    path.  If you encounter such paths in the output you might want to check\n    your setup as relative paths are usually problematic in multithreaded\n    environments.\n  <ul class="path">\n  <% for item, virtual, expanded in iter_sys_path() %>\n    <%py\n      class_ = []\n      if virtual:\n          class_.append(\'virtual\')\n      if expanded:\n          class_.append(\'exp\')\n      class_ = \' \'.join(class_)\n    %>\n    <li<% if class_ %> class="$class_"<% endif %>>$escape(item)</li>\n  <% endfor %>\n  </ul>\n</div>'
)


def iter_sys_path():
    if os.name == 'posix':

        def strip(x):
            prefix = os.path.expanduser('~')
            if x.startswith(prefix):
                x = '~' + x[len(prefix):]
            return x

    else:
        strip = lambda x: x
    cwd = os.path.abspath(os.getcwd())
    for item in sys.path:
        path = os.path.join(cwd, item or os.path.curdir)
        yield (strip(os.path.normpath(path)), not os.path.isdir(path),
               path != item)
Exemple #22
0
def test_for():
    """Template for loop"""
    t = Template('<% for i in range(10) %>[$i]<% endfor %>')
    assert t.render() == ''.join(['[%s]' % i for i in xrange(10)])
Exemple #23
0
def test_from_file_with_fileobject():
    """Template from_file where file parameter is a file object"""
    t = Template.from_file(sio.StringIO("Hello ${you}!"))
    assert t.render(you="World") == "Hello World!"
Exemple #24
0
def test_unicode():
    """Template unicode modes"""
    t = Template(u'öäü$szlig')
    assert t.render(szlig='ß') == u'öäüß'
    t = Template(u'öäü$szlig', unicode_mode=False, charset='iso-8859-15')
    assert t.render(szlig='\xdf') == '\xf6\xe4\xfc\xdf'
Exemple #25
0
def test_undefined():
    """Template undefined behavior"""
    t = Template('<% for item in seq %>$item<% endfor %>$missing')
    assert t.render() == ''
Exemple #26
0
def test_break():
    """Template brake statement"""
    t = Template('<% for i in xrange(5) %><%py break %>$i<% endfor %>')
    assert t.render() == ''
def test_continue():
    """Template continue statement"""
    t = Template('<% for i in xrange(10) %><% if i % 2 == 0 %>'
                 '<%py continue %><% endif %>$i<% endfor %>')
    assert t.render() == '13579'
def test_print():
    """Template print helper"""
    t = Template('1 <%py print "2", %>3')
    t.render() == '1 2 3'
Exemple #29
0
def test_while():
    """Template while loop"""
    t = Template('<%py idx = 0 %><% while idx < 10 %>x<%py idx += 1 %><% endwhile %>')
    assert t.render() == 'x' * 10
def test_undefined():
    """Template undefined behavior"""
    t = Template('<% for item in seq %>$item<% endfor %>$missing')
    assert t.render() == ''
def test_substitute():
    """Templer rendering responds to substitute as well"""
    t = Template('<% if a %>1<% endif %>\n2')
    assert t.render(a=1) == t.substitute(a=1)
def test_nl_trim():
    """Template newline trimming"""
    t = Template('<% if 1 %>1<% endif %>\n2')
    assert t.render() == '12'
def test_while():
    """Template while loop"""
    t = Template('<%py idx = 0 %><% while idx < 10 %>x<%py idx += 1 %><% endwhile %>')
    assert t.render() == 'x' * 10
Exemple #34
0
    :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
try:
    from simplejson import dumps
except ImportError:

    def dumps(*args):
        raise RuntimeError('simplejson required for jsrouting')


from inspect import getmro
from werkzeug.templates import Template
from werkzeug.routing import NumberConverter
_javascript_routing_template = Template(
    u"<% if name_parts %><% for idx in xrange(0, len(name_parts) - 1) %>if (typeof ${'.'.join(name_parts[:idx + 1])} === 'undefined') ${'.'.join(name_parts[:idx + 1])} = {};\n<% endfor %>${'.'.join(name_parts)} = <% endif %>(function (server_name, script_name, subdomain, url_scheme) {\n    var converters = ${', '.join(converters)};\n    var rules = $rules;\n    function in_array(array, value) {\n        if (array.indexOf != undefined) {\n            return array.indexOf(value) != -1;\n        }\n        for (var i = 0; i < array.length; i++) {\n            if (array[i] == value) {\n                return true;\n            }\n        }\n        return false;\n    }\n    function array_diff(array1, array2) {\n        array1 = array1.slice();\n        for (var i = array1.length-1; i >= 0; i--) {\n            if (in_array(array2, array1[i])) {\n                array1.splice(i, 1);\n            }\n        }\n        return array1;\n    }\n    function split_obj(obj) {\n        var names = [];\n        var values = [];\n        for (var name in obj) {\n            if (typeof(obj[name]) != 'function') {\n                names.push(name);\n                values.push(obj[name]);\n            }\n        }\n        return {names: names, values: values, original: obj};\n    }\n    function suitable(rule, args) {\n        var default_args = split_obj(rule.defaults || {});\n        var diff_arg_names = array_diff(rule.arguments, default_args.names);\n\n        for (var i = 0; i < diff_arg_names.length; i++) {\n            if (!in_array(args.names, diff_arg_names[i])) {\n                return false;\n            }\n        }\n\n        if (array_diff(rule.arguments, args.names).length == 0) {\n            if (rule.defaults == null) {\n                return true;\n            }\n            for (var i = 0; i < default_args.names.length; i++) {\n                var key = default_args.names[i];\n                var value = default_args.values[i];\n                if (value != args.original[key]) {\n                    return false;\n                }\n            }\n        }\n\n        return true;\n    }\n    function build(rule, args) {\n        var tmp = [];\n        var processed = rule.arguments.slice();\n        for (var i = 0; i < rule.trace.length; i++) {\n            var part = rule.trace[i];\n            if (part.is_dynamic) {\n                var converter = converters[rule.converters[part.data]];\n                var data = converter(args.original[part.data]);\n                if (data == null) {\n                    return null;\n                }\n                tmp.push(data);\n                processed.push(part.name);\n            } else {\n                tmp.push(part.data);\n            }\n        }\n        tmp = tmp.join('');\n        var pipe = tmp.indexOf('|');\n        var subdomain = tmp.substring(0, pipe);\n        var url = tmp.substring(pipe+1);\n\n        var unprocessed = array_diff(args.names, processed);\n        var first_query_var = true;\n        for (var i = 0; i < unprocessed.length; i++) {\n            if (first_query_var) {\n                url += '?';\n            } else {\n                url += '&';\n            }\n            first_query_var = false;\n            url += encodeURIComponent(unprocessed[i]);\n            url += '=';\n            url += encodeURIComponent(args.original[unprocessed[i]]);\n        }\n        return {subdomain: subdomain, path: url};\n    }\n    function lstrip(s, c) {\n        while (s && s.substring(0, 1) == c) {\n            s = s.substring(1);\n        }\n        return s;\n    }\n    function rstrip(s, c) {\n        while (s && s.substring(s.length-1, s.length) == c) {\n            s = s.substring(0, s.length-1);\n        }\n        return s;\n    }\n    return function(endpoint, args, force_external) {\n        args = split_obj(args);\n        var rv = null;\n        for (var i = 0; i < rules.length; i++) {\n            var rule = rules[i];\n            if (rule.endpoint != endpoint) continue;\n            if (suitable(rule, args)) {\n                rv = build(rule, args);\n                if (rv != null) {\n                    break;\n                }\n            }\n        }\n        if (rv == null) {\n            return null;\n        }\n        if (!force_external && rv.subdomain == subdomain) {\n            return rstrip(script_name, '/') + '/' + lstrip(rv.path, '/');\n        } else {\n            return url_scheme + '://'\n                   + (rv.subdomain ? rv.subdomain + '.' : '')\n                   + server_name + rstrip(script_name, '/')\n                   + '/' + lstrip(rv.path, '/');\n        }\n    };\n})"
)


def generate_map(map, name='url_map'):
    """
    Generates a JavaScript function containing the rules defined in
    this map, to be used with a MapAdapter's generate_javascript
    method.  If you don't pass a name the returned JavaScript code is
    an expression that returns a function.  Otherwise it's a standalone
    script that assigns the function with that name.  Dotted names are
    resolved (so you an use a name like 'obj.url_for')
    
    In order to use JavaScript generation, simplejson must be installed.
    
    Note that using this feature will expose the rules
def test_for():
    """Template for loop"""
    t = Template('<% for i in range(10) %>[$i]<% endfor %>')
    assert t.render() == ''.join(['[%s]' % i for i in xrange(10)])
Exemple #36
0
def get_template(name):
    return Template.from_file(join(dirname(__file__), 'shared', name),
                              unicode_mode=False,
                              errors='ignore')
Exemple #37
0
def test_from_file_with_fileobject():
    """Template from_file where file parameter is a file object"""
    t = Template.from_file(sio.StringIO("Hello ${you}!"))
    assert t.render(you="World") == "Hello World!"
Exemple #38
0
 def generate(self, rsp, **kwargs):
     template_data = self.req.environ.copy()
     template_data.update(kwargs)
     rsp.data = Template.from_file(self.filename).render(template_data)
Exemple #39
0
def test_continue():
    """Template continue statement"""
    t = Template('<% for i in xrange(10) %><% if i % 2 == 0 %>'
                 '<%py continue %><% endif %>$i<% endfor %>')
    assert t.render() == '13579'
Exemple #40
0
def get_template(name):
    return Template.from_file(join(dirname(__file__), 'shared', name), unicode_mode=False, errors='ignore')
Exemple #41
0
 def render_template(self, name, values):
     return Template.from_file(path.join(TEMPLATES, name)).render(values)