File python-htmltmpl-1.22-performance.patch of Package python-htmltmpl
Index: htmltmpl.py
===================================================================
RCS file: /cvsroot/htmltmpl/htmltmpl/htmltmpl.py,v
retrieving revision 1.16
diff -a -u -r1.16 htmltmpl.py
--- htmltmpl.py 17 Dec 2001 07:21:04 -0000 1.16
+++ htmltmpl.py 3 Jul 2003 11:11:56 -0000
@@ -76,6 +76,12 @@
LOCK_SH = 2
LOCK_UN = 3
+def DEB(str):
+ """ Print debugging message to stderr.
+ @hidden
+ """
+ print >> sys.stderr, str
+
##############################################
# CLASS: TemplateManager #
##############################################
@@ -166,7 +172,7 @@
if precompile and not LOCKTYPE:
raise TemplateError, "Template precompilation is not "\
"available on this platform."
- self.DEB("INIT DONE")
+ self._debug and DEB("INIT DONE")
def prepare(self, file):
""" Preprocess, parse, tokenize and compile the template.
@@ -212,17 +218,17 @@
compile_params = (self._include, self._max_include,
self._comments, self._gettext)
if precompiled.is_uptodate(compile_params):
- self.DEB("PRECOMPILED: UPTODATE")
+ self._debug and DEB("PRECOMPILED: UPTODATE")
compiled = precompiled
else:
- self.DEB("PRECOMPILED: NOT UPTODATE")
+ self._debug and DEB("PRECOMPILED: NOT UPTODATE")
compiled = self.update(precompiled)
else:
- self.DEB("PRECOMPILED: NOT PRECOMPILED")
+ self._debug and DEB("PRECOMPILED: NOT PRECOMPILED")
compiled = self.compile(file)
self.save_precompiled(compiled)
else:
- self.DEB("PRECOMPILATION DISABLED")
+ self._debug and DEB("PRECOMPILATION DISABLED")
compiled = self.compile(file)
return compiled
@@ -244,7 +250,7 @@
<em>TemplateCompiler</em>. The instance must represent a template
compiled from a file on disk.
"""
- self.DEB("UPDATE")
+ self._debug and DEB("UPDATE")
updated = self.compile(template.file())
if self._precompile:
self.save_precompiled(updated)
@@ -254,12 +260,6 @@
# PRIVATE METHODS #
##############################################
- def DEB(self, str):
- """ Print debugging message to stderr if debugging is enabled.
- @hidden
- """
- if self._debug: print >> sys.stderr, str
-
def lock_file(self, file, lock):
""" Provide platform independent file locking.
@hidden
@@ -316,7 +316,7 @@
@hidden
"""
filename = file + "c" # "template.tmplc"
- self.DEB("LOADING PRECOMPILED")
+ self._debug and DEB("LOADING PRECOMPILED")
try:
remove_bad = 0
file = None
@@ -390,7 +390,7 @@
remove_bad = 1
raise
else:
- self.DEB("SAVING PRECOMPILED")
+ self._debug and DEB("SAVING PRECOMPILED")
finally:
if file:
self.lock_file(file, LOCK_UN)
@@ -439,7 +439,7 @@
should be automatically looked up in enclosing scopes.
Automatic global lookup is disabled by default. Global lookup
- can be overriden on a per-variable basis by the
+ can be overridden on a per-variable basis by the
<strong>GLOBAL</strong> parameter of a <strong>TMPL_VAR</strong>
statement.
@@ -499,7 +499,7 @@
raise TemplateError, "Value of toplevel variable '%s' must "\
"be either a scalar or a list." % var
self._vars[var] = value
- self.DEB("VALUE SET: " + str(var))
+ self._debug and DEB("VALUE SET: " + str(var))
def reset(self, keep_data=0):
""" Reset the template data.
@@ -521,7 +521,7 @@
self._current_pos = 0
if not keep_data:
self._vars.clear()
- self.DEB("RESET")
+ self._debug and DEB("RESET")
def process(self, template, part=None):
""" Process a compiled template. Return the result as string.
@@ -549,7 +549,7 @@
If this parameter is not specified, then the whole template
is processed, or all remaining parts are processed.
"""
- self.DEB("APP INPUT:")
+ self._debug and DEB("APP INPUT:")
if self._debug: pprint.pprint(self._vars, sys.stderr)
if part != None and (part == 0 or part < self._current_part):
raise TemplateError, "process() - invalid part number"
@@ -574,7 +574,7 @@
tokens = template.tokens()
len_tokens = len(tokens)
- out = "" # buffer for processed output
+ out = [] # buffer for processed output
# Recover position at which we ended after processing of last part.
i = self._current_pos
@@ -601,12 +601,12 @@
skip_params = 1
# If output of current block is not disabled then append
- # the substitued and escaped variable to the output.
+ # the substituted and escaped variable to the output.
if DISABLE_OUTPUT not in output_control:
value = str(self.find_value(var, loop_name, loop_pass,
loop_total, globalp))
- out += self.escape(value, escape)
- self.DEB("VAR: " + str(var))
+ out.append(self.escape(value, escape))
+ self._debug and DEB("VAR: " + str(var))
elif token == "<TMPL_LOOP":
var = tokens[i + PARAM_NAME]
@@ -629,10 +629,10 @@
if passtotal == 0:
# This loop is empty.
output_control.append(DISABLE_OUTPUT)
- self.DEB("LOOP: DISABLE: " + str(var))
+ self._debug and DEB("LOOP: DISABLE: " + str(var))
else:
output_control.append(ENABLE_OUTPUT)
- self.DEB("LOOP: FIRST PASS: %s TOTAL: %d"\
+ self._debug and DEB("LOOP: FIRST PASS: %s TOTAL: %d"\
% (var, passtotal))
elif token == "<TMPL_IF":
@@ -644,10 +644,10 @@
if self.find_value(var, loop_name, loop_pass,
loop_total, globalp):
output_control.append(ENABLE_OUTPUT)
- self.DEB("IF: ENABLE: " + str(var))
+ self._debug and DEB("IF: ENABLE: " + str(var))
else:
output_control.append(DISABLE_OUTPUT)
- self.DEB("IF: DISABLE: " + str(var))
+ self._debug and DEB("IF: DISABLE: " + str(var))
elif token == "<TMPL_UNLESS":
var = tokens[i + PARAM_NAME]
@@ -658,10 +658,10 @@
if self.find_value(var, loop_name, loop_pass,
loop_total, globalp):
output_control.append(DISABLE_OUTPUT)
- self.DEB("UNLESS: DISABLE: " + str(var))
+ self._debug and DEB("UNLESS: DISABLE: " + str(var))
else:
output_control.append(ENABLE_OUTPUT)
- self.DEB("UNLESS: ENABLE: " + str(var))
+ self._debug and DEB("UNLESS: ENABLE: " + str(var))
elif token == "</TMPL_LOOP":
skip_params = 1
@@ -679,26 +679,26 @@
loop_start.pop()
loop_total.pop()
output_control.pop()
- self.DEB("LOOP: END")
+ self._debug and DEB("LOOP: END")
else:
- # Jump to the beggining of this loop block
+ # Jump to the beginning of this loop block
# to process next pass of the loop.
i = loop_start[-1]
- self.DEB("LOOP: NEXT PASS")
+ self._debug and DEB("LOOP: NEXT PASS")
elif token == "</TMPL_IF":
skip_params = 1
if not output_control:
raise TemplateError, "Unmatched </TMPL_IF>."
output_control.pop()
- self.DEB("IF: END")
+ self._debug and DEB("IF: END")
elif token == "</TMPL_UNLESS":
skip_params = 1
if not output_control:
raise TemplateError, "Unmatched </TMPL_UNLESS>."
output_control.pop()
- self.DEB("UNLESS: END")
+ self._debug and DEB("UNLESS: END")
elif token == "<TMPL_ELSE":
skip_params = 1
@@ -707,23 +707,23 @@
if output_control[-1] == DISABLE_OUTPUT:
# Condition was false, activate the ELSE block.
output_control[-1] = ENABLE_OUTPUT
- self.DEB("ELSE: ENABLE")
+ self._debug and DEB("ELSE: ENABLE")
elif output_control[-1] == ENABLE_OUTPUT:
# Condition was true, deactivate the ELSE block.
output_control[-1] = DISABLE_OUTPUT
- self.DEB("ELSE: DISABLE")
+ self._debug and DEB("ELSE: DISABLE")
else:
raise TemplateError, "BUG: ELSE: INVALID FLAG"
elif token == "<TMPL_BOUNDARY":
if part and part == self._current_part:
- self.DEB("BOUNDARY ON")
+ self._debug and DEB("BOUNDARY ON")
self._current_part += 1
self._current_pos = i + 1 + PARAMS_NUMBER
break
else:
skip_params = 1
- self.DEB("BOUNDARY OFF")
+ self._debug and DEB("BOUNDARY OFF")
self._current_part += 1
elif token == "<TMPL_INCLUDE":
@@ -731,22 +731,22 @@
# when it was not replaced by the parser.
skip_params = 1
filename = tokens[i + PARAM_NAME]
- out += """
+ out.append("""
<br />
<p>
<strong>HTMLTMPL WARNING:</strong><br />
Cannot include template: <strong>%s</strong>
</p>
<br />
- """ % filename
- self.DEB("CANNOT INCLUDE WARNING")
+ """ % filename)
+ self._debug and DEB("CANNOT INCLUDE WARNING")
elif token == "<TMPL_GETTEXT":
skip_params = 1
if DISABLE_OUTPUT not in output_control:
text = tokens[i + PARAM_GETTEXT_STRING]
- out += gettext.gettext(text)
- self.DEB("GETTEXT: " + text)
+ out.append(gettext.gettext(text))
+ self._debug and DEB("GETTEXT: " + text)
else:
# Unknown processing directive.
@@ -756,7 +756,7 @@
# Raw textual template data.
# If output of current block is not disabled, then
# append template data to the output buffer.
- out += token
+ out.append(token)
i += 1
# end of the big while loop
@@ -764,18 +764,12 @@
# Check whether all opening statements were closed.
if loop_name: raise TemplateError, "Missing </TMPL_LOOP>."
if output_control: raise TemplateError, "Missing </TMPL_IF> or </TMPL_UNLESS>"
- return out
+ return "".join(out)
##############################################
# PRIVATE METHODS #
##############################################
- def DEB(self, str):
- """ Print debugging message to stderr if debugging is enabled.
- @hidden
- """
- if self._debug: print >> sys.stderr, str
-
def find_value(self, var, loop_name, loop_pass, loop_total,
global_override=None):
""" Search the self._vars data structure to find variable var
@@ -783,11 +777,11 @@
is currently being processed. If the variable is an ordinary
variable, then return it.
- If the variable is an identificator of a loop, then
+ If the variable is an identifier of a loop, then
return the total number of times this loop will
be executed.
- Return an empty string, if the variable is not
+ Return an empty string if the variable is not
found at all.
@hidden
@@ -808,7 +802,7 @@
self.is_ordinary_var(scope[var]):
globals.append(scope[var])
- # Descent deeper into the hierarchy.
+ # Descend deeper into the hierarchy.
if scope.has_key(loop_name[i]) and scope[loop_name[i]]:
scope = scope[loop_name[i]][loop_pass[i]]
else:
@@ -843,7 +837,7 @@
@hidden
"""
- self.DEB("MAGIC: '%s', PASS: %d, TOTAL: %d"\
+ self._debug and DEB("MAGIC: '%s', PASS: %d, TOTAL: %d"\
% (var, loop_pass, loop_total))
if var == "__FIRST__":
if loop_pass == 0:
@@ -889,7 +883,7 @@
raise TemplateError, "Magic variable __EVERY__x: "\
"Pass number cannot be zero."
elif (loop_pass + 1) % every == 0:
- self.DEB("MAGIC: EVERY: " + str(every))
+ self._debug and DEB("MAGIC: EVERY: " + str(every))
return 1
else:
return 0
@@ -934,7 +928,7 @@
class. The compiled form is used as input for the TemplateProcessor
which uses it to actually process the template.
- This class should be used direcly only when you need to compile
+ This class should be used directly only when you need to compile
a template from a string. If your template is in a file, then you
should use the <em>TemplateManager</em> class which provides
a higher level interface to this class and also can save the
@@ -979,10 +973,10 @@
@param file Filename of the template.
See the <em>prepare()</em> method of the <em>TemplateManager</em>
- class for exaplanation of this parameter.
+ class for explanation of this parameter.
"""
- self.DEB("COMPILING FROM FILE: " + file)
+ self._debug and DEB("COMPILING FROM FILE: " + file)
self._include_path = os.path.join(os.path.dirname(file), INCLUDE_DIR)
tokens = self.parse(self.read(file))
compile_params = (self._include, self._max_include, self._comments,
@@ -1004,7 +998,7 @@
@param data String containing the template data.
"""
- self.DEB("COMPILING FROM STRING")
+ self._debug and DEB("COMPILING FROM STRING")
self._include = 0
tokens = self.parse(data)
compile_params = (self._include, self._max_include, self._comments,
@@ -1015,19 +1009,13 @@
##############################################
# PRIVATE METHODS #
##############################################
-
- def DEB(self, str):
- """ Print debugging message to stderr if debugging is enabled.
- @hidden
- """
- if self._debug: print >> sys.stderr, str
def read(self, filename):
""" Read content of file and return it. Raise an error if a problem
occurs.
@hidden
"""
- self.DEB("READING: " + filename)
+ self._debug and DEB("READING: " + filename)
try:
f = None
try:
@@ -1049,11 +1037,11 @@
@hidden
"""
if self._comments:
- self.DEB("PREPROCESS: COMMENTS")
+ self._debug and DEB("PREPROCESS: COMMENTS")
template_data = self.remove_comments(template_data)
tokens = self.tokenize(template_data)
if self._include:
- self.DEB("PREPROCESS: INCLUDES")
+ self._debug and DEB("PREPROCESS: INCLUDES")
self.include_templates(tokens)
return tokens
@@ -1092,7 +1080,7 @@
# Do not include the template.
# Protection against infinite recursive includes.
skip_params = 1
- self.DEB("INCLUDE: LIMIT REACHED: " + filename)
+ self._debug and DEB("INCLUDE: LIMIT REACHED: " + filename)
else:
# Include the template.
skip_params = 0
@@ -1106,7 +1094,7 @@
# token and its parameters.
tokens[i:i+PARAMS_NUMBER+1] = include_tokens
i = i + len(include_tokens)
- self.DEB("INCLUDED: " + filename)
+ self._debug and DEB("INCLUDED: " + filename)
continue # Do not increment 'i' below.
i += 1
# end of the main while loop
@@ -1122,7 +1110,7 @@
@hidden
"""
- self.DEB("TOKENIZING TEMPLATE")
+ self._debug and DEB("TOKENIZING TEMPLATE")
# NOTE: The TWO double quotes in character class in the regexp below
# are there only to prevent confusion of syntax highlighter in Emacs.
pattern = r"""
@@ -1152,7 +1140,7 @@
else:
# "Normal" template data.
if self._gettext:
- self.DEB("PARSING GETTEXT STRINGS")
+ self._debug and DEB("PARSING GETTEXT STRINGS")
self.gettext_tokens(tokens, statement)
else:
tokens.append(statement)
@@ -1226,7 +1214,7 @@
""" Append a gettext token and gettext string to the tokens array.
@hidden
"""
- self.DEB("GETTEXT PARSER: TOKEN: " + str)
+ self._debug and DEB("GETTEXT PARSER: TOKEN: " + str)
tokens.append("<TMPL_GETTEXT")
tokens.append(str)
tokens.append(None)
@@ -1234,7 +1222,7 @@
def strip_brackets(self, statement):
""" Strip HTML brackets (with optional HTML comments) from the
- beggining and from the end of a statement.
+ beginning and from the end of a statement.
@hidden
"""
if statement.startswith("<!-- TMPL_") or \
@@ -1249,12 +1237,12 @@
"""
directive = params[0]
del params[0]
- self.DEB("TOKENIZER: DIRECTIVE: " + directive)
+ self._debug and DEB("TOKENIZER: DIRECTIVE: " + directive)
return "<" + directive
def find_name(self, params):
""" Extract identifier from a statement. The identifier can be
- specified both implicitely or explicitely as a 'NAME' parameter.
+ specified both implicitly or explicitly as a 'NAME' parameter.
@hidden
"""
if len(params) > 0 and '=' not in params[0]:
@@ -1264,7 +1252,7 @@
else:
# explicit identifier as a 'NAME' parameter
name = self.find_param("NAME", params)
- self.DEB("TOKENIZER: NAME: " + str(name))
+ self._debug and DEB("TOKENIZER: NAME: " + str(name))
return name
def find_param(self, param, params):
@@ -1282,10 +1270,12 @@
else:
# The value is without double quotes.
ret_value = value
- self.DEB("TOKENIZER: PARAM: '%s' => '%s'" % (param, ret_value))
+ self._debug and DEB("TOKENIZER: PARAM: '%s' => '%s'"\
+ % (param, ret_value))
return ret_value
else:
- self.DEB("TOKENIZER: PARAM: '%s' => NOT DEFINED" % param)
+ self._debug and DEB("TOKENIZER: PARAM: '%s' => NOT DEFINED"\
+ % param)
return None
@@ -1322,16 +1312,16 @@
self._include_mtimes = {}
if not file:
- self.DEB("TEMPLATE WAS COMPILED FROM A STRING")
+ self._debug and DEB("TEMPLATE WAS COMPILED FROM A STRING")
return
- # Save modifitcation time of the main template file.
+ # Save modification time of the main template file.
if os.path.isfile(file):
self._mtime = os.path.getmtime(file)
else:
raise TemplateError, "Template: file does not exist: '%s'" % file
- # Save modificaton times of all included template files.
+ # Save modification times of all included template files.
for inc_file in include_files:
if os.path.isfile(inc_file):
self._include_mtimes[inc_file] = os.path.getmtime(inc_file)
@@ -1339,7 +1329,7 @@
raise TemplateError, "Template: file does not exist: '%s'"\
% inc_file
- self.DEB("NEW TEMPLATE CREATED")
+ self._debug and DEB("NEW TEMPLATE CREATED")
def is_uptodate(self, compile_params=None):
""" Check whether the compiled template is uptodate.
@@ -1359,15 +1349,15 @@
internal use by the <em>TemplateManager</em>.
"""
if not self._file:
- self.DEB("TEMPLATE COMPILED FROM A STRING")
+ self._debug and DEB("TEMPLATE COMPILED FROM A STRING")
return 0
if self._version != __version__:
- self.DEB("TEMPLATE: VERSION NOT UPTODATE")
+ self._debug and DEB("TEMPLATE: VERSION NOT UPTODATE")
return 0
if compile_params != None and compile_params != self._compile_params:
- self.DEB("TEMPLATE: DIFFERENT COMPILATION PARAMS")
+ self._debug and DEB("TEMPLATE: DIFFERENT COMPILATION PARAMS")
return 0
# Check modification times of the main template and all included
@@ -1377,7 +1367,7 @@
# Main template file.
if not (os.path.isfile(self._file) and \
self._mtime == os.path.getmtime(self._file)):
- self.DEB("TEMPLATE: NOT UPTODATE: " + self._file)
+ self._debug and DEB("TEMPLATE: NOT UPTODATE: " + self._file)
return 0
# Included templates.
@@ -1385,10 +1375,10 @@
if not (os.path.isfile(inc_file) and \
self._include_mtimes[inc_file] == \
os.path.getmtime(inc_file)):
- self.DEB("TEMPLATE: NOT UPTODATE: " + inc_file)
+ self._debug and DEB("TEMPLATE: NOT UPTODATE: " + inc_file)
return 0
else:
- self.DEB("TEMPLATE: UPTODATE")
+ self._debug and DEB("TEMPLATE: UPTODATE")
return 1
def tokens(self):
@@ -1431,13 +1421,6 @@
self.__dict__ = dict
- def DEB(self, str):
- """ Print debugging message to stderr.
- @hidden
- """
- if self._debug: print >> sys.stderr, str
-
-
##############################################
# EXCEPTIONS #
##############################################
@@ -1452,7 +1435,7 @@
All potential IOError exceptions are handled by the module and are
converted to TemplateError exceptions. That means you should catch the
TemplateError exception if there is a possibility that for example
- the template file will not be accesssible.
+ the template file will not be accessible.
The exception can be raised by constructors or by any method of any
class.