| 1 |
""" simpleTALUtils |
| 2 |
|
| 3 |
Copyright (c) 2009 Colin Stewart (http://www.owlfish.com/) |
| 4 |
All rights reserved. |
| 5 |
|
| 6 |
Redistribution and use in source and binary forms, with or without |
| 7 |
modification, are permitted provided that the following conditions |
| 8 |
are met: |
| 9 |
1. Redistributions of source code must retain the above copyright |
| 10 |
notice, this list of conditions and the following disclaimer. |
| 11 |
2. Redistributions in binary form must reproduce the above copyright |
| 12 |
notice, this list of conditions and the following disclaimer in the |
| 13 |
documentation and/or other materials provided with the distribution. |
| 14 |
3. The name of the author may not be used to endorse or promote products |
| 15 |
derived from this software without specific prior written permission. |
| 16 |
|
| 17 |
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
| 18 |
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
| 19 |
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 20 |
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 21 |
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
| 22 |
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 23 |
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 24 |
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 25 |
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
| 26 |
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 27 |
|
| 28 |
If you make any bug fixes or feature enhancements please let me know! |
| 29 |
|
| 30 |
This module is holds utilities that make using SimpleTAL easier. |
| 31 |
Initially this is just the HTMLStructureCleaner class, used to clean |
| 32 |
up HTML that can then be used as 'structure' content. |
| 33 |
|
| 34 |
Module Dependencies: None |
| 35 |
""" |
| 36 |
|
| 37 |
import io, os, stat, threading, sys, codecs, cgi, re, types, logging |
| 38 |
from . import __version__, simpleTAL |
| 39 |
|
| 40 |
|
| 41 |
ESCAPED_TEXT_REGEX=re.compile (r"\&\S+?;") |
| 42 |
|
| 43 |
class TemplateCache: |
| 44 |
""" A TemplateCache is a multi-thread safe object that caches compiled templates. |
| 45 |
This cache only works with file based templates, the ctime of the file is |
| 46 |
checked on each hit, if the file has changed the template is re-compiled. |
| 47 |
""" |
| 48 |
def __init__ (self): |
| 49 |
self.templateCache = {} |
| 50 |
self.cacheLock = threading.Lock() |
| 51 |
self.hits = 0 |
| 52 |
self.misses = 0 |
| 53 |
|
| 54 |
def getTemplate (self, name, inputEncoding='utf-8'): |
| 55 |
""" Name should be the path of a template file. If the path ends in 'xml' it is treated |
| 56 |
as an XML Template, otherwise it's treated as an HTML Template. If the template file |
| 57 |
has changed since the last cache it will be re-compiled. |
| 58 |
|
| 59 |
inputEncoding is only used for HTML templates, and should be the encoding that the template |
| 60 |
is stored in. |
| 61 |
""" |
| 62 |
if (name in self.templateCache): |
| 63 |
template, oldctime = self.templateCache [name] |
| 64 |
ctime = os.stat (name)[stat.ST_MTIME] |
| 65 |
if (oldctime == ctime): |
| 66 |
|
| 67 |
self.hits += 1 |
| 68 |
return template |
| 69 |
|
| 70 |
return self._cacheTemplate_ (name, inputEncoding) |
| 71 |
|
| 72 |
def getXMLTemplate (self, name): |
| 73 |
""" Name should be the path of an XML template file. |
| 74 |
""" |
| 75 |
if (name in self.templateCache): |
| 76 |
template, oldctime = self.templateCache [name] |
| 77 |
ctime = os.stat (name)[stat.ST_MTIME] |
| 78 |
if (oldctime == ctime): |
| 79 |
|
| 80 |
self.hits += 1 |
| 81 |
return template |
| 82 |
|
| 83 |
return self._cacheTemplate_ (name, None, xmlTemplate=1) |
| 84 |
|
| 85 |
def _cacheTemplate_ (self, name, inputEncoding, xmlTemplate=0): |
| 86 |
self.cacheLock.acquire () |
| 87 |
try: |
| 88 |
tempFile = open (name, 'rb') |
| 89 |
if (xmlTemplate): |
| 90 |
|
| 91 |
template = simpleTAL.compileXMLTemplate (tempFile) |
| 92 |
else: |
| 93 |
|
| 94 |
firstline = tempFile.readline() |
| 95 |
tempFile.seek(0) |
| 96 |
if (name [-3:] == "xml") or (firstline.strip ()[:5] == b'<?xml') or (firstline [:9] == b'<!DOCTYPE' and firstline.find(b'XHTML') != -1): |
| 97 |
template = simpleTAL.compileXMLTemplate (tempFile) |
| 98 |
else: |
| 99 |
template = simpleTAL.compileHTMLTemplate (codecs.lookup (inputEncoding).streamreader(tempFile)) |
| 100 |
tempFile.close() |
| 101 |
self.templateCache [name] = (template, os.stat (name)[stat.ST_MTIME]) |
| 102 |
self.misses += 1 |
| 103 |
except Exception as e: |
| 104 |
self.cacheLock.release() |
| 105 |
raise e |
| 106 |
|
| 107 |
self.cacheLock.release() |
| 108 |
return template |
| 109 |
|
| 110 |
def tagAsText (tag,atts): |
| 111 |
result = "<" + tag |
| 112 |
for name,value in atts: |
| 113 |
if (ESCAPED_TEXT_REGEX.search (value) is not None): |
| 114 |
|
| 115 |
result += ' %s="%s"' % (name, value) |
| 116 |
else: |
| 117 |
result += ' %s="%s"' % (name, cgi.escape (value)) |
| 118 |
result += ">" |
| 119 |
return result |
| 120 |
|
| 121 |
class MacroExpansionInterpreter (simpleTAL.TemplateInterpreter): |
| 122 |
def __init__ (self): |
| 123 |
simpleTAL.TemplateInterpreter.__init__ (self) |
| 124 |
|
| 125 |
self.macroStateStack = [] |
| 126 |
self.commandHandler [simpleTAL.TAL_DEFINE] = self.cmdNoOp |
| 127 |
self.commandHandler [simpleTAL.TAL_CONDITION] = self.cmdNoOp |
| 128 |
self.commandHandler [simpleTAL.TAL_REPEAT] = self.cmdNoOp |
| 129 |
self.commandHandler [simpleTAL.TAL_CONTENT] = self.cmdNoOp |
| 130 |
self.commandHandler [simpleTAL.TAL_ATTRIBUTES] = self.cmdNoOp |
| 131 |
self.commandHandler [simpleTAL.TAL_OMITTAG] = self.cmdNoOp |
| 132 |
self.commandHandler [simpleTAL.TAL_START_SCOPE] = self.cmdStartScope |
| 133 |
self.commandHandler [simpleTAL.TAL_OUTPUT] = self.cmdOutput |
| 134 |
self.commandHandler [simpleTAL.TAL_STARTTAG] = self.cmdOutputStartTag |
| 135 |
self.commandHandler [simpleTAL.TAL_ENDTAG_ENDSCOPE] = self.cmdEndTagEndScope |
| 136 |
self.commandHandler [simpleTAL.METAL_USE_MACRO] = self.cmdUseMacro |
| 137 |
self.commandHandler [simpleTAL.METAL_DEFINE_SLOT] = self.cmdDefineSlot |
| 138 |
self.commandHandler [simpleTAL.TAL_NOOP] = self.cmdNoOp |
| 139 |
|
| 140 |
self.inMacro = None |
| 141 |
self.macroArg = None |
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
def popProgram (self): |
| 146 |
self.inMacro = self.macroStateStack.pop() |
| 147 |
simpleTAL.TemplateInterpreter.popProgram (self) |
| 148 |
|
| 149 |
def pushProgram (self): |
| 150 |
self.macroStateStack.append (self.inMacro) |
| 151 |
simpleTAL.TemplateInterpreter.pushProgram (self) |
| 152 |
|
| 153 |
def cmdOutputStartTag (self, command, args): |
| 154 |
newAtts = [] |
| 155 |
for att, value in list(self.originalAttributes.items()): |
| 156 |
if (self.macroArg is not None and att == "metal:define-macro"): |
| 157 |
newAtts.append (("metal:use-macro",self.macroArg)) |
| 158 |
elif (self.inMacro and att=="metal:define-slot"): |
| 159 |
newAtts.append (("metal:fill-slot", value)) |
| 160 |
else: |
| 161 |
newAtts.append ((att, value)) |
| 162 |
self.macroArg = None |
| 163 |
self.currentAttributes = newAtts |
| 164 |
simpleTAL.TemplateInterpreter.cmdOutputStartTag (self, command, args) |
| 165 |
|
| 166 |
def cmdUseMacro (self, command, args): |
| 167 |
simpleTAL.TemplateInterpreter.cmdUseMacro (self, command, args) |
| 168 |
if (self.tagContent is not None): |
| 169 |
|
| 170 |
self.inMacro = 1 |
| 171 |
self.macroArg = args[0] |
| 172 |
|
| 173 |
def cmdEndTagEndScope (self, command, args): |
| 174 |
|
| 175 |
if (self.tagContent is not None): |
| 176 |
contentType, resultVal = self.tagContent |
| 177 |
if (contentType): |
| 178 |
if (isinstance (resultVal, simpleTAL.Template)): |
| 179 |
|
| 180 |
|
| 181 |
self.pushProgram() |
| 182 |
resultVal.expandInline (self.context, self.file, self) |
| 183 |
|
| 184 |
self.popProgram() |
| 185 |
|
| 186 |
self.slotParameters = {} |
| 187 |
|
| 188 |
self.inMacro = 0 |
| 189 |
else: |
| 190 |
if (isinstance (resultVal, str)): |
| 191 |
self.file.write (resultVal) |
| 192 |
elif (isinstance (resultVal, bytes)): |
| 193 |
self.file.write (str (resultVal, 'ascii')) |
| 194 |
else: |
| 195 |
self.file.write (str (str (resultVal), 'ascii')) |
| 196 |
else: |
| 197 |
if (isinstance (resultVal, str)): |
| 198 |
self.file.write (cgi.escape (resultVal)) |
| 199 |
elif (isinstance (resultVal, bytes)): |
| 200 |
self.file.write (cgi.escape (str (resultVal, 'ascii'))) |
| 201 |
else: |
| 202 |
self.file.write (cgi.escape (str (str (resultVal), 'ascii'))) |
| 203 |
|
| 204 |
if (self.outputTag and not args[1]): |
| 205 |
self.file.write ('</' + args[0] + '>') |
| 206 |
|
| 207 |
if (self.movePCBack is not None): |
| 208 |
self.programCounter = self.movePCBack |
| 209 |
return |
| 210 |
|
| 211 |
if (self.localVarsDefined): |
| 212 |
self.context.popLocals() |
| 213 |
|
| 214 |
self.movePCForward,self.movePCBack,self.outputTag,self.originalAttributes,self.currentAttributes,self.repeatVariable,self.tagContent,self.localVarsDefined = self.scopeStack.pop() |
| 215 |
self.programCounter += 1 |
| 216 |
|
| 217 |
def ExpandMacros (context, template, outputEncoding="utf-8"): |
| 218 |
out = io.StringIO() |
| 219 |
interp = MacroExpansionInterpreter() |
| 220 |
interp.initialise (context, out) |
| 221 |
template.expand (context, out, outputEncoding=outputEncoding, interpreter=interp) |
| 222 |
return out.getvalue() |
| 223 |
|