small refactoring
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent dd65ef4 · Browse files · 5 files·+85 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+85 added−60 removed
- other:+85 added−60 removed
Provenance
- Commit
ed1e0d4- Tree
12b7e78- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
dd65ef4
5 files changed+85 added−60 removed
modified:examples/rwbench/rwbench.py+1 added-2 removed
39 unmodified lines40 self.href = '/article/%d' % self.id41 self.title = generate_lorem_ipsum(1, False, 5, 10)42 self.user = choice(users)43 self.body = generate_lorem_ipsum()44- self.pub_date = datetime.utcfromtimestamp(randrange(1000000000,45- 2000000000))44+ self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9))45 46 47 class User(object):48 36 unmodified linesmodified:jinja2/compiler.py+53 added-51 removed
355 unmodified lines356 """Get a new unique identifier."""357 self._last_identifier += 1358 return 't%d' % self._last_identifier359 360+ def buffer(self, frame):361+ """Enable buffering for the frame from that point onwards."""362+ frame.buffer = buf = self.temporary_identifier()363+ self.writeline('%s = []' % buf)364+ return buf365+366+ def return_buffer_contents(self, frame):367+ """Return the buffer contents of the frame."""368+ if self.environment.autoescape:369+ self.writeline('return Markup(concat(%s))' % frame.buffer)370+ else:371+ self.writeline('return concat(%s)' % frame.buffer)372+373 def indent(self):374 """Indent by one."""375 self._indentation += 1376 383 unmodified lines760 self.indent()761 if frame.buffer is None:762 self.writeline('yield event')763 else:751- self.writeline('%s.append(event)' % frame.buffer)764+ self.writeline('%s(event)' % frame.buffer)765 self.outdent()766 767 def visit_Import(self, node, frame):768 """Visit regular imports."""82 unmodified lines851 aliases = self.collect_shadowed(loop_frame)852 853 # otherwise we set up a buffer and add a function def854 else:842- loop_frame.buffer = buf = self.temporary_identifier()855 self.writeline('def loop(reciter, loop_render_func):', node)856 self.indent()845- self.writeline('%s = []' % buf, node)857+ self.buffer(loop_frame)858 aliases = {}859 860 self.pull_locals(loop_frame)861 if node.else_:68 unmodified lines930 931 # if the node was recursive we have to return the buffer contents932 # and start the iteration code933 if node.recursive:922- if self.environment.autoescape:923- self.writeline('return Markup(concat(%s))' % buf)924- else:925- self.writeline('return concat(%s)' % buf)934+ self.return_buffer_contents(loop_frame)935 self.outdent()936 if frame.buffer is None:937 self.writeline('yield loop(', node)938 else:20 unmodified lines959 def visit_Macro(self, node, frame):960 macro_frame = self.function_scoping(node, frame)961 args = macro_frame.arguments962 self.writeline('def macro(%s):' % ', '.join(args), node)954- macro_frame.buffer = buf = self.temporary_identifier()963 self.indent()964+ self.buffer(macro_frame)965 self.pull_locals(macro_frame)957- self.writeline('%s = []' % buf)966 self.blockvisit(node.body, macro_frame)959- if self.environment.autoescape:960- self.writeline('return Markup(concat(%s))' % buf)961- else:962- self.writeline("return concat(%s)" % buf)967+ self.return_buffer_contents(macro_frame)968 self.outdent()969 self.newline()970 if frame.toplevel:971 if not node.name.startswith('__'):17 unmodified lines989 call_frame = self.function_scoping(node, frame, node.iter_child_nodes990 (exclude=('call',)))991 args = call_frame.arguments992 self.writeline('def call(%s):' % ', '.join(args), node)988- call_frame.buffer = buf = self.temporary_identifier()993 self.indent()994 self.pull_locals(call_frame)991- self.writeline('%s = []' % buf)995+ self.buffer(call_frame)996 self.blockvisit(node.body, call_frame)993- if self.environment.autoescape:994- self.writeline("return Markup(concat(%s))" % buf)995- else:996- self.writeline('return concat(%s)' % buf)997+ self.return_buffer_contents(call_frame)998 self.outdent()999 arg_tuple = ', '.join(repr(x.name) for x in node.args)1000 if len(node.args) == 1:1001 arg_tuple += ','20 unmodified lines1022 filter_frame.inspect(node.iter_child_nodes())1023 1024 aliases = self.collect_shadowed(filter_frame)1025 self.pull_locals(filter_frame)1025- filter_frame.buffer = buf = self.temporary_identifier()1026+ self.buffer(filter_frame)1027 1027- self.writeline('%s = []' % buf, node)1028 for child in node.body:1029 self.visit(child, filter_frame)1030 1031 if frame.buffer is None:1032 self.writeline('yield ', node)1033 else:1034 self.writeline('%s.append(' % frame.buffer, node)1035- self.visit_Filter(node.filter, filter_frame, 'concat(%s)' % buf)1035+ self.visit_Filter(node.filter, filter_frame, 'concat(%s)'1036+ % filter_frame.buffer)1037 if frame.buffer is not None:1038 self.write(')')1039 1040 def visit_ExprStmt(self, node, frame):29 unmodified lines1070 body[-1].append(const)1071 else:1072 body.append([const])1073 1073- # if we have less than 3 nodes or less than 6 and a buffer we1074- # yield or extend/append1075- if len(body) < 3 or (frame.buffer is not None and len(body) < 6):1074+ # if we have less than 3 nodes or a buffer we yield or extend/append1075+ if len(body) < 3 or frame.buffer is not None:1076 if frame.buffer is not None:1077 # for one item we append, for more we extend1078 if len(body) == 1:1079 self.writeline('%s.append(' % frame.buffer)8 unmodified lines1088 else:1089 self.writeline(val + ', ')1090 else:1091 if frame.buffer is None:1092- self.writeline('yield ')1092+ self.writeline('yield ', item)1093 else:1094 self.newline(item)1095 close = 11096 if self.environment.autoescape:21 unmodified lines1118 format.append(concat(item).replace('%', '%%'))1119 else:1120 format.append('%s')1121 arguments.append(item)1122- if frame.buffer is None:1123- self.writeline('yield ')1122+ self.writeline('yield ')1124- else:1125- self.writeline('%s.append(' % frame.buffer)1123 self.write(repr(concat(format)) + ' % (')1124 idx = -11125 self.indent()1126 for argument in arguments:1130- self.newline()1127+ self.newline(argument)1128 close = 01129 if self.environment.autoescape:1130 self.write('escape(')1131 close += 13 unmodified lines1135 self.visit(argument, frame)1136 self.write(')' * close + ', ')1137 self.outdent()1138 self.writeline(')')1142- if frame.buffer is not None:1143- self.write(')')1139 1140 if outdent_later:1141 self.outdent()1142 38 unmodified lines1181 if node.ctx == 'store' and frame.toplevel:1182 frame.assigned_names.add(node.name)1183 self.write('l_' + node.name)1184 1190- def visit_MarkSafe(self, node, frame):1191- self.write('Markup(')1192- self.visit(node.expr, frame)1193- self.write(')')1194-1195- def visit_EnvironmentAttribute(self, node, frame):1196- self.write('environment.' + node.name)1197-1198- def visit_ExtensionAttribute(self, node, frame):1199- self.write('environment.extensions[%r].%s' % (node.identifier, node.attr))1200-1201- def visit_ImportedName(self, node, frame):1202- self.write(self.import_aliases[node.importname])1203-1204- def visit_InternalName(self, node, frame):1205- self.write(node.name)1206-1185 def visit_Const(self, node, frame):1186 val = node.value1187 if isinstance(val, float):1210- # XXX: add checks for infinity and nan1188 self.write(str(val))1189 else:1190 self.write(repr(val))1191 156 unmodified lines1348 1349 def visit_Keyword(self, node, frame):1350 self.write(node.key + '=')1351 self.visit(node.value, frame)1352+1353+ # Unused nodes for extensions1354+1355+ def visit_MarkSafe(self, node, frame):1356+ self.write('Markup(')1357+ self.visit(node.expr, frame)1358+ self.write(')')1359+1360+ def visit_EnvironmentAttribute(self, node, frame):1361+ self.write('environment.' + node.name)1362+1363+ def visit_ExtensionAttribute(self, node, frame):1364+ self.write('environment.extensions[%r].%s' % (node.identifier, node.attr))1365+1366+ def visit_ImportedName(self, node, frame):1367+ self.write(self.import_aliases[node.importname])1368+1369+ def visit_InternalName(self, node, frame):1370+ self.write(node.name)1371+1372+ def visit_Continue(self, node, frame):1373+ self.writeline('continue', node)1374+1375+ def visit_Break(self, node, frame):1376+ self.writeline('break', node)modified:jinja2/environment.py-1 removed
335 unmodified lines336 source = self.parse(source, name, filename)337 if self.optimized:338 node = optimize(source, self)339 source = generate(node, self, name, filename)340- #print source340 if raw:341 return source342 if filename is None:343 filename = '<template>'338 unmodified linesmodified:jinja2/nodes.py+8 added
798 unmodified lines799 def as_const(self):800 return Markup(self.expr.as_const())801 802 803+class Continue(Stmt):804+ """Continue a loop."""805+806+807+class Break(Stmt):808+ """Break a loop."""809+810+811 # and close down812 _node_setup_finished = Truemodified:jinja2/runtime.py+23 added-6 removed
183 unmodified lines184 if enforce_length:185 len(self)186 187 def cycle(self, *args):188- """A replacement for the old ``{% cycle %}`` tag."""188+ """Cycles among the arguments with the current loop index."""189 if not args:190 raise TypeError('no items for cycling given')191 return args[self.index0 % len(args)]192 6 unmodified lines199 def __len__(self):200 return self.length201 202 def __iter__(self):203- return self203+ return LoopContextIterator(self)204 205 def loop(self, iterable):206 if self._recurse is None:207 raise TypeError('Tried to call non recursive loop. Maybe you '3 unmodified lines211 # a nifty trick to enhance the error message if someone tried to call212 # the the loop without or with too many arguments.213 __call__ = loop; del loop214 215- def next(self):216- self.index0 += 1217- return self._next(), self218-215 @property216 def length(self):217 if self._length is None:218 try:219+ # first try to get the length from the iterable (if the220+ # iterable is a sequence)221 length = len(self._iterable)222 except TypeError:223+ # if that's not possible (ie: iterating over a generator)224+ # we have to convert the iterable into a sequence and225+ # use the length of that.226 self._iterable = tuple(self._iterable)227 self._next = iter(self._iterable).next228 length = len(tuple(self._iterable)) + self.index0 + 1229 self._length = length6 unmodified lines236 self.length237 )238 239 240+class LoopContextIterator(object):241+ """The iterator for a loop context."""242+ __slots__ = ('context',)243+244+ def __init__(self, context):245+ self.context = context246+247+ def __iter__(self):248+ return self249+250+ def next(self):251+ ctx = self.context252+ ctx.index0 += 1253+ return ctx._next(), ctx254+255+256 class Macro(object):257 """Wraps a macro."""258 259 def __init__(self, environment, func, name, arguments, defaults,179 unmodified lines