Skip to content
Myr

python 3 port: automated changes by a slightly modified python-modernize

Before adoption: this commit came in with the history the project adopted, so no landing records it.

(replacing unicode with six.text_type, but not replacing u"" by six.u(""))

authored by Thomas Waldmann · committed by Thomas Waldmann · parent 846bdc1 · Browse files · 29 files+171 added−131 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

29 files+171 added−131 removed

  • other:+171 added−131 removed

29 files+171 added−131 removed

modified:jinja2/_markupsafe/__init__.py+8 added-5 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12from itertools import imap13import six14from six.moves import map15from six.moves import zip161718__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']19
58 unmodified lines
78 return self7980 def __add__(self, other):81 if hasattr(other, '__html__') or isinstance(other, basestring):79 return self.__class__(unicode(self) + unicode(escape(other)))82 return self.__class__(six.text_type(self) + six.text_type(escape(other)))83 return NotImplemented8485 def __radd__(self, other):86 if hasattr(other, '__html__') or isinstance(other, basestring):84 return self.__class__(unicode(escape(other)) + unicode(self))87 return self.__class__(six.text_type(escape(other)) + six.text_type(self))88 return NotImplemented8990 def __mul__(self, num):91 if isinstance(num, (int, long)):
49 unmodified lines
141 return unichr(int(name[1:]))142 except ValueError:143 pass144 return u''142 return _entity_re.sub(handle_match, unicode(self))145 return _entity_re.sub(handle_match, six.text_type(self))146147 def striptags(self):148 r"""Unescape markup into an unicode string and strip all tags. This149 also resolves known HTML4 and XHTML entities. Whitespace is
19 unmodified lines
169 def make_wrapper(name):170 orig = getattr(unicode, name)171 def func(self, *args, **kwargs):172 args = _escape_argspec(list(args), enumerate(args))170 _escape_argspec(kwargs, kwargs.iteritems())173 _escape_argspec(kwargs, six.iteritems(kwargs))174 return self.__class__(orig(self, *args, **kwargs))175 func.__name__ = orig.__name__176 func.__doc__ = orig.__doc__177 return func
35 unmodified lines
213 self.obj = obj214215 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])216 __str__ = lambda s: str(escape(s.obj))214 __unicode__ = lambda s: unicode(escape(s.obj))217 __unicode__ = lambda s: six.text_type(escape(s.obj))218 __repr__ = lambda s: str(escape(repr(s.obj)))219 __int__ = lambda s: int(s.obj)220 __float__ = lambda s: float(s.obj)221
7 unmodified lines
modified:jinja2/_markupsafe/_bundle.py+2 added-1 removed
8 unmodified lines
910 :copyright: Copyright 2010 by the Jinja team, see AUTHORS.11 :license: BSD, see LICENSE for details.12"""13from __future__ import print_function14import sys15import os16import re17
7 unmodified lines
252627def main():28 if len(sys.argv) != 2:28 print 'error: only argument is path to markupsafe'29 print('error: only argument is path to markupsafe')30 sys.exit(1)31 basedir = os.path.dirname(__file__)32 markupdir = sys.argv[1]33 for filename in os.listdir(markupdir):
17 unmodified lines
modified:jinja2/_markupsafe/_native.py+3 added-2 removed
7 unmodified lines
8 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja2._markupsafe import Markup12import six131415def escape(s):16 """Convert the characters &, <, >, ' and " in string s to HTML-safe
1 unmodified line
18 such characters in HTML. Marks return value as markup string.19 """20 if hasattr(s, '__html__'):21 return s.__html__()21 return Markup(unicode(s)22 return Markup(six.text_type(s)23 .replace('&', '&amp;')24 .replace('>', '&gt;')25 .replace('<', '&lt;')26 .replace("'", '&#39;')
14 unmodified lines
41 """Make a string unicode if it isn't already. That way a markup42 string is not converted back to unicode.43 """44 if not isinstance(s, unicode):44 s = unicode(s)45 s = six.text_type(s)46 return s
modified:jinja2/_markupsafe/tests.py+4 added-3 removed
1import gc2import unittest3from jinja2._markupsafe import Markup, escape, escape_silent4import six567class MarkupTestCase(unittest.TestCase):89 def test_markup_operations(self):10 # adding two strings should escape the unsafe one11 unsafe = '<script type="application/x-some-script">alert("foo");</script>'12 safe = Markup('<em>username</em>')12 assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)13 assert unsafe + safe == six.text_type(escape(unsafe)) + six.text_type(safe)1415 # string interpolations are safe to use too16 assert Markup('<em>%s</em>') % '<bad user>' == \17 '<em>&lt;bad user&gt;</em>'
37 unmodified lines
55class MarkupLeakTestCase(unittest.TestCase):5657 def test_markup_leaks(self):58 counts = set()58 for count in xrange(20):59 for item in xrange(1000):59 for count in range(20):60 for item in range(1000):61 escape("foo")62 escape("<foo>")63 escape(u"foo")64 escape(u"<foo>")
17 unmodified lines
modified:jinja2/testsuite/__init__.py+1 added-1 removed
57 unmodified lines
5859 def assert_traceback_matches(self, callback, expected_tb):60 try:61 callback()62 except Exception, e:62 except Exception as e:63 tb = format_exception(*sys.exc_info())64 if re.search(expected_tb.strip(), ''.join(tb)) is None:65 raise self.fail('Traceback did not match:\n\n%s\nexpected:\n%s'66 % (''.join(tb), expected_tb))
29 unmodified lines
modified:jinja2/testsuite/api.py+17 added-16 removed
14 unmodified lines
15from jinja2 import Environment, Undefined, DebugUndefined, \16 StrictUndefined, UndefinedError, meta, \17 is_undefined, Template, DictLoader18from jinja2.utils import Cycler19import six2021env = Environment()2223
26 unmodified lines
50 items = 1, 2, 351 c = Cycler(*items)52 for item in items + items:53 assert c.current == item53 assert c.next() == item54 c.next()54 assert six.advance_iterator(c) == item55 six.advance_iterator(c)56 assert c.current == 257 c.reset()58 assert c.current == 159
47 unmodified lines
107108 def test_find_refererenced_templates(self):109 ast = env.parse('{% extends "layout.html" %}{% include helper %}')110 i = meta.find_referenced_templates(ast)110 assert i.next() == 'layout.html'111 assert i.next() is None111 assert six.advance_iterator(i) == 'layout.html'112 assert six.advance_iterator(i) is None113 assert list(i) == []114115 ast = env.parse('{% extends "layout.html" %}'116 '{% from "test.html" import a, b as c %}'
24 unmodified lines
141142 def test_basic_streaming(self):143 tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "144 "}} - {{ item }}</li>{%- endfor %}</ul>")144 stream = tmpl.stream(seq=range(4))145 self.assert_equal(stream.next(), '<ul>')146 self.assert_equal(stream.next(), '<li>1 - 0</li>')147 self.assert_equal(stream.next(), '<li>2 - 1</li>')148 self.assert_equal(stream.next(), '<li>3 - 2</li>')149 self.assert_equal(stream.next(), '<li>4 - 3</li>')150 self.assert_equal(stream.next(), '</ul>')145 stream = tmpl.stream(seq=list(range(4)))146 self.assert_equal(six.advance_iterator(stream), '<ul>')147 self.assert_equal(six.advance_iterator(stream), '<li>1 - 0</li>')148 self.assert_equal(six.advance_iterator(stream), '<li>2 - 1</li>')149 self.assert_equal(six.advance_iterator(stream), '<li>3 - 2</li>')150 self.assert_equal(six.advance_iterator(stream), '<li>4 - 3</li>')151 self.assert_equal(six.advance_iterator(stream), '</ul>')152153 def test_buffered_streaming(self):154 tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "155 "}} - {{ item }}</li>{%- endfor %}</ul>")155 stream = tmpl.stream(seq=range(4))156 stream = tmpl.stream(seq=list(range(4)))157 stream.enable_buffering(size=3)157 self.assert_equal(stream.next(), u'<ul><li>1 - 0</li><li>2 - 1</li>')158 self.assert_equal(stream.next(), u'<li>3 - 2</li><li>4 - 3</li></ul>')158 self.assert_equal(six.advance_iterator(stream), u'<ul><li>1 - 0</li><li>2 - 1</li>')159 self.assert_equal(six.advance_iterator(stream), u'<li>3 - 2</li><li>4 - 3</li></ul>')160161 def test_streaming_behavior(self):162 tmpl = env.from_string("")163 stream = tmpl.stream()
58 unmodified lines
222223 def test_none_gives_proper_error(self):224 try:225 Environment().getattr(None, 'split')()225 except UndefinedError, e:226 except UndefinedError as e:227 assert e.message == "'None' has no attribute 'split'"228 else:229 assert False, 'expected exception'230231 def test_object_repr(self):232 try:233 Undefined(obj=42, name='upper')()233 except UndefinedError, e:234 except UndefinedError as e:235 assert e.message == "'int object' has no attribute 'upper'"236 else:237 assert False, 'expected exception'238
8 unmodified lines
modified:jinja2/testsuite/core_tags.py+3 added-3 removed
20 unmodified lines
21class ForLoopTestCase(JinjaTestCase):2223 def test_simple(self):24 tmpl = env.from_string('{% for item in seq %}{{ item }}{% endfor %}')25 assert tmpl.render(seq=range(10)) == '0123456789'25 assert tmpl.render(seq=list(range(10))) == '0123456789'2627 def test_else(self):28 tmpl = env.from_string('{% for item in seq %}XXX{% else %}...{% endfor %}')29 assert tmpl.render() == '...'
24 unmodified lines
54 def test_cycling(self):55 tmpl = env.from_string('''{% for item in seq %}{{56 loop.cycle('<1>', '<2>') }}{% endfor %}{%57 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')58 output = tmpl.render(seq=range(4), through=('<1>', '<2>'))58 output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))59 assert output == '<1><2>' * 46061 def test_scope(self):62 tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')63 output = tmpl.render(seq=range(10))63 output = tmpl.render(seq=list(range(10)))64 assert not output6566 def test_varlen(self):67 def inner():
218 unmodified lines
modified:jinja2/testsuite/ext.py+2 added-1 removed
16 unmodified lines
17from jinja2.exceptions import TemplateAssertionError18from jinja2.ext import Extension19from jinja2.lexer import Token, count_newlines20from jinja2.utils import next21import six2223# 2.x / 3.x24try:25 from io import BytesIO
196 unmodified lines
222 def test_rebinding(self):223 original = Environment(extensions=[TestExtension])224 overlay = original.overlay()225 for env in original, overlay:225 for ext in env.extensions.itervalues():226 for ext in six.itervalues(env.extensions):227 assert ext.environment is env228229 def test_preprocessor_extension(self):230 env = Environment(extensions=[PreprocessorExtension])
226 unmodified lines
modified:jinja2/testsuite/filters.py+11 added-8 removed
10 unmodified lines
11import unittest12from jinja2.testsuite import JinjaTestCase1314from jinja2 import Markup, Environment15import six16from six.moves import map17from six.moves import zip1819env = Environment()2021
27 unmodified lines
4950 def test_batch(self):51 tmpl = env.from_string("{{ foo|batch(3)|list }}|"52 "{{ foo|batch(3, 'X')|list }}")50 out = tmpl.render(foo=range(10))53 out = tmpl.render(foo=list(range(10)))54 assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"55 "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")5657 def test_slice(self):58 tmpl = env.from_string('{{ foo|slice(3)|list }}|'59 '{{ foo|slice(3, "X")|list }}')57 out = tmpl.render(foo=range(10))60 out = tmpl.render(foo=list(range(10)))61 assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"62 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")6364 def test_escape(self):
46 unmodified lines
111112113 def test_first(self):114 tmpl = env.from_string('{{ foo|first }}')112 out = tmpl.render(foo=range(10))115 out = tmpl.render(foo=list(range(10)))116 assert out == '0'117118 def test_float(self):119 tmpl = env.from_string('{{ "42"|float }}|'
37 unmodified lines
157 assert tmpl.render(users=map(User, ['foo', 'bar'])) == 'foo, bar'158159 def test_last(self):160 tmpl = env.from_string('''{{ foo|last }}''')158 out = tmpl.render(foo=range(10))161 out = tmpl.render(foo=list(range(10)))162 assert out == '9'163164 def test_length(self):165 tmpl = env.from_string('''{{ "hello world"|length }}''')
7 unmodified lines
173174 def test_pprint(self):175 from pprint import pformat176 tmpl = env.from_string('''{{ data|pprint }}''')174 data = range(1000)177 data = list(range(1000))178 assert tmpl.render(data=data) == pformat(data)179180 def test_random(self):181 tmpl = env.from_string('''{{ seq|random }}''')179 seq = range(100)182 seq = list(range(100))183 for _ in range(10):184 assert int(tmpl.render(seq=seq)) in seq185186 def test_reverse(self):
3 unmodified lines
190191 def test_string(self):192 x = [1, 2, 3, 4, 5]193 tmpl = env.from_string('''{{ obj|string }}''')191 assert tmpl.render(obj=x) == unicode(x)194 assert tmpl.render(obj=x) == six.text_type(x)195196 def test_title(self):197 tmpl = env.from_string('''{{ "foo bar"|title }}''')198 assert tmpl.render() == "Foo Bar"
100 unmodified lines
299 class Magic(object):300 def __init__(self, value):301 self.value = value302 def __unicode__(self):300 return unicode(self.value)303 return six.text_type(self.value)304 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')305 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'306307 def test_groupby(self):
92 unmodified lines
modified:jinja2/testsuite/imports.py+1 added-1 removed
81 unmodified lines
82 t = test_env.from_string('{% include ["missing", "missing2"] %}')83 self.assert_raises(TemplateNotFound, t.render)84 try:85 t.render()86 except TemplatesNotFound, e:86 except TemplatesNotFound as e:87 assert e.templates == ['missing', 'missing2']88 assert e.name == 'missing2'89 else:90 assert False, 'thou shalt raise'
51 unmodified lines
modified:jinja2/testsuite/inheritance.py+2 added-2 removed
146 unmodified lines
147 '{% endblock %}]{% endfor %}'148 }))149 t = env.from_string('{% extends "master.html" %}{% block item %}'150 '{{ item }}{% endblock %}')151 assert t.render(seq=range(5)) == '[0][1][2][3][4]'151 assert t.render(seq=list(range(5))) == '[0][1][2][3][4]'152153 def test_super_in_scoped_block(self):154 env = Environment(loader=DictLoader({155 'master.html': '{% for item in seq %}[{% block item scoped %}'156 '{{ item }}{% endblock %}]{% endfor %}'157 }))158 t = env.from_string('{% extends "master.html" %}{% block item %}'159 '{{ super() }}|{{ item * 2 }}{% endblock %}')160 assert t.render(seq=range(5)) == '[0|0][1|2][2|4][3|6][4|8]'160 assert t.render(seq=list(range(5))) == '[0|0][1|2][2|4][3|6][4|8]'161162 def test_scoped_block_after_inheritance(self):163 env = Environment(loader=DictLoader({164 'layout.html': '''
63 unmodified lines
modified:jinja2/testsuite/lexnparse.py+15 added-14 removed
13 unmodified lines
14from jinja2.testsuite import JinjaTestCase1516from jinja2 import Environment, Template, TemplateSyntaxError, \17 UndefinedError, nodes18import six1920env = Environment()2122
19 unmodified lines
42 def test_balancing(self):43 env = Environment('{%', '%}', '${', '}')44 tmpl = env.from_string('''{% for item in seq45 %}${{'foo': item}|upper}{% endfor %}''')45 assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"46 assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"4748 def test_comments(self):49 env = Environment('<!--', '-->', '{', '}')50 tmpl = env.from_string('''\
1 unmodified line
52<!--- for item in seq -->53 <li>{item}</li>54<!--- endfor -->55</ul>''')55 assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "56 assert tmpl.render(seq=list(range(3))) == ("<ul>\n <li>0</li>\n "57 "<li>1</li>\n <li>2</li>\n</ul>")5859 def test_string_escapes(self):60 for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':
7 unmodified lines
68 assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')6970 def test_operators(self):71 from jinja2.lexer import operators71 for test, expect in operators.iteritems():72 for test, expect in six.iteritems(operators):73 if test in '([{}])':74 continue75 stream = env.lexer.tokenize('{{ %s }}' % test)75 stream.next()76 six.advance_iterator(stream)77 assert stream.current.type == expect7879 def test_normalizing(self):80 for seq in '\r', '\r\n', '\n':
11 unmodified lines
92<!-- I'm a comment, I'm not interesting -->\93<? for item in seq -?>94 <?= item ?>95<?- endfor ?>''')95 assert tmpl.render(seq=range(5)) == '01234'96 assert tmpl.render(seq=list(range(5))) == '01234'9798 def test_erb_syntax(self):99 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')100 tmpl = env.from_string('''\101<%# I'm a comment, I'm not interesting %>\102<% for item in seq -%>103 <%= item %>104<%- endfor %>''')104 assert tmpl.render(seq=range(5)) == '01234'105 assert tmpl.render(seq=list(range(5))) == '01234'106107 def test_comment_syntax(self):108 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')109 tmpl = env.from_string('''\110<!--# I'm a comment, I'm not interesting -->\111<!-- for item in seq --->112 ${item}113<!--- endfor -->''')113 assert tmpl.render(seq=range(5)) == '01234'114 assert tmpl.render(seq=list(range(5))) == '01234'115116 def test_balancing(self):117 tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')118 assert tmpl.render() == 'bar'
11 unmodified lines
130<%# regular comment %>131% for item in seq:132 ${item}133% endfor''')133 assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \134 range(5)134 assert [int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()] == \135 list(range(5))136137 env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')138 tmpl = env.from_string('''\139<%# regular comment %>140% for item in seq:141 ${item} ## the rest of the stuff142% endfor''')142 assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \143 range(5)143 assert [int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()] == \144 list(range(5))145146 def test_line_syntax_priority(self):147 # XXX: why is the whitespace there in front of the newline?148 env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')
17 unmodified lines
166 def test_error_messages(self):167 def assert_error(code, expected):168 try:169 Template(code)169 except TemplateSyntaxError, e:170 except TemplateSyntaxError as e:171 assert str(e) == expected, 'unexpected error message'172 else:173 assert False, 'that was supposed to be an error'174
160 unmodified lines
335 tmpl = env.from_string('{{ "foo" "bar" "baz" }}')336 assert tmpl.render() == 'foobarbaz'337338 def test_notin(self):338 bar = xrange(100)339 bar = range(100)340 tmpl = env.from_string('''{{ not 42 in bar }}''')340 assert tmpl.render(bar=bar) == unicode(not 42 in bar)341 assert tmpl.render(bar=bar) == six.text_type(not 42 in bar)342343 def test_implicit_subscribed_tuple(self):344 class Foo(object):345 def __getitem__(self, x):
43 unmodified lines
modified:jinja2/testsuite/regression.py+4 added-2 removed
12 unmodified lines
13from jinja2.testsuite import JinjaTestCase1415from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \16 TemplateNotFound, PrefixLoader17from six.moves import map18from six.moves import zip1920env = Environment()2122
96 unmodified lines
119 {% endfor %}120121 ''')122121 assert tmpl.render().split() == map(unicode, range(1, 11)) * 5123 assert tmpl.render().split() == map(unicode, list(range(1, 11))) * 5124125 def test_weird_inline_comment(self):126 env = Environment(line_statement_prefix='%')127 self.assert_raises(TemplateSyntaxError, env.from_string,
115 unmodified lines
243 'foo': DictLoader({})244 }))245 try:246 env.get_template('foo/bar.html')245 except TemplateNotFound, e:247 except TemplateNotFound as e:248 assert e.name == 'foo/bar.html'249 else:250 assert False, 'expected error here'251
6 unmodified lines
modified:jinja2/testsuite/security.py+5 added-4 removed
16 unmodified lines
17 ImmutableSandboxedEnvironment, unsafe18from jinja2 import Markup, escape19from jinja2.exceptions import SecurityError, TemplateSyntaxError, \20 TemplateRuntimeError21import six222324class PrivateStuff(object):25
50 unmodified lines
76 def test_markup_operations(self):77 # adding two strings should escape the unsafe one78 unsafe = '<script type="application/x-some-script">alert("foo");</script>'79 safe = Markup('<em>username</em>')79 assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)80 assert unsafe + safe == six.text_type(escape(unsafe)) + six.text_type(safe)8182 # string interpolations are safe to use too83 assert Markup('<em>%s</em>') % '<bad user>' == \84 '<em>&lt;bad user&gt;</em>'
29 unmodified lines
114 '<p>Hello {{ name }}!</p>{% endmacro %}'115 '{{ say_hello("<blink>foo</blink>") }}')116 escaped_out = '<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>'117 assert t.render() == escaped_out117 assert unicode(t.module) == escaped_out118 assert six.text_type(t.module) == escaped_out119 assert escape(t.module) == escaped_out120 assert t.module.say_hello('<blink>foo</blink>') == escaped_out121 assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out122
13 unmodified lines
136 env.intercepted_binops = frozenset(['+'])137 t = env.from_string('{{ %s }}' % expr)138 try:139 t.render(ctx)139 except TemplateRuntimeError, e:140 except TemplateRuntimeError as e:141 pass142 else:143 self.fail('expected runtime error')144
8 unmodified lines
153 env.intercepted_unops = frozenset(['-'])154 t = env.from_string('{{ %s }}' % expr)155 try:156 t.render(ctx)156 except TemplateRuntimeError, e:157 except TemplateRuntimeError as e:158 pass159 else:160 self.fail('expected runtime error')161
5 unmodified lines
modified:jinja2/testsuite/utils.py+2 added-2 removed
58 unmodified lines
59class MarkupLeakTestCase(JinjaTestCase):6061 def test_markup_leaks(self):62 counts = set()63 for count in xrange(20):64 for item in xrange(1000):63 for count in range(20):64 for item in range(1000):65 escape("foo")66 escape("<foo>")67 escape(u"foo")68 escape(u"<foo>")
14 unmodified lines
modified:jinja2/compiler.py+11 added-8 removed
14 unmodified lines
15from jinja2.nodes import EvalContext16from jinja2.visitor import NodeVisitor17from jinja2.exceptions import TemplateAssertionError18from jinja2.utils import Markup, concat, escape, is_python_keyword, next19import six20from six.moves import map21from six.moves import zip222324operators = {25 'eq': '==',
6 unmodified lines
32 'notin': 'not in'33}3435try:33 exec '(0 if 0 else 0)'36 exec('(0 if 0 else 0)')37except SyntaxError:38 have_condexpr = False39else:40 have_condexpr = True
12 unmodified lines
53 x = 4254 def f():55 if 0: dummy(x)56 return f54unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)57unoptimize_before_dead_code = bool(unoptimize_before_dead_code().__closure__)585960def generate(node, environment, name, filename, stream=None,61 defer_init=False):
18 unmodified lines
80 if not has_safe_repr(item):81 return False82 return True83 elif isinstance(value, dict):81 for key, value in value.iteritems():84 for key, value in six.iteritems(value):85 if not has_safe_repr(key):86 return False87 if not has_safe_repr(value):88 return False
455 unmodified lines
544 for kwarg in node.kwargs:545 self.write(', ')546 self.visit(kwarg, frame)547 if extra_kwargs is not None:545 for key, value in extra_kwargs.iteritems():548 for key, value in six.iteritems(extra_kwargs):549 self.write(', %s=%s' % (key, value))550 if node.dyn_args:551 self.write(', *')552 self.visit(node.dyn_args, frame)
7 unmodified lines
560 self.write('%r: ' % kwarg.key)561 self.visit(kwarg.value, frame)562 self.write(', ')563 if extra_kwargs is not None:561 for key, value in extra_kwargs.iteritems():564 for key, value in six.iteritems(extra_kwargs):565 self.write('%r: %s, ' % (key, value))566 if node.dyn_kwargs is not None:567 self.write('}, **')568 self.visit(node.dyn_kwargs, frame)
58 unmodified lines
627 return aliases628629 def pop_scope(self, aliases, frame):630 """Restore all aliases and delete unused variables."""628 for name, alias in aliases.iteritems():631 for name, alias in six.iteritems(aliases):632 self.writeline('l_%s = %s' % (name, alias))633 to_delete = set()634 for name in frame.identifiers.declared_locally:635 if name not in aliases:
193 unmodified lines
829 self.writeline('yield event')830 self.outdent(2 + (not self.has_known_extends))831832 # at this point we now have the blocks collected and can visit them too.830 for name, block in self.blocks.iteritems():833 for name, block in six.iteritems(self.blocks):834 block_frame = Frame(eval_ctx)835 block_frame.inspect(block.body)836 block_frame.block = name837 self.writeline('def block_%s(context%s):' % (name, envenv),
380 unmodified lines
1218 if self.has_known_extends and frame.require_output_check:1219 return12201221 if self.environment.finalize:1219 finalize = lambda x: unicode(self.environment.finalize(x))1222 finalize = lambda x: six.text_type(self.environment.finalize(x))1223 else:1224 finalize = unicode12251226 # if we are inside a frame that requires output checking, we do so
426 unmodified lines
modified:jinja2/debug.py+5 added-4 removed
13 unmodified lines
14import traceback15from types import TracebackType16from jinja2.utils import CodeType, missing, internal_code17from jinja2.exceptions import TemplateSyntaxError18import six1920# on pypy we can take advantage of transparent proxies21try:22 from __pypy__ import tproxy
2 unmodified lines
252627# how does the raise helper look like?28try:28 exec "raise TypeError, 'foo'"29 exec("raise TypeError, 'foo'")30except SyntaxError:31 raise_helper = 'raise __jinja_exception__[1]'32except TypeError:33 raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]'
124 unmodified lines
158 tb = exc_info[2]159 frames = []160161 # skip some internal frames if wanted161 for x in xrange(initial_skip):162 for x in range(initial_skip):163 if tb is not None:164 tb = tb.tb_next165 initial_tb = tb166
39 unmodified lines
206 if ctx:207 locals = ctx.get_all()208 else:209 locals = {}209 for name, value in real_locals.iteritems():210 for name, value in six.iteritems(real_locals):211 if name.startswith('l_') and value is not missing:212 locals[name[2:]] = value213214 # if there is a local called __jinja_exception__, we get
39 unmodified lines
254 pass255256 # execute the code and catch the new traceback257 try:257 exec code in globals, locals258 exec(code, globals, locals)259 except:260 exc_info = sys.exc_info()261 new_tb = exc_info[2].tb_next262
78 unmodified lines
modified:jinja2/environment.py+14 added-9 removed
19 unmodified lines
20from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \21 TemplatesNotFound22from jinja2.utils import import_string, LRUCache, Markup, missing, \23 concat, consume, internalcode, _encode_filename24import six25from functools import reduce26from six.moves import filter27from six.moves import map28from six.moves import zip293031# for direct template usage we have up to ten living environments32_spontaneous_environments = LRUCache(10)
263 unmodified lines
296 """Add the items to the instance of the environment if they do not exist297 yet. This is used by :ref:`extensions <writing-extensions>` to register298 callbacks and configuration values without breaking inheritance.299 """295 for key, value in attributes.iteritems():300 for key, value in six.iteritems(attributes):301 if not hasattr(self, key):302 setattr(self, key, value)303304 def overlay(self, block_start_string=missing, block_end_string=missing,
22 unmodified lines
327 rv.__dict__.update(self.__dict__)328 rv.overlayed = True329 rv.linked_to = self330326 for key, value in args.iteritems():331 for key, value in six.iteritems(args):332 if value is not missing:333 setattr(rv, key, value)334335 if cache_size is not missing:
1 unmodified line
337 else:338 rv.cache = copy_cache(self.cache)339340 rv.extensions = {}336 for key, value in self.extensions.iteritems():341 for key, value in six.iteritems(self.extensions):342 rv.extensions[key] = value.bind(rv)343 if extensions is not missing:344 rv.extensions.update(load_extensions(rv, extensions))345
65 unmodified lines
411 This does not perform preprocessing. If you want the preprocessing412 of the extensions to be applied you have to filter source through413 the :meth:`preprocess` method.414 """410 source = unicode(source)415 source = six.text_type(source)416 try:417 return self.lexer.tokeniter(source, name, filename)418 except TemplateSyntaxError:419 exc_info = sys.exc_info()
4 unmodified lines
424 called for all parsing and compiling methods but *not* for :meth:`lex`425 because there you usually only want the actual source tokenized.426 """427 return reduce(lambda s, e: e.preprocess(s, name, filename),423 self.iter_extensions(), unicode(source))428 self.iter_extensions(), six.text_type(source))429430 def _tokenize(self, source, name, filename=None, state=None):431 """Called by the parser to do the preprocessing and filtering432 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
148 unmodified lines
581582 def write_file(filename, data, mode):583 if zip:584 info = ZipInfo(filename)580 info.external_attr = 0755 << 16L585 info.external_attr = 0o755 << 16586 zip_file.writestr(info, data)587 else:588 f = open(os.path.join(target, filename), mode)589 try:
15 unmodified lines
605 for name in self.list_templates(extensions, filter_func):606 source, filename, _ = self.loader.get_source(self, name)607 try:608 code = self.compile(source, name, filename, True, True)604 except TemplateSyntaxError, e:609 except TemplateSyntaxError as e:610 if not ignore_errors:611 raise612 log_function('Could not compile "%s": %s' % (name, e))613 continue
233 unmodified lines
847 namespace = {848 'environment': environment,849 '__file__': code.co_filename850 }846 exec code in namespace851 exec(code, namespace)852 rv = cls._from_namespace(environment, namespace, globals)853 rv._uptodate = uptodate854 return rv855
151 unmodified lines
1007 def __html__(self):1008 return Markup(concat(self._body_stream))10091010 def __str__(self):1006 return unicode(self).encode('utf-8')1011 return six.text_type(self).encode('utf-8')10121013 # unicode goes after __str__ because we configured 2to3 to rename1014 # __unicode__ to __str__. because the 2to3 tree is not designed to1015 # remove nodes from it, we leave the above __str__ around and let
115 unmodified lines
modified:jinja2/exceptions.py+5 added-2 removed
6 unmodified lines
78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import six12from six.moves import map13from six.moves import zip141516class TemplateError(Exception):17 """Baseclass for all template errors."""1819 def __init__(self, message=None):20 if message is not None:18 message = unicode(message).encode('utf-8')21 message = six.text_type(message).encode('utf-8')22 Exception.__init__(self, message)2324 @property25 def message(self):
59 unmodified lines
85 # function translated the syntax error into a new traceback86 self.translated = False8788 def __str__(self):86 return unicode(self).encode('utf-8')89 return six.text_type(self).encode('utf-8')9091 # unicode goes after __str__ because we configured 2to3 to rename92 # __unicode__ to __str__. because the 2to3 tree is not designed to93 # remove nodes from it, we leave the above __str__ around and let
53 unmodified lines
modified:jinja2/ext.py+3 added-2 removed
15 unmodified lines
16from jinja2.environment import Environment17from jinja2.runtime import Undefined, concat18from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError19from jinja2.utils import contextfunction, import_string, Markup, next20import six212223# the only real useful gettext functions for a Jinja template. Note24# that ugettext must be assigned to gettext as Jinja doesn't support
329 unmodified lines
354 # in case newstyle gettext is used, the method is powerful355 # enough to handle the variable expansion and autoescape356 # handling itself357 if self.environment.newstyle_gettext:357 for key, value in variables.iteritems():358 for key, value in six.iteritems(variables):359 # the function adds that later anyways in case num was360 # called num, so just skip it.361 if num_called_num and key == 'num':362 continue
238 unmodified lines
601 source = fileobj.read().decode(options.get('encoding', 'utf-8'))602 try:603 node = environment.parse(source)604 tokens = list(environment.lex(environment.preprocess(source)))604 except TemplateSyntaxError, e:605 except TemplateSyntaxError as e:606 if not silent:607 raise608 # skip templates with syntax errors609 return
12 unmodified lines
modified:jinja2/filters.py+18 added-14 removed
15 unmodified lines
16from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \17 unicode_urlencode18from jinja2.runtime import Undefined19from jinja2.exceptions import FilterArgumentError20import six21from six.moves import map22from six.moves import zip232425_word_re = re.compile(r'\w+(?u)')26
43 unmodified lines
70def do_forceescape(value):71 """Enforce HTML escaping. This will probably double escape variables."""72 if hasattr(value, '__html__'):73 value = value.__html__()71 return escape(unicode(value))74 return escape(six.text_type(value))757677def do_urlencode(value):78 """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
2 unmodified lines
81 .. versionadded:: 2.782 """83 itemiter = None84 if isinstance(value, dict):82 itemiter = value.iteritems()85 itemiter = six.iteritems(value)86 elif not isinstance(value, basestring):87 try:88 itemiter = iter(value)89 except TypeError:
22 unmodified lines
112 """113 if count is None:114 count = -1115 if not eval_ctx.autoescape:113 return unicode(s).replace(unicode(old), unicode(new), count)116 return six.text_type(s).replace(six.text_type(old), six.text_type(new), count)117 if hasattr(old, '__html__') or hasattr(new, '__html__') and \118 not hasattr(s, '__html__'):119 s = escape(s)120 else:
36 unmodified lines
157 if the filter returned something unless the second parameter is false.158 """159 rv = u' '.join(160 u'%s="%s"' % (escape(key), escape(value))158 for key, value in d.iteritems()161 for key, value in six.iteritems(d)162 if value is not None and not isinstance(value, Undefined)163 )164 if autospace and rv:165 rv = u' ' + rv
145 unmodified lines
311 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)312313 # no automatic escaping? joining is a lot eaiser then314 if not eval_ctx.autoescape:312 return unicode(d).join(imap(unicode, value))315 return six.text_type(d).join(imap(unicode, value))316317 # if the delimiter doesn't have an html representation we check318 # if any of the items has. If yes we do a coercion to Markup319 if not hasattr(d, '__html__'):
2 unmodified lines
322 for idx, item in enumerate(value):323 if hasattr(item, '__html__'):324 do_escape = True325 else:323 value[idx] = unicode(item)326 value[idx] = six.text_type(item)327 if do_escape:328 d = escape(d)329 else:327 d = unicode(d)330 d = six.text_type(d)331 return d.join(value)332333 # no html involved, to normal joining334 return soft_unicode(d).join(imap(soft_unicode, value))335336337def do_center(value, width=80):338 """Centers the value in a field of a given width."""336 return unicode(value).center(width)339 return six.text_type(value).center(width)340341342@environmentfilter343def do_first(environment, seq):344 """Return the first item of a sequence."""345 try:343 return iter(seq).next()346 return six.advance_iterator(iter(seq))347 except StopIteration:348 return environment.undefined('No first item, sequence was empty.')349350351@environmentfilter352def do_last(environment, seq):353 """Return the last item of a sequence."""354 try:352 return iter(reversed(seq)).next()355 return six.advance_iterator(iter(reversed(seq)))356 except StopIteration:357 return environment.undefined('No last item, sequence was empty.')358359
181 unmodified lines
541 """Strip SGML/XML tags and replace adjacent whitespace by one space.542 """543 if hasattr(value, '__html__'):544 value = value.__html__()542 return Markup(unicode(value)).striptags()545 return Markup(six.text_type(value)).striptags()546547548def do_slice(value, slices, fill_with=None):549 """Slice an iterator and return a list of lists containing
19 unmodified lines
569 length = len(seq)570 items_per_slice = length // slices571 slices_with_extra = length % slices572 offset = 0570 for slice_number in xrange(slices):573 for slice_number in range(slices):574 start = offset + slice_number * items_per_slice575 if slice_number < slices_with_extra:576 offset += 1577 end = offset + (slice_number + 1) * items_per_slice
116 unmodified lines
694 __slots__ = ()695 grouper = property(itemgetter(0))696 list = property(itemgetter(1))697695 def __new__(cls, (key, value)):698 def __new__(cls, xxx_todo_changeme):699 (key, value) = xxx_todo_changeme700 return tuple.__new__(cls, (key, list(value)))701702703@environmentfilter
32 unmodified lines
736737738def do_mark_unsafe(value):739 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""736 return unicode(value)740 return six.text_type(value)741742743def do_reverse(value):744 """Reverse the object or return an iterator the iterates over it the other
88 unmodified lines
modified:jinja2/lexer.py+7 added-6 removed
17 unmodified lines
18from operator import itemgetter19from collections import deque20from jinja2.exceptions import TemplateSyntaxError21from jinja2.utils import LRUCache, next22import six232425# cache for the lexers. Exists in order to be able to have multiple26# environments with the same lexer
99 unmodified lines
126 ',': TOKEN_COMMA,127 ';': TOKEN_SEMICOLON128}129129reverse_operators = dict([(v, k) for k, v in operators.iteritems()])130reverse_operators = dict([(v, k) for k, v in six.iteritems(operators)])131assert len(operators) == len(reverse_operators), 'operators dropped'132operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in133 sorted(operators, key=lambda x: -len(x))))134
184 unmodified lines
319 return result320321 def skip(self, n=1):322 """Got n tokens ahead."""322 for x in xrange(n):323 for x in range(n):324 next(self)325326 def next_if(self, expr):327 """Perform the token test and return the token if it matched.
198 unmodified lines
526 try:527 value = self._normalize_newlines(value[1:-1]) \528 .encode('ascii', 'backslashreplace') \529 .decode('unicode-escape')529 except Exception, e:530 except Exception as e:531 msg = str(e).split(':')[-1].strip()532 raise TemplateSyntaxError(msg, lineno, name, filename)533 # if we can express it as bytestring (ascii only)534 # we do that for support of semi broken APIs
14 unmodified lines
549 def tokeniter(self, source, name, filename=None, state=None):550 """This method tokenizes the text and returns the tokens in a551 generator. Use this method if you just want to tokenize a template.552 """552 source = '\n'.join(unicode(source).splitlines())553 source = '\n'.join(six.text_type(source).splitlines())554 pos = 0555 lineno = 1556 stack = ['root']557 if state is not None and state != 'root':
32 unmodified lines
590 # bygroup is a bit more complex, in that case we591 # yield for the current token the first named592 # group that matched593 elif token == '#bygroup':593 for key, value in m.groupdict().iteritems():594 for key, value in six.iteritems(m.groupdict()):595 if value is not None:596 yield lineno, key, value597 lineno += value.count('\n')598 break
48 unmodified lines
647 if new_state == '#pop':648 stack.pop()649 # resolve the new state by group checking650 elif new_state == '#bygroup':650 for key, value in m.groupdict().iteritems():651 for key, value in six.iteritems(m.groupdict()):652 if value is not None:653 stack.append(key)654 break655 else:
27 unmodified lines
modified:jinja2/loaders.py+2 added-1 removed
11 unmodified lines
12import sys13import weakref14from types import ModuleType15from os import path16import six17try:18 from hashlib import sha119except ImportError:20 from sha import new as sha1
338 unmodified lines
359 raise TemplateNotFound(name)360361 def list_templates(self):362 result = []362 for prefix, loader in self.mapping.iteritems():363 for prefix, loader in six.iteritems(self.mapping):364 for template in loader.list_templates():365 result.append(prefix + self.delimiter + template)366 return result367
107 unmodified lines
modified:jinja2/nodes.py+4 added-3 removed
14 unmodified lines
15import operator16from itertools import chain, izip17from collections import deque18from jinja2.utils import Markup, MethodType, FunctionType19import six202122#: the types we support for context functions23_context_function_types = (FunctionType, MethodType)
118 unmodified lines
142 for attr in self.attributes:143 setattr(self, attr, attributes.pop(attr, None))144 if attributes:145 raise TypeError('unknown attribute %r' %145 iter(attributes).next())146 six.advance_iterator(iter(attributes)))147148 def iter_fields(self, exclude=None, only=None):149 """This method iterates over all fields that are defined and yields150 ``(key, value)`` tuples. Per default all fields are returned, but
289 unmodified lines
440 """Return a const object if the value is representable as441 constant value in the generated code, otherwise it will raise442 an `Impossible` exception.443 """443 from compiler import has_safe_repr444 from .compiler import has_safe_repr445 if not has_safe_repr(value):446 raise Impossible()447 return cls(value, lineno=lineno, environment=environment)448
238 unmodified lines
687 fields = ('nodes',)688689 def as_const(self, eval_ctx=None):690 eval_ctx = get_eval_context(self, eval_ctx)690 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)691 return ''.join(six.text_type(x.as_const(eval_ctx)) for x in self.nodes)692693694class Compare(Expr):695 """Compares an expression with some other expressions. `ops` must be a
216 unmodified lines
modified:jinja2/parser.py+2 added
10 unmodified lines
11from jinja2 import nodes12from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13from jinja2.utils import next14from jinja2.lexer import describe_token, describe_token_expr15from six.moves import map16from six.moves import zip171819#: statements that callinto 20_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
877 unmodified lines
modified:jinja2/runtime.py+5 added-4 removed
12 unmodified lines
13from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \14 concat, internalcode, next, object_type_repr15from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \16 TemplateNotFound17import six181920# these variables are exported to the template runtime21__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
41 unmodified lines
63 # if the parent is shared a copy should be created because64 # we don't want to modify the dict passed65 if shared:66 parent = dict(parent)66 for key, value in locals.iteritems():67 for key, value in six.iteritems(locals):68 if key[:2] == 'l_' and value is not missing:69 parent[key[2:]] = value70 return Context(environment, parent, template_name, blocks)71
47 unmodified lines
119120 # create the initial mapping of blocks. Whenever template inheritance121 # takes place the runtime will update this mapping with the new blocks122 # from the template.122 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())123 self.blocks = dict((k, [v]) for k, v in six.iteritems(blocks))124125 def super(self, name, current):126 """Render a parent block."""127 try:
63 unmodified lines
191 context = new_context(self.environment, self.name, {},192 self.parent, True, None, locals)193 context.vars.update(self.vars)194 context.eval_ctx = self.eval_ctx194 context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())195 context.blocks.update((k, list(v)) for k, v in six.iteritems(self.blocks))196 return context197198 def _all(meth):199 proxy = lambda self: getattr(self.get_all(), meth)()
283 unmodified lines
483 __float__ = __complex__ = __pow__ = __rpow__ = \484 _fail_with_undefined_error485486 def __str__(self):486 return unicode(self).encode('utf-8')487 return six.text_type(self).encode('utf-8')488489 # unicode goes after __str__ because we configured 2to3 to rename490 # __unicode__ to __str__. because the 2to3 tree is not designed to491 # remove nodes from it, we leave the above __str__ around and let
71 unmodified lines
modified:jinja2/sandbox.py+1 added-1 removed
88 unmodified lines
89def safe_range(*args):90 """A range that can't generate ranges with a length of more than91 MAX_RANGE items.92 """93 rng = xrange(*args)93 rng = range(*args)94 if len(rng) > MAX_RANGE:95 raise OverflowError('range too big, maximum size for range is %d' %96 MAX_RANGE)97 return rng
264 unmodified lines
modified:jinja2/tests.py+3 added-2 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja2.runtime import Undefined13import six1415try:16 from collections import Mapping as MappingType17except ImportError:
58 unmodified lines
767778def test_lower(value):79 """Return true if the variable is lowercased."""79 return unicode(value).islower()80 return six.text_type(value).islower()818283def test_upper(value):84 """Return true if the variable is uppercased."""84 return unicode(value).isupper()85 return six.text_type(value).isupper()868788def test_string(value):89 """Return true if the object is a string."""
73 unmodified lines
modified:jinja2/utils.py+11 added-10 removed
9 unmodified lines
10"""11import re12import sys13import errno14import six15try:16 from urllib.parse import quote_from_bytes as url_quote17except ImportError:18 from urllib import quote as url_quote
33 unmodified lines
52 def _test_gen_bug():53 raise TypeError(_test_gen_bug)54 yield None55 _concat(_test_gen_bug())55except TypeError, _error:56except TypeError as _error:57 if not _error.args or _error.args[0] is not _test_gen_bug:58 def concat(gen):59 try:60 return _concat(list(gen))
12 unmodified lines
73try:74 next = next75except NameError:76 def next(x):76 return x.next()77 return six.advance_iterator(x)787980# if this python version is unable to deal with unicode filenames81# when passed to encode we let this function encode it properly.
23 unmodified lines
105 yield None106FunctionType = type(_func)107GeneratorType = type(_func())108MethodType = type(_C.method)108CodeType = type(_C.method.func_code)109CodeType = type(_C.method.__code__)110try:111 raise TypeError()112except TypeError:113 _tb = sys.exc_info()[2]
42 unmodified lines
156157158def internalcode(f):159 """Marks the function as internally used"""159 internal_code.add(f.func_code)160 internal_code.add(f.__code__)161 return f162163164def is_undefined(obj):
61 unmodified lines
226 otherwise `None`.227 """228 try:229 return open(filename, mode)229 except IOError, e:230 except IOError as e:231 if e.errno not in (errno.ENOENT, errno.EISDIR):232 raise233234
40 unmodified lines
275 """276 trim_url = lambda x, limit=trim_url_limit: limit is not None \277 and (x[:limit] + (len(x) >=limit and '...'278 or '')) or x278 words = _word_split_re.split(unicode(escape(text)))279 words = _word_split_re.split(six.text_type(escape(text)))280 nofollow_attr = nofollow and ' rel="nofollow"' or ''281 for i, word in enumerate(words):282 match = _punctuation_re.match(word)283 if match:
28 unmodified lines
312 from random import choice, randrange313 words = LOREM_IPSUM_WORDS.split()314 result = []315315 for _ in xrange(n):316 for _ in range(n):317 next_capitalized = True318 last_comma = last_fullstop = 0319 word = None320 last = None321 p = []322323 # each paragraph contains out of 20 to 100 words.323 for idx, _ in enumerate(xrange(randrange(min, max))):324 for idx, _ in enumerate(range(randrange(min, max))):325 while True:326 word = choice(words)327 if word != last:328 last = word
34 unmodified lines
363 If non strings are provided they are converted to their unicode364 representation first.365 """366 if not isinstance(obj, basestring):366 obj = unicode(obj)367 obj = six.text_type(obj)368 if isinstance(obj, unicode):369 obj = obj.encode(charset)369 return unicode(url_quote(obj))370 return six.text_type(url_quote(obj))371372373class LRUCache(object):374 """A simple LRU Cache implementation."""
252 unmodified lines