"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "Cheetah/Template.py" between
cheetah3-3.1.0.tar.gz and cheetah3-3.2.0.tar.gz

About: Cheetah3 is a template engine and code generation tool for e.g. for Web development or Java, SQL, LaTeX, form email ... (written in Python).

Template.py  (cheetah3-3.1.0):Template.py  (cheetah3-3.2.0)
skipping to change at line 265 skipping to change at line 265
klass._CHEETAH_useCompilationCache (_CHEETAH_xxx) klass._CHEETAH_useCompilationCache (_CHEETAH_xxx)
Instance attributes look like this:: Instance attributes look like this::
klass._CHEETAH__globalSetVars (_CHEETAH__xxx with 2 underscores) klass._CHEETAH__globalSetVars (_CHEETAH__xxx with 2 underscores)
''' '''
# this is used by ._addCheetahPlumbingCodeToClass() # this is used by ._addCheetahPlumbingCodeToClass()
_CHEETAH_requiredCheetahMethods = ( _CHEETAH_requiredCheetahMethods = (
'_initCheetahInstance', '_initCheetahInstance',
'searchList', 'searchList',
'errorCatcher', 'errorCatcher',
'getVar', 'getVar',
'varExists', 'varExists',
'getFileContents', 'getFileContents',
'i18n', 'i18n',
'runAsMainProgram', 'runAsMainProgram',
'respond', 'respond',
'shutdown', 'shutdown',
'webInput', 'webInput',
'serverSidePath', 'serverSidePath',
'generatedClassCode', 'generatedClassCode',
'generatedModuleCode', 'generatedModuleCode',
'_getCacheStore', '_getCacheStore',
'_getCacheStoreIdPrefix', '_getCacheStoreIdPrefix',
'_createCacheRegion', '_createCacheRegion',
'getCacheRegion', 'getCacheRegion',
'getCacheRegions', 'getCacheRegions',
'refreshCache', 'refreshCache',
'_handleCheetahInclude', '_handleCheetahInclude',
'_getTemplateAPIClassForIncludeDirectiveCompilation', '_getTemplateAPIClassForIncludeDirectiveCompilation',
) )
_CHEETAH_requiredCheetahClassMethods = ('subclass',) _CHEETAH_requiredCheetahClassMethods = ('subclass',)
_CHEETAH_requiredCheetahClassAttributes = ( _CHEETAH_requiredCheetahClassAttributes = (
'cacheRegionClass', 'cacheStore', 'cacheRegionClass', 'cacheStore',
'cacheStoreIdPrefix', 'cacheStoreClass') 'cacheStoreIdPrefix', 'cacheStoreClass')
# The following are used by .compile(). # The following are used by .compile().
# Most are documented in its docstring. # Most are documented in its docstring.
_CHEETAH_cacheModuleFilesForTracebacks = False _CHEETAH_cacheModuleFilesForTracebacks = False
_CHEETAH_cacheDirForModuleFiles = None # change to a dirname _CHEETAH_cacheDirForModuleFiles = None # change to a dirname
skipping to change at line 970 skipping to change at line 970
pass pass
settings.templateAPIClass = PreprocessTemplateAPIClass settings.templateAPIClass = PreprocessTemplateAPIClass
if not hasattr(settings, 'compilerSettings'): if not hasattr(settings, 'compilerSettings'):
settings.compilerSettings = {} settings.compilerSettings = {}
klass._updateSettingsWithPreprocessTokens( klass._updateSettingsWithPreprocessTokens(
compilerSettings=settings.compilerSettings, compilerSettings=settings.compilerSettings,
placeholderToken=settings.placeholderToken, placeholderToken=settings.placeholderToken,
directiveToken=settings.directiveToken directiveToken=settings.directiveToken
) )
return settings return settings
@classmethod @classmethod
def _updateSettingsWithPreprocessTokens( def _updateSettingsWithPreprocessTokens(
klass, compilerSettings, placeholderToken, directiveToken): klass, compilerSettings, placeholderToken, directiveToken):
if (placeholderToken and if (placeholderToken
'cheetahVarStartToken' not in compilerSettings): and 'cheetahVarStartToken' not in compilerSettings):
compilerSettings['cheetahVarStartToken'] = placeholderToken compilerSettings['cheetahVarStartToken'] = placeholderToken
if directiveToken: if directiveToken:
if 'directiveStartToken' not in compilerSettings: if 'directiveStartToken' not in compilerSettings:
compilerSettings['directiveStartToken'] = directiveToken compilerSettings['directiveStartToken'] = directiveToken
if 'directiveEndToken' not in compilerSettings: if 'directiveEndToken' not in compilerSettings:
compilerSettings['directiveEndToken'] = directiveToken compilerSettings['directiveEndToken'] = directiveToken
if 'commentStartToken' not in compilerSettings: if 'commentStartToken' not in compilerSettings:
compilerSettings['commentStartToken'] = directiveToken*2 compilerSettings['commentStartToken'] = directiveToken*2 # noqa : E226,E501 missing whitespace around operator
if 'multiLineCommentStartToken' not in compilerSettings: if 'multiLineCommentStartToken' not in compilerSettings:
compilerSettings['multiLineCommentStartToken'] = ( compilerSettings['multiLineCommentStartToken'] = (
directiveToken+'*') directiveToken + '*')
if 'multiLineCommentEndToken' not in compilerSettings: if 'multiLineCommentEndToken' not in compilerSettings:
compilerSettings['multiLineCommentEndToken'] = ( compilerSettings['multiLineCommentEndToken'] = (
'*'+directiveToken) '*' + directiveToken)
if 'EOLSlurpToken' not in compilerSettings: if 'EOLSlurpToken' not in compilerSettings:
compilerSettings['EOLSlurpToken'] = directiveToken compilerSettings['EOLSlurpToken'] = directiveToken
@classmethod @classmethod
def _addCheetahPlumbingCodeToClass(klass, concreteTemplateClass): def _addCheetahPlumbingCodeToClass(klass, concreteTemplateClass):
"""If concreteTemplateClass is not a subclass of Cheetah.Template, add """If concreteTemplateClass is not a subclass of Cheetah.Template, add
the required cheetah methods and attributes to it. the required cheetah methods and attributes to it.
This is called on each new template class after it has been compiled. This is called on each new template class after it has been compiled.
If concreteTemplateClass is not a subclass of Cheetah.Template but If concreteTemplateClass is not a subclass of Cheetah.Template but
skipping to change at line 1020 skipping to change at line 1020
getattr(method, '__func__', method), concreteTemplateClass) getattr(method, '__func__', method), concreteTemplateClass)
setattr(concreteTemplateClass, methodname, newMethod) setattr(concreteTemplateClass, methodname, newMethod)
for classMethName in klass._CHEETAH_requiredCheetahClassMethods: for classMethName in klass._CHEETAH_requiredCheetahClassMethods:
if not hasattr(concreteTemplateClass, classMethName): if not hasattr(concreteTemplateClass, classMethName):
meth = getattr(klass, classMethName) meth = getattr(klass, classMethName)
setattr(concreteTemplateClass, classMethName, setattr(concreteTemplateClass, classMethName,
classmethod(meth.__func__)) classmethod(meth.__func__))
for attrname in klass._CHEETAH_requiredCheetahClassAttributes: for attrname in klass._CHEETAH_requiredCheetahClassAttributes:
attrname = '_CHEETAH_'+attrname attrname = '_CHEETAH_' + attrname
if not hasattr(concreteTemplateClass, attrname): if not hasattr(concreteTemplateClass, attrname):
attrVal = getattr(klass, attrname) attrVal = getattr(klass, attrname)
setattr(concreteTemplateClass, attrname, attrVal) setattr(concreteTemplateClass, attrname, attrVal)
if (not hasattr(concreteTemplateClass, '__str__') if (not hasattr(concreteTemplateClass, '__str__')
or concreteTemplateClass.__str__ == object.__str__): or concreteTemplateClass.__str__ == object.__str__):
mainMethNameAttr = '_mainCheetahMethod_for_' \ mainMethNameAttr = '_mainCheetahMethod_for_' \
+ concreteTemplateClass.__name__ + concreteTemplateClass.__name__
mainMethName = getattr(concreteTemplateClass, mainMethName = getattr(concreteTemplateClass,
mainMethNameAttr, None) mainMethNameAttr, None)
skipping to change at line 1227 skipping to change at line 1227
errmsgextra = errmsg + "\n%s" errmsgextra = errmsg + "\n%s"
if not isinstance(source, (NoneType, string_type)): if not isinstance(source, (NoneType, string_type)):
raise TypeError(errmsg % ('source', 'string or None')) raise TypeError(errmsg % ('source', 'string or None'))
if not isinstance(file, (NoneType, string_type, filetype)): if not isinstance(file, (NoneType, string_type, filetype)):
raise TypeError(errmsg % raise TypeError(errmsg %
('file', 'string, file open for reading, or None')) ('file', 'string, file open for reading, or None'))
if not isinstance(filter, (string_type, type)) \ if not isinstance(filter, (string_type, type)) \
and not (isinstance(filter, type) and and not (isinstance(filter, type)
issubclass(filter, Filters.Filter)): and issubclass(filter, Filters.Filter)):
raise TypeError(errmsgextra % raise TypeError(errmsgextra %
('filter', 'string or class', ('filter', 'string or class',
'(if class, must be subclass ' '(if class, must be subclass '
'of Cheetah.Filters.Filter)')) 'of Cheetah.Filters.Filter)'))
if not isinstance(filtersLib, (string_type, types.ModuleType)): if not isinstance(filtersLib, (string_type, types.ModuleType)):
raise TypeError(errmsgextra % raise TypeError(errmsgextra %
('filtersLib', 'string or module', ('filtersLib', 'string or module',
'(if module, must contain subclasses ' '(if module, must contain subclasses '
'of Cheetah.Filters.Filter)')) 'of Cheetah.Filters.Filter)'))
skipping to change at line 1257 skipping to change at line 1257
raise TypeError( raise TypeError(
errmsgextra % ('errorCatcher', 'string, class or None', errmsgextra % ('errorCatcher', 'string, class or None',
'(if class, must be subclass of ' '(if class, must be subclass of '
'Cheetah.ErrorCatchers.ErrorCatcher)')) 'Cheetah.ErrorCatchers.ErrorCatcher)'))
if compilerSettings is not Unspecified: if compilerSettings is not Unspecified:
if not isinstance(compilerSettings, dict): if not isinstance(compilerSettings, dict):
raise TypeError(errmsg % raise TypeError(errmsg %
('compilerSettings', 'dictionary')) ('compilerSettings', 'dictionary'))
if source is not None and file is not None: if source is not None and file is not None:
raise TypeError("you must supply either a source string or the" + raise TypeError("you must supply either a source string or the"
" 'file' keyword argument, but not both") + " 'file' keyword argument, but not both")
################################################## ##################################################
# Do superclass initialization. # Do superclass initialization.
super(Template, self).__init__() super(Template, self).__init__()
################################################## ##################################################
# Do required version check # Do required version check
if not hasattr(self, '_CHEETAH_versionTuple'): if not hasattr(self, '_CHEETAH_versionTuple'):
try: try:
mod = sys.modules[self.__class__.__module__] mod = sys.modules[self.__class__.__module__]
compiledVersion = mod.__CHEETAH_version__ compiledVersion = mod.__CHEETAH_version__
compiledVersionTuple = \ compiledVersionTuple = \
convertVersionStringToTuple(compiledVersion) convertVersionStringToTuple(compiledVersion)
if compiledVersionTuple < MinCompatibleVersionTuple: if compiledVersionTuple < MinCompatibleVersionTuple:
raise AssertionError( raise AssertionError(
'This template was compiled with Cheetah version %s.' 'This template was compiled with Cheetah version %s.'
'Templates compiled before version %s must be recompiled.' 'Templates compiled before version %s '
% (compiledVersion, MinCompatibleVersion)) 'must be recompiled.'
% (compiledVersion, MinCompatibleVersion))
except AssertionError: except AssertionError:
raise raise
except Exception: except Exception:
pass pass
################################################## ##################################################
# Setup instance state attributes used during the life of template # Setup instance state attributes used during the life of template
# post-compile # post-compile
if searchList: if searchList:
for namespace in searchList: for namespace in searchList:
skipping to change at line 1339 skipping to change at line 1340
""" """
return self._CHEETAH_generatedModuleCode return self._CHEETAH_generatedModuleCode
def generatedClassCode(self): def generatedClassCode(self):
"""Return the class code the compiler generated, or None if no """Return the class code the compiler generated, or None if no
compilation took place. compilation took place.
""" """
return self._CHEETAH_generatedModuleCode[ return self._CHEETAH_generatedModuleCode[
self._CHEETAH_generatedModuleCode.find('\nclass '): self._CHEETAH_generatedModuleCode.find('\nclass '):
self._CHEETAH_generatedModuleCode.find( self._CHEETAH_generatedModuleCode.find(
'\n## END CLASS DEFINITION')] '\n## END CLASS DEFINITION')]
def searchList(self): def searchList(self):
"""Return a reference to the searchlist """Return a reference to the searchlist
""" """
return self._CHEETAH__searchList return self._CHEETAH__searchList
def errorCatcher(self): def errorCatcher(self):
"""Return a reference to the current errorCatcher """Return a reference to the current errorCatcher
""" """
return self._CHEETAH__errorCatcher return self._CHEETAH__errorCatcher
skipping to change at line 1909 skipping to change at line 1910
Version: 1.186 Version: 1.186
Start Date: 2002/03/17 Start Date: 2002/03/17
Last Revision Date: 2008/03/10 04:48:11 Last Revision Date: 2008/03/10 04:48:11
""" """
src = src.lower() src = src.lower()
isCgi = not self._CHEETAH__isControlledByWebKit isCgi = not self._CHEETAH__isControlledByWebKit
if isCgi and src in ('f', 'v'): if isCgi and src in ('f', 'v'):
global _formUsedByWebInput global _formUsedByWebInput
if _formUsedByWebInput is None: if _formUsedByWebInput is None:
_formUsedByWebInput = cgi.FieldStorage() _formUsedByWebInput = cgi.FieldStorage()
source, func = 'field', _formUsedByWebInput.getvalue source, func = 'field', _formUsedByWebInput.getvalue
elif isCgi and src == 'c': elif isCgi and src == 'c':
raise RuntimeError("can't get cookies from a CGI script") raise RuntimeError("can't get cookies from a CGI script")
elif isCgi and src == 's': elif isCgi and src == 's':
raise RuntimeError("can't get session variables from a CGI script") raise RuntimeError("can't get session variables from a CGI script")
elif isCgi and src == 'v': elif isCgi and src == 'v':
source, func = 'value', self.request().value source, func = 'value', self.request().value
elif isCgi and src == 's': elif isCgi and src == 's':
source, func = 'session', self.request().session().value source, func = 'session', self.request().session().value
elif src == 'f': elif src == 'f':
source, func = 'field', self.request().field source, func = 'field', self.request().field
elif src == 'c': elif src == 'c':
source, func = 'cookie', self.request().cookie source, func = 'cookie', self.request().cookie
elif src == 'v': elif src == 'v':
source, func = 'value', self.request().value source, func = 'value', self.request().value
elif src == 's': elif src == 's':
source, func = 'session', self.request().session().value # noqa: E5 01,F841 source, func = 'session', self.request().session().value # noqa: E5 01,F841
else: else:
raise TypeError("arg 'src' invalid") raise TypeError("arg 'src' invalid")
converters = { converters = {
'': _Converter('string', None, default, default), '': _Converter('string', None, default, default),
'int': _Converter('int', int, defaultInt, badInt), 'int': _Converter('int', int, defaultInt, badInt),
'float': _Converter('float', float, defaultFloat, badFloat), 'float': _Converter('float', float, defaultFloat, badFloat),
} }
# pprint.pprint(locals()); return {} # pprint.pprint(locals()); return {}
dic = {} # Destination. dic = {} # Destination.
for name in names: for name in names:
k, v = _lookup(name, func, False, converters) k, v = _lookup(name, func, False, converters)
dic[k] = v dic[k] = v
for name in namesMulti: for name in namesMulti:
k, v = _lookup(name, func, True, converters) k, v = _lookup(name, func, True, converters)
dic[k] = v dic[k] = v
skipping to change at line 1974 skipping to change at line 1975
if hasattr(exception, 'lineno'): if hasattr(exception, 'lineno'):
pyLineno = exception.lineno pyLineno = exception.lineno
else: else:
pyLineno = int( pyLineno = int(
re.search('[ \t]*File.*line (\d+)', formatedExc).group(1)) re.search('[ \t]*File.*line (\d+)', formatedExc).group(1))
lines = generatedPyCode.splitlines() lines = generatedPyCode.splitlines()
prevLines = [] # (i, content) prevLines = [] # (i, content)
for i in range(1, 4): for i in range(1, 4):
if pyLineno-i <= 0: if pyLineno - i <= 0:
break break
prevLines.append((pyLineno+1-i, lines[pyLineno-i])) prevLines.append((pyLineno + 1 - i, lines[pyLineno - i]))
nextLines = [] # (i, content) nextLines = [] # (i, content)
for i in range(1, 4): for i in range(1, 4):
if not pyLineno+i < len(lines): if not pyLineno + i < len(lines):
break break
nextLines.append((pyLineno+i, lines[pyLineno+i])) nextLines.append((pyLineno + i, lines[pyLineno + i]))
nextLines.reverse() nextLines.reverse()
report = 'Line|Python Code\n' report = 'Line|Python Code\n'
report += '----|--------------------------' \ report += '----|--------------------------' \
'-----------------------------------\n' '-----------------------------------\n'
while prevLines: while prevLines:
lineInfo = prevLines.pop() lineInfo = prevLines.pop()
report += "%(row)-4d|%(line)s\n" \ report += "%(row)-4d|%(line)s\n" \
% {'row': lineInfo[0], 'line': lineInfo[1]} % {'row': lineInfo[0], 'line': lineInfo[1]}
if hasattr(exception, 'offset'): if hasattr(exception, 'offset'):
report += ' '*(3+(exception.offset or 0)) + '^\n' report += ' '*(3 + (exception.offset or 0)) + '^\n' # noqa: E226,E501 m issing whitespace around operator
while nextLines: while nextLines:
lineInfo = nextLines.pop() lineInfo = nextLines.pop()
report += "%(row)-4d|%(line)s\n" \ report += "%(row)-4d|%(line)s\n" \
% {'row': lineInfo[0], 'line': lineInfo[1]} % {'row': lineInfo[0], 'line': lineInfo[1]}
message = [ message = [
"Error in the Python code which Cheetah generated for this template:", "Error in the Python code which Cheetah generated for this template:",
'='*80, '='*80, # noqa: E226 missing whitespace around operator
'', '',
str(exception), str(exception),
'', '',
report, report,
'='*80, '='*80, # noqa: E226 missing whitespace around operator
] ]
cheetahPosMatch = re.search('line (\d+), col (\d+)', formatedExc) cheetahPosMatch = re.search('line (\d+), col (\d+)', formatedExc)
if cheetahPosMatch: if cheetahPosMatch:
lineno = int(cheetahPosMatch.group(1)) lineno = int(cheetahPosMatch.group(1))
col = int(cheetahPosMatch.group(2)) col = int(cheetahPosMatch.group(2))
# if hasattr(exception, 'offset'): # if hasattr(exception, 'offset'):
# col = exception.offset # col = exception.offset
message.append('\nHere is the corresponding Cheetah code:\n') message.append('\nHere is the corresponding Cheetah code:\n')
else: else:
lineno = None lineno = None
col = None col = None
cheetahPosMatch = re.search('line (\d+), col (\d+)', cheetahPosMatch = re.search('line (\d+), col (\d+)',
'\n'.join(lines[max(pyLineno-2, 0):])) '\n'.join(lines[max(pyLineno - 2, 0):]))
if cheetahPosMatch: if cheetahPosMatch:
lineno = int(cheetahPosMatch.group(1)) lineno = int(cheetahPosMatch.group(1))
col = int(cheetahPosMatch.group(2)) col = int(cheetahPosMatch.group(2))
message.append('\nHere is the corresponding Cheetah code.') message.append('\nHere is the corresponding Cheetah code.')
message.append('** I had to guess the line & column numbers,' message.append('** I had to guess the line & column numbers,'
' so they are probably incorrect:\n') ' so they are probably incorrect:\n')
message = '\n'.join(message) message = '\n'.join(message)
reader = SourceReader(source, filename=filename) reader = SourceReader(source, filename=filename)
return ParseError(reader, message, lineno=lineno, col=col) return ParseError(reader, message, lineno=lineno, col=col)
 End of changes. 25 change blocks. 
58 lines changed or deleted 59 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)