Source

wheezy.template / demos / bigtable / bigtable.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 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
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

"""
"""

import sys

try:
    from wheezy.html.utils import escape_html as escape
except ImportError:
    import cgi
    escape = cgi.escape

PY3 = sys.version_info[0] >= 3
s = PY3 and str or unicode

ctx = {
    'table': [dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10)
              for x in range(1000)]
}


# region: python list append

if PY3:
    def test_list_append():
        b = []
        w = b.append
        table = ctx['table']
        w('<table>\n')
        for row in table:
            w('<tr>\n')
            for key, value in row.items():
                w('<td>')
                w(escape(key))
                w('</td><td>')
                w(str(value))
                w('</td>\n')
            w('</tr>\n')
        w('</table>')
        return ''.join(b)
else:
    def test_list_append():  # noqa
        b = []
        w = b.append
        table = ctx['table']
        w(u'<table>\n')
        for row in table:
            w(u'<tr>\n')
            for key, value in row.items():
                w(u'<td>')
                w(escape(key))
                w(u'</td><td>')
                w(unicode(value))
                w(u'</td>\n')
            w(u'</tr>\n')
        w(u'</table>')
        return ''.join(b)


# region: python list extend

if PY3:
    def test_list_extend():
        b = []
        e = b.extend
        table = ctx['table']
        e(('<table>\n',))
        for row in table:
            e(('<tr>\n',))
            for key, value in row.items():
                e(('<td>',
                   escape(key),
                   '</td><td>',
                   str(value),
                   '</td>\n'))
            e(('</tr>\n',))
        e(('</table>',))
        return ''.join(b)
else:
    def test_list_extend():  # noqa
        b = []
        e = b.extend
        table = ctx['table']
        e((u'<table>\n',))
        for row in table:
            e((u'<tr>\n',))
            for key, value in row.items():
                e((u'<td>',
                   escape(key),
                   u'</td><td>',
                   unicode(value),
                   u'</td>\n'))
            e((u'</tr>\n',))
        e((u'</table>',))
        return ''.join(b)


# region: wheezy.template

try:
    from wheezy.template.engine import Engine
    from wheezy.template.loader import DictLoader
    from wheezy.template.ext.core import CoreExtension
except ImportError:
    test_wheezy_template = None
else:
    engine = Engine(loader=DictLoader({'x': s("""\
@require(table)
<table>
    @for row in table:
    <tr>
        @for key, value in row.items():
        <td>@key!h</td><td>@value!s</td>
        @end
    </tr>
    @end
</table>
""")}), extensions=[CoreExtension()])
    engine.global_vars.update({'h': escape})
    wheezy_template = engine.get_template('x')

    def test_wheezy_template():
        return wheezy_template.render(ctx)


# region: Jinja2

try:
    from jinja2 import Environment
except ImportError:
    test_jinja2 = None
else:
    jinja2_template = Environment().from_string(s("""\
<table>
    {% for row in table: %}
    <tr>
        {% for key, value in row.items(): %}
        <td>{{ key | e }}</td><td>{{ value }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>
"""))

    def test_jinja2():
        return jinja2_template.render(ctx)


# region: tornado

try:
    from tornado.template import Template
except ImportError:
    test_tornado = None
else:
    tornado_template = Template(s("""\
<table>
    {% for row in table %}
    <tr>
        {% for key, value in row.items() %}
        <td>{{ key }}</td><td>{{ value }}</td>
        {% end %}
    </tr>
    {% end %}
</table>
"""))

    def test_tornado():
        return tornado_template.generate(**ctx).decode('utf8')


# region: mako

try:
    from mako.template import Template
except ImportError:
    test_mako = None
else:
    mako_template = Template(s("""\
<table>
    % for row in table:
    <tr>
        % for key, value in row.items():
        <td>${ key | h }</td><td>${ value }</td>
        % endfor
    </tr>
    % endfor
</table>
"""))

    def test_mako():
        return mako_template.render(**ctx)


# region: tenjin

try:
    import tenjin
except ImportError:
    test_tenjin = None
else:
    try:
        import webext
        helpers = {
            'to_str': webext.to_str,
            'escape': webext.escape_html
        }
    except ImportError:
        helpers = {
            'to_str': tenjin.helpers.to_str,
            'escape': tenjin.helpers.escape
        }
    tenjin_template = tenjin.Template(encoding='utf8')
    tenjin_template.convert(s("""\
<table>
    <?py for row in table: ?>
    <tr>
        <?py for key, value in row.items(): ?>
        <td>${ key }</td><td>#{ value }</td>
        <?py #end ?>
    </tr>
    <?py #end ?>
</table>
"""))

    def test_tenjin():
        return tenjin_template.render(ctx, helpers)


# region: web2py

try:
    import cStringIO
    from gluon.html import xmlescape
    from gluon.template import get_parsed
except ImportError:
    test_web2py = None
else:
    # see gluon.globals.Response
    class DummyResponse(object):
        def __init__(self):
            self.body = cStringIO.StringIO()

        def write(self, data, escape=True):
            if not escape:
                self.body.write(str(data))
            else:
                self.body.write(xmlescape(data))

    web2py_template = compile(get_parsed(s("""\
<table>
    {{ for row in table: }}
    <tr>
        {{ for key, value in row.items(): }}
        <td>{{ =key }}</td><td>{{ =value }}</td>
        {{ pass }}
    </tr>
    {{ pass }}
</table>
""")), '', 'exec')

    def test_web2py():
        response = DummyResponse()
        exec(web2py_template, {}, dict(response=response, **ctx))
        return response.body.getvalue().decode('utf8')


# region: django

try:
    from django.conf import settings
    settings.configure()
    from django.template import Template
    from django.template import Context
except ImportError:
    test_django = None
else:
    django_template = Template(s("""\
<table>
    {% for row in table %}
    <tr>
        {% for key, value in row.items %}
        <td>{{ key }}</td><td>{{ value }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>
"""))

    def test_django():
        return django_template.render(Context(ctx))

# region: chameleon

try:
    from chameleon.zpt.template import PageTemplate
except ImportError:
    test_chameleon = None
else:
    chameleon_template = PageTemplate(s("""\
<table>
    <tr tal:repeat="row table">
        <i tal:omit-tag="" tal:repeat="key row">
        <td>${key}</td><td>${row[key]}</td>
        </i>
    </tr>
</table>
"""))

    def test_chameleon():
        return chameleon_template.render(**ctx)

# region: cheetah

try:
    from Cheetah.Template import Template
except ImportError:
    test_cheetah = None
else:
    cheetah_ctx = {}
    cheetah_template = Template(s("""\
#import cgi
<table>
    #for $row in $table
    <tr>
        #for $key, $value in $row.items
        <td>$cgi.escape($key)</td><td>$value</td>
        #end for
    </tr>
    #end for
</table>
"""), searchList=[cheetah_ctx])

    def test_cheetah():
        cheetah_ctx.update(ctx)
        output = cheetah_template.respond()
        cheetah_ctx.clear()
        return output

# region: spitfire

try:
    import spitfire
    import spitfire.compiler.util
except ImportError:
    test_spitfire = None
else:
    spitfire_template = spitfire.compiler.util.load_template(s("""\
#from cgi import escape
<table>
    #for $row in $table
    <tr>
        #for $key, $value in $row.items()
        <td>${key|filter=escape}</td><td>$value</td>
        #end for
    </tr>
    #end for
</table>
"""), 'spitfire_template', spitfire.compiler.analyzer.o3_options, {
        'enable_filters': True})

    def test_spitfire():
        return spitfire_template(search_list=[ctx]).main()

# region: qpy

try:
    from qpy import join_xml
    from qpy import xml
    from qpy import xml_quote
except ImportError:
    test_qpy_list_append = None
else:
    if PY3:
        def test_qpy_list_append():
            b = []
            w = b.append
            table = ctx['table']
            w(xml('<table>\n'))
            for row in table:
                w(xml('<tr>\n'))
                for key, value in row.items():
                    w(xml('<td>'))
                    w(xml_quote(key))
                    w(xml('</td><td>'))
                    w(value)
                    w(xml('</td>\n'))
                w(xml('</tr>\n'))
            w(xml('</table>'))
            return join_xml(b)
    else:
        def test_qpy_list_append():
            b = []
            w = b.append
            table = ctx['table']
            w(xml(u'<table>\n'))
            for row in table:
                w(xml(u'<tr>\n'))
                for key, value in row.items():
                    w(xml(u'<td>'))
                    w(xml_quote(key))
                    w(xml(u'</td><td>'))
                    w(value)
                    w(xml(u'</td>\n'))
                w(xml(u'</tr>\n'))
            w(xml(u'</table>'))
            return join_xml(b)

# region: bottle

try:
    from bottle import SimpleTemplate
except ImportError:
    test_bottle = None
else:
    bottle_template = SimpleTemplate(s("""\
<table>
    % for row in table:
    <tr>
        % for key, value in row.items():
        <td>{{key}}</td><td>{{!value}}</td>
        % end
    </tr>
    % end
</table>
"""))

    def test_bottle():
        return bottle_template.render(**ctx)


def run(number=100):
    import profile
    from timeit import Timer
    from pstats import Stats
    names = globals().keys()
    names = sorted([(name, globals()[name])
                    for name in names if name.startswith('test_')])
    print("                     msec    rps  tcalls  funcs")
    for name, test in names:
        if test:
            assert isinstance(test(), s)
            t = Timer(setup='from __main__ import %s as t' % name,
                      stmt='t()')
            t = t.timeit(number=number)
            st = Stats(profile.Profile().runctx(
                'test()', globals(), locals()))
            print('%-17s %7.2f %6.2f %7d %6d' % (name[5:],
                                                 1000 * t / number,
                                                 number / t,
                                                 st.total_calls,
                                                 len(st.stats)))
        else:
            print('%-26s not installed' % name[5:])


if __name__ == '__main__':
    run()