| 1 |
''' |
| 2 |
Provides the core API for Cheetah |
| 3 |
|
| 4 |
See the docstring in the Template class and the Users' Guide |
| 5 |
for more information. |
| 6 |
''' |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
import sys |
| 11 |
import re |
| 12 |
import logging |
| 13 |
import os.path |
| 14 |
import time |
| 15 |
from random import randrange |
| 16 |
import inspect |
| 17 |
import io |
| 18 |
try: |
| 19 |
from StringIO import StringIO |
| 20 |
except ImportError: |
| 21 |
from io import StringIO |
| 22 |
import traceback |
| 23 |
import pprint |
| 24 |
try: |
| 25 |
import cgi |
| 26 |
except ImportError: |
| 27 |
from urllib.parse import parse_qs |
| 28 |
cgi = None |
| 29 |
import types |
| 30 |
|
| 31 |
from . import ErrorCatchers |
| 32 |
from . import Filters |
| 33 |
from .CacheRegion import CacheRegion |
| 34 |
from .CacheStore import MemoryCacheStore |
| 35 |
from .Compiler import Compiler |
| 36 |
from .NameMapper import NotFound, valueFromSearchList |
| 37 |
from .Parser import ParseError, SourceReader |
| 38 |
|
| 39 |
from .Servlet import Servlet |
| 40 |
from .Unspecified import Unspecified |
| 41 |
from .Utils.Indenter import Indenter |
| 42 |
from .Utils.WebInputMixin import _Converter, _lookup, \ |
| 43 |
NonNumericInputError |
| 44 |
from .Version import MinCompatibleVersion |
| 45 |
from .Version import convertVersionStringToTuple, \ |
| 46 |
MinCompatibleVersionTuple |
| 47 |
from .compat import PY2, string_type, unicode |
| 48 |
from .convertTmplPathToModuleName import convertTmplPathToModuleName |
| 49 |
|
| 50 |
try: |
| 51 |
from threading import Lock |
| 52 |
except ImportError: |
| 53 |
class Lock: |
| 54 |
def acquire(self): |
| 55 |
pass |
| 56 |
|
| 57 |
def release(self): |
| 58 |
pass |
| 59 |
|
| 60 |
if PY2: |
| 61 |
filetype = file |
| 62 |
|
| 63 |
def createMethod(func, cls): |
| 64 |
return types.MethodType(func, None, cls) |
| 65 |
else: |
| 66 |
filetype = io.IOBase |
| 67 |
|
| 68 |
def createMethod(func, cls): |
| 69 |
return func |
| 70 |
|
| 71 |
|
| 72 |
NoneType = type(None) |
| 73 |
|
| 74 |
|
| 75 |
__checkFileMtime = True |
| 76 |
|
| 77 |
|
| 78 |
def checkFileMtime(value): |
| 79 |
globals()['__checkFileMtime'] = value |
| 80 |
|
| 81 |
|
| 82 |
class Error(Exception): |
| 83 |
pass |
| 84 |
|
| 85 |
|
| 86 |
class PreprocessError(Error): |
| 87 |
pass |
| 88 |
|
| 89 |
|
| 90 |
def hashList(v_list): |
| 91 |
hashedList = [] |
| 92 |
for v in v_list: |
| 93 |
if isinstance(v, dict): |
| 94 |
v = hashDict(v) |
| 95 |
elif isinstance(v, list): |
| 96 |
v = hashList(v) |
| 97 |
hashedList.append(v) |
| 98 |
return hash(tuple(hashedList)) |
| 99 |
|
| 100 |
|
| 101 |
def hashDict(d): |
| 102 |
items = sorted(d.items()) |
| 103 |
hashedList = [] |
| 104 |
for k, v in items: |
| 105 |
if isinstance(v, dict): |
| 106 |
v = hashDict(v) |
| 107 |
elif isinstance(v, list): |
| 108 |
v = hashList(v) |
| 109 |
hashedList.append((k, v)) |
| 110 |
return hash(tuple(hashedList)) |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
def _genUniqueModuleName(baseModuleName): |
| 117 |
"""The calling code is responsible for concurrency locking. |
| 118 |
""" |
| 119 |
finalName = baseModuleName |
| 120 |
while finalName in sys.modules: |
| 121 |
finalName = ('cheetah_%s_%s_%s' % (baseModuleName, |
| 122 |
str(time.time()).replace('.', '_'), |
| 123 |
str(randrange(10000, 99999)))) |
| 124 |
return finalName |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
_formUsedByWebInput = None |
| 130 |
|
| 131 |
|
| 132 |
def updateLinecache(filename, src): |
| 133 |
import linecache |
| 134 |
size = len(src) |
| 135 |
mtime = time.time() |
| 136 |
lines = src.splitlines() |
| 137 |
fullname = filename |
| 138 |
linecache.cache[filename] = size, mtime, lines, fullname |
| 139 |
|
| 140 |
|
| 141 |
class CompileCacheItem(object): |
| 142 |
pass |
| 143 |
|
| 144 |
|
| 145 |
class TemplatePreprocessor(object): |
| 146 |
''' |
| 147 |
This is used with the preprocessors argument to Template.compile(). |
| 148 |
|
| 149 |
See the docstring for Template.compile |
| 150 |
|
| 151 |
\\*\\* Preprocessors are an advanced topic \\*\\* |
| 152 |
''' |
| 153 |
|
| 154 |
def __init__(self, settings): |
| 155 |
self._settings = settings |
| 156 |
|
| 157 |
def preprocess(self, source, file): |
| 158 |
"""Create an intermediate template and return the source code |
| 159 |
it outputs |
| 160 |
""" |
| 161 |
settings = self._settings |
| 162 |
if not source: |
| 163 |
if isinstance(file, (str, unicode)): |
| 164 |
f = open(file) |
| 165 |
source = f.read() |
| 166 |
f.close() |
| 167 |
elif hasattr(file, 'read'): |
| 168 |
source = file.read() |
| 169 |
file = None |
| 170 |
|
| 171 |
templateAPIClass = settings.templateAPIClass |
| 172 |
possibleKwArgs = [ |
| 173 |
arg for arg in |
| 174 |
inspect.getargs(templateAPIClass.compile.__func__.__code__)[0] |
| 175 |
if arg not in ('klass', 'source', 'file',)] |
| 176 |
|
| 177 |
compileKwArgs = {} |
| 178 |
for arg in possibleKwArgs: |
| 179 |
if hasattr(settings, arg): |
| 180 |
compileKwArgs[arg] = getattr(settings, arg) |
| 181 |
|
| 182 |
tmplClass = templateAPIClass.compile( |
| 183 |
source=source, file=file, **compileKwArgs) |
| 184 |
tmplInstance = tmplClass(**settings.templateInitArgs) |
| 185 |
outputSource = settings.outputTransformer(tmplInstance) |
| 186 |
outputFile = None |
| 187 |
return outputSource, outputFile |
| 188 |
|
| 189 |
|
| 190 |
class Template(Servlet): |
| 191 |
''' |
| 192 |
This class provides a) methods used by templates at runtime and b) |
| 193 |
methods for compiling Cheetah source code into template classes. |
| 194 |
|
| 195 |
This documentation assumes you already know Python and the basics of object |
| 196 |
oriented programming. If you don't know Python, see the sections of the |
| 197 |
Cheetah Users' Guide for non-programmers. It also assumes you have read |
| 198 |
about Cheetah's syntax in the Users' Guide. |
| 199 |
|
| 200 |
The following explains how to use Cheetah from within Python programs or |
| 201 |
via the interpreter. If you statically compile your templates on the |
| 202 |
command line using the 'cheetah' script, this is not relevant to you. |
| 203 |
Statically compiled Cheetah template modules/classes (e.g. myTemplate.py: |
| 204 |
MyTemplateClasss) are just like any other Python module or class. Also |
| 205 |
note, most Python web frameworks (Webware, Aquarium, mod_python, |
| 206 |
Turbogears, CherryPy, Quixote, etc.) provide plugins that handle Cheetah |
| 207 |
compilation for you. |
| 208 |
|
| 209 |
There are several possible usage patterns:: |
| 210 |
|
| 211 |
1) tclass = Template.compile(src) |
| 212 |
t1 = tclass() # or tclass(namespaces=[namespace,...]) |
| 213 |
t2 = tclass() # or tclass(namespaces=[namespace2,...]) |
| 214 |
outputStr = str(t1) # or outputStr = t1.aMethodYouDefined() |
| 215 |
|
| 216 |
Template.compile provides a rich and very flexible API via its |
| 217 |
optional arguments so there are many possible variations of this |
| 218 |
pattern. One example is: |
| 219 |
tclass = Template.compile('hello $name from $caller', |
| 220 |
baseclass=dict) |
| 221 |
print(tclass(name='world', caller='me')) |
| 222 |
See the Template.compile() docstring for more details. |
| 223 |
|
| 224 |
2) tmplInstance = Template(src) |
| 225 |
# or Template(src, namespaces=[namespace,...]) |
| 226 |
outputStr = str(tmplInstance) |
| 227 |
# or outputStr = tmplInstance.aMethodYouDefined(...args...) |
| 228 |
|
| 229 |
Notes on the usage patterns:: |
| 230 |
|
| 231 |
usage pattern 1) |
| 232 |
This is the most flexible, but it is slightly more verbose unless you |
| 233 |
write a wrapper function to hide the plumbing. Under the hood, all |
| 234 |
other usage patterns are based on this approach. Templates compiled |
| 235 |
this way can #extend (subclass) any Python baseclass: old-style or |
| 236 |
new-style (based on object or a builtin type). |
| 237 |
|
| 238 |
usage pattern 2) |
| 239 |
This was Cheetah's original usage pattern. It returns an instance, |
| 240 |
but you can still access the generated class via |
| 241 |
tmplInstance.__class__. If you want to use several different |
| 242 |
namespace 'searchLists' with a single template source definition, |
| 243 |
you're better off with Template.compile (1). |
| 244 |
|
| 245 |
Limitations (use pattern 1 instead):: |
| 246 |
|
| 247 |
- Templates compiled this way can only #extend subclasses of the |
| 248 |
new-style 'object' baseclass. Cheetah.Template is a subclass of |
| 249 |
'object'. You also can not #extend dict, list, or other builtin |
| 250 |
types. |
| 251 |
- If your template baseclass' __init__ constructor expects args |
| 252 |
there is currently no way to pass them in. |
| 253 |
|
| 254 |
If you need to subclass a dynamically compiled Cheetah class, do something |
| 255 |
like this:: |
| 256 |
|
| 257 |
from Cheetah.Template import Template |
| 258 |
T1 = Template.compile('$meth1 #def meth1: this is meth1 in T1') |
| 259 |
T2 = Template.compile( |
| 260 |
'#implements meth1\\nthis is meth1 redefined in T2', baseclass=T1) |
| 261 |
print(T1, T1()) |
| 262 |
print(T2, T2()) |
| 263 |
|
| 264 |
Note about class and instance attribute names:: |
| 265 |
|
| 266 |
Attributes used by Cheetah have a special prefix to avoid confusion with |
| 267 |
the attributes of the templates themselves or those of template |
| 268 |
baseclasses. |
| 269 |
|
| 270 |
Class attributes which are used in class methods look like this:: |
| 271 |
|
| 272 |
klass._CHEETAH_useCompilationCache (_CHEETAH_xxx) |
| 273 |
|
| 274 |
Instance attributes look like this:: |
| 275 |
|
| 276 |
klass._CHEETAH__globalSetVars (_CHEETAH__xxx with 2 underscores) |
| 277 |
''' |
| 278 |
|
| 279 |
|
| 280 |
_CHEETAH_requiredCheetahMethods = ( |
| 281 |
'_initCheetahInstance', |
| 282 |
'searchList', |
| 283 |
'errorCatcher', |
| 284 |
'getVar', |
| 285 |
'varExists', |
| 286 |
'getFileContents', |
| 287 |
'i18n', |
| 288 |
'runAsMainProgram', |
| 289 |
'respond', |
| 290 |
'shutdown', |
| 291 |
'webInput', |
| 292 |
'serverSidePath', |
| 293 |
'generatedClassCode', |
| 294 |
'generatedModuleCode', |
| 295 |
|
| 296 |
'_getCacheStore', |
| 297 |
'_getCacheStoreIdPrefix', |
| 298 |
'_createCacheRegion', |
| 299 |
'getCacheRegion', |
| 300 |
'getCacheRegions', |
| 301 |
'refreshCache', |
| 302 |
|
| 303 |
'_handleCheetahInclude', |
| 304 |
'_getTemplateAPIClassForIncludeDirectiveCompilation', |
| 305 |
) |
| 306 |
_CHEETAH_requiredCheetahClassMethods = ('subclass',) |
| 307 |
_CHEETAH_requiredCheetahClassAttributes = ( |
| 308 |
'cacheRegionClass', 'cacheStore', |
| 309 |
'cacheStoreIdPrefix', 'cacheStoreClass') |
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
_CHEETAH_cacheModuleFilesForTracebacks = False |
| 314 |
_CHEETAH_cacheDirForModuleFiles = None |
| 315 |
|
| 316 |
_CHEETAH_compileCache = dict() |
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
_CHEETAH_compileLock = Lock() |
| 323 |
_CHEETAH_defaultMainMethodName = None |
| 324 |
_CHEETAH_compilerSettings = None |
| 325 |
_CHEETAH_compilerClass = Compiler |
| 326 |
_CHEETAH_compilerInstance = None |
| 327 |
_CHEETAH_cacheCompilationResults = True |
| 328 |
_CHEETAH_useCompilationCache = True |
| 329 |
_CHEETAH_keepRefToGeneratedCode = True |
| 330 |
_CHEETAH_defaultBaseclassForTemplates = None |
| 331 |
_CHEETAH_defaultClassNameForTemplates = None |
| 332 |
|
| 333 |
_CHEETAH_defaultMainMethodNameForTemplates = None |
| 334 |
_CHEETAH_defaultModuleNameForTemplates = \ |
| 335 |
'DynamicallyCompiledCheetahTemplate' |
| 336 |
_CHEETAH_defaultModuleGlobalsForTemplates = None |
| 337 |
_CHEETAH_preprocessors = None |
| 338 |
_CHEETAH_defaultPreprocessorClass = TemplatePreprocessor |
| 339 |
|
| 340 |
|
| 341 |
_CHEETAH_generatedModuleCode = None |
| 342 |
NonNumericInputError = NonNumericInputError |
| 343 |
_CHEETAH_cacheRegionClass = CacheRegion |
| 344 |
_CHEETAH_cacheStoreClass = MemoryCacheStore |
| 345 |
|
| 346 |
_CHEETAH_cacheStore = None |
| 347 |
_CHEETAH_cacheStoreIdPrefix = None |
| 348 |
|
| 349 |
@classmethod |
| 350 |
def _getCompilerClass(klass, source=None, file=None): |
| 351 |
return klass._CHEETAH_compilerClass |
| 352 |
|
| 353 |
@classmethod |
| 354 |
def _getCompilerSettings(klass, source=None, file=None): |
| 355 |
return klass._CHEETAH_compilerSettings |
| 356 |
|
| 357 |
@classmethod |
| 358 |
def compile(klass, source=None, file=None, |
| 359 |
returnAClass=True, |
| 360 |
|
| 361 |
compilerSettings=Unspecified, |
| 362 |
compilerClass=Unspecified, |
| 363 |
moduleName=None, |
| 364 |
className=Unspecified, |
| 365 |
mainMethodName=Unspecified, |
| 366 |
baseclass=Unspecified, |
| 367 |
moduleGlobals=Unspecified, |
| 368 |
cacheCompilationResults=Unspecified, |
| 369 |
useCache=Unspecified, |
| 370 |
preprocessors=Unspecified, |
| 371 |
cacheModuleFilesForTracebacks=Unspecified, |
| 372 |
cacheDirForModuleFiles=Unspecified, |
| 373 |
commandlineopts=None, |
| 374 |
keepRefToGeneratedCode=Unspecified, |
| 375 |
): |
| 376 |
|
| 377 |
""" |
| 378 |
The core API for compiling Cheetah source code into template classes. |
| 379 |
|
| 380 |
This class method compiles Cheetah source code and returns a python |
| 381 |
class. You then create template instances using that class. All |
| 382 |
Cheetah's other compilation API's use this method under the hood. |
| 383 |
|
| 384 |
Internally, this method a) parses the Cheetah source code and generates |
| 385 |
Python code defining a module with a single class in it, b) dynamically |
| 386 |
creates a module object with a unique name, c) execs the generated code |
| 387 |
in that module's namespace then inserts the module into sys.modules, |
| 388 |
and d) returns a reference to the generated class. If you want to get |
| 389 |
the generated python source code instead, pass the argument |
| 390 |
returnAClass=False. |
| 391 |
|
| 392 |
It caches generated code and classes. See the descriptions of the |
| 393 |
arguments'cacheCompilationResults' and 'useCache' for details. This |
| 394 |
doesn't mean that templates will automatically recompile themselves |
| 395 |
when the source file changes. Rather, if you call Template.compile(src) |
| 396 |
or Template.compile(file=path) repeatedly it will attempt to return a |
| 397 |
cached class definition instead of recompiling. |
| 398 |
|
| 399 |
Hooks are provided template source preprocessing. See the notes on the |
| 400 |
'preprocessors' arg. |
| 401 |
|
| 402 |
If you are an advanced user and need to customize the way Cheetah |
| 403 |
parses source code or outputs Python code, you should check out |
| 404 |
the compilerSettings argument. |
| 405 |
|
| 406 |
Arguments:: |
| 407 |
|
| 408 |
You must provide either a 'source' or 'file' arg, but not both:: |
| 409 |
|
| 410 |
- source (string or None) |
| 411 |
- file (string path, file-like object, or None) |
| 412 |
|
| 413 |
The rest of the arguments are strictly optional. All but the first |
| 414 |
have defaults in attributes of the Template class which can be |
| 415 |
overridden in subclasses of this class. Working with most of these |
| 416 |
is an advanced topic. |
| 417 |
|
| 418 |
:: |
| 419 |
|
| 420 |
- returnAClass=True |
| 421 |
If false, return the generated module code rather than a class. |
| 422 |
|
| 423 |
- compilerSettings (a dict) |
| 424 |
Default: Template._CHEETAH_compilerSettings=None |
| 425 |
|
| 426 |
a dictionary of settings to override those defined in |
| 427 |
DEFAULT_COMPILER_SETTINGS. These can also be overridden in your |
| 428 |
template source code with the #compiler or #compiler-settings |
| 429 |
directives. |
| 430 |
|
| 431 |
- compilerClass (a class) |
| 432 |
Default: Template._CHEETAH_compilerClass=Cheetah.Compiler.Compiler |
| 433 |
|
| 434 |
a subclass of Cheetah.Compiler.Compiler. Mucking with this is a |
| 435 |
very advanced topic. |
| 436 |
|
| 437 |
- moduleName (a string) |
| 438 |
Default: |
| 439 |
Template._CHEETAH_defaultModuleNameForTemplates |
| 440 |
='DynamicallyCompiledCheetahTemplate' |
| 441 |
|
| 442 |
What to name the generated Python module. If the provided value |
| 443 |
is None and a file arg was given, the moduleName is created from |
| 444 |
the file path. In all cases if the moduleName provided is |
| 445 |
already in sys.modules it is passed through a filter that |
| 446 |
generates a unique variant of the name. |
| 447 |
|
| 448 |
- className (a string) |
| 449 |
Default: Template._CHEETAH_defaultClassNameForTemplates=None |
| 450 |
|
| 451 |
What to name the generated Python class. If the provided value |
| 452 |
is None, the moduleName is use as the class name. |
| 453 |
|
| 454 |
- mainMethodName (a string) |
| 455 |
Default: |
| 456 |
Template._CHEETAH_defaultMainMethodNameForTemplates |
| 457 |
=None (and thus DEFAULT_COMPILER_SETTINGS['mainMethodName']) |
| 458 |
|
| 459 |
What to name the main output generating method in the compiled |
| 460 |
template class. |
| 461 |
|
| 462 |
- baseclass (a string or a class) |
| 463 |
Default: Template._CHEETAH_defaultBaseclassForTemplates=None |
| 464 |
|
| 465 |
Specifies the baseclass for the template without manually |
| 466 |
including an #extends directive in the source. The #extends |
| 467 |
directive trumps this arg. |
| 468 |
|
| 469 |
If the provided value is a string you must make sure that a class |
| 470 |
reference by that name is available to your template, either by |
| 471 |
using an #import directive or by providing it in the arg |
| 472 |
'moduleGlobals'. |
| 473 |
|
| 474 |
If the provided value is a class, Cheetah will handle all the |
| 475 |
details for you. |
| 476 |
|
| 477 |
- moduleGlobals (a dict) |
| 478 |
Default: Template._CHEETAH_defaultModuleGlobalsForTemplates=None |
| 479 |
|
| 480 |
A dict of vars that will be added to the global namespace of the |
| 481 |
module the generated code is executed in, prior to the execution |
| 482 |
of that code. This should be Python values, not code strings! |
| 483 |
|
| 484 |
- cacheCompilationResults (True/False) |
| 485 |
Default: Template._CHEETAH_cacheCompilationResults=True |
| 486 |
|
| 487 |
Tells Cheetah to cache the generated code and classes so that |
| 488 |
they can be reused if Template.compile() is called multiple times |
| 489 |
with the same source and options. |
| 490 |
|
| 491 |
- useCache (True/False) |
| 492 |
Default: Template._CHEETAH_useCompilationCache=True |
| 493 |
|
| 494 |
Should the compilation cache be used? If True and a previous |
| 495 |
compilation created a cached template class with the same source |
| 496 |
code, compiler settings and other options, the cached template |
| 497 |
class will be returned. |
| 498 |
|
| 499 |
- cacheModuleFilesForTracebacks (True/False) |
| 500 |
Default: Template._CHEETAH_cacheModuleFilesForTracebacks=False |
| 501 |
|
| 502 |
In earlier versions of Cheetah tracebacks from exceptions that |
| 503 |
were raised inside dynamically compiled Cheetah templates were |
| 504 |
opaque because Python didn't have access to a python source file |
| 505 |
to use in the traceback: |
| 506 |
|
| 507 |
File "xxxx.py", line 192, in getTextiledContent |
| 508 |
content = str(template(searchList=searchList)) |
| 509 |
File "cheetah_yyyy.py", line 202, in __str__ |
| 510 |
File "cheetah_yyyy.py", line 187, in respond |
| 511 |
File "cheetah_yyyy.py", line 139, in writeBody |
| 512 |
ZeroDivisionError: integer division or modulo by zero |
| 513 |
|
| 514 |
It is now possible to keep those files in a cache dir and allow |
| 515 |
Python to include the actual source lines in tracebacks and makes |
| 516 |
them much easier to understand: |
| 517 |
|
| 518 |
File "xxxx.py", line 192, in getTextiledContent |
| 519 |
content = str(template(searchList=searchList)) |
| 520 |
File "/tmp/CheetahCacheDir/cheetah_yyyy.py", line 202, in __str__ |
| 521 |
def __str__(self): return self.respond() |
| 522 |
File "/tmp/CheetahCacheDir/cheetah_yyyy.py", line 187, in respond |
| 523 |
self.writeBody(trans=trans) |
| 524 |
File "/tmp/CheetahCacheDir/cheetah_yyyy.py", line 139, in writeBody |
| 525 |
__v = 0/0 # $(0/0) |
| 526 |
ZeroDivisionError: integer division or modulo by zero |
| 527 |
|
| 528 |
- cacheDirForModuleFiles (a string representing a dir path) |
| 529 |
Default: Template._CHEETAH_cacheDirForModuleFiles=None |
| 530 |
|
| 531 |
See notes on cacheModuleFilesForTracebacks. |
| 532 |
|
| 533 |
- preprocessors |
| 534 |
Default: Template._CHEETAH_preprocessors=None |
| 535 |
|
| 536 |
** THIS IS A VERY ADVANCED TOPIC ** |
| 537 |
|
| 538 |
These are used to transform the source code prior to compilation. |
| 539 |
They provide a way to use Cheetah as a code generator for Cheetah |
| 540 |
code. In other words, you use one Cheetah template to output the |
| 541 |
source code for another Cheetah template. |
| 542 |
|
| 543 |
The major expected use cases are: |
| 544 |
|
| 545 |
a) 'compile-time caching' aka 'partial template binding', |
| 546 |
wherein an intermediate Cheetah template is used to output |
| 547 |
the source for the final Cheetah template. The intermediate |
| 548 |
template is a mix of a modified Cheetah syntax (the |
| 549 |
'preprocess syntax') and standard Cheetah syntax. The |
| 550 |
preprocessor syntax is executed at compile time and outputs |
| 551 |
Cheetah code which is then compiled in turn. This approach |
| 552 |
allows one to completely soft-code all the elements in the |
| 553 |
template which are subject to change yet have it compile to |
| 554 |
extremely efficient Python code with everything but the |
| 555 |
elements that must be variable at runtime (per browser |
| 556 |
request, etc.) compiled as static strings. Examples of this |
| 557 |
usage pattern will be added to the Cheetah Users' Guide. |
| 558 |
|
| 559 |
The'preprocess syntax' is just Cheetah's standard one with |
| 560 |
alternatives for the $ and # tokens: |
| 561 |
|
| 562 |
e.g. '@' and '%' for code like this |
| 563 |
@aPreprocessVar $aRuntimeVar |
| 564 |
%if aCompileTimeCondition then yyy else zzz |
| 565 |
%% preprocessor comment |
| 566 |
|
| 567 |
#if aRunTimeCondition then aaa else bbb |
| 568 |
## normal comment |
| 569 |
$aRuntimeVar |
| 570 |
|
| 571 |
b) adding #import and #extends directives dynamically based on |
| 572 |
the source |
| 573 |
|
| 574 |
If preprocessors are provided, Cheetah pipes the source code |
| 575 |
through each one in the order provided. Each preprocessor should |
| 576 |
accept the args (source, file) and should return a tuple (source, |
| 577 |
file). |
| 578 |
|
| 579 |
The argument value should be a list, but a single non-list value |
| 580 |
is acceptable and will automatically be converted into a list. |
| 581 |
Each item in the list will be passed through |
| 582 |
Template._normalizePreprocessor(). The items should either match |
| 583 |
one of the following forms: |
| 584 |
|
| 585 |
- an object with a .preprocess(source, file) method |
| 586 |
- a callable with the following signature: |
| 587 |
source, file = f(source, file) |
| 588 |
|
| 589 |
or one of the forms below: |
| 590 |
|
| 591 |
- a single string denoting the 2 'tokens' for the preprocess |
| 592 |
syntax. The tokens should be in the order (placeholderToken, |
| 593 |
directiveToken) and should separated with a space: |
| 594 |
e.g. '@ %' |
| 595 |
klass = Template.compile(src, preprocessors='@ %') |
| 596 |
# or |
| 597 |
klass = Template.compile(src, preprocessors=['@ %']) |
| 598 |
|
| 599 |
- a dict with the following keys or an object with the |
| 600 |
following attributes (all are optional, but nothing will |
| 601 |
happen if you don't provide at least one): |
| 602 |
- tokens: same as the single string described above. You can |
| 603 |
also provide a tuple of 2 strings. |
| 604 |
- searchList: the searchList used |
| 605 |
for preprocess $placeholders |
| 606 |
- compilerSettings: used in the compilation |
| 607 |
of the intermediate template |
| 608 |
- templateAPIClass: an optional subclass of `Template` |
| 609 |
- outputTransformer: a simple hook for passing in a callable |
| 610 |
which can do further transformations of the preprocessor |
| 611 |
output, or do something else like debug logging. The |
| 612 |
default is str(). |
| 613 |
+ any keyword arguments to Template.compile which you want |
| 614 |
to provide for the compilation |
| 615 |
of the intermediate template. |
| 616 |
|
| 617 |
klass = Template.compile( |
| 618 |
src, |
| 619 |
preprocessors=[dict(tokens='@ %', searchList=[...])]) |
| 620 |
|
| 621 |
""" |
| 622 |
errmsg = "arg '%s' must be %s" |
| 623 |
|
| 624 |
if not isinstance(source, (NoneType, string_type)): |
| 625 |
raise TypeError(errmsg % ('source', 'string or None')) |
| 626 |
|
| 627 |
if not isinstance(file, (NoneType, string_type, filetype)): |
| 628 |
raise TypeError(errmsg % |
| 629 |
('file', 'string, file-like object, or None')) |
| 630 |
|
| 631 |
if baseclass is Unspecified: |
| 632 |
baseclass = klass._CHEETAH_defaultBaseclassForTemplates |
| 633 |
if isinstance(baseclass, Template): |
| 634 |
baseclass = baseclass.__class__ |
| 635 |
|
| 636 |
if not isinstance(baseclass, (NoneType, string_type, type)): |
| 637 |
raise TypeError(errmsg % ('baseclass', 'string, class or None')) |
| 638 |
|
| 639 |
if cacheCompilationResults is Unspecified: |
| 640 |
cacheCompilationResults = klass._CHEETAH_cacheCompilationResults |
| 641 |
|
| 642 |
if not isinstance(cacheCompilationResults, (int, bool)): |
| 643 |
raise TypeError(errmsg % ('cacheCompilationResults', 'boolean')) |
| 644 |
|
| 645 |
if useCache is Unspecified: |
| 646 |
useCache = klass._CHEETAH_useCompilationCache |
| 647 |
|
| 648 |
if not isinstance(useCache, (int, bool)): |
| 649 |
raise TypeError(errmsg % ('useCache', 'boolean')) |
| 650 |
|
| 651 |
if compilerSettings is Unspecified: |
| 652 |
compilerSettings = klass._getCompilerSettings(source, file) or {} |
| 653 |
if not isinstance(compilerSettings, dict): |
| 654 |
raise TypeError(errmsg % ('compilerSettings', 'dictionary')) |
| 655 |
|
| 656 |
if compilerClass is Unspecified: |
| 657 |
compilerClass = klass._getCompilerClass(source, file) |
| 658 |
if preprocessors is Unspecified: |
| 659 |
preprocessors = klass._CHEETAH_preprocessors |
| 660 |
|
| 661 |
if keepRefToGeneratedCode is Unspecified: |
| 662 |
keepRefToGeneratedCode = klass._CHEETAH_keepRefToGeneratedCode |
| 663 |
|
| 664 |
if not isinstance(keepRefToGeneratedCode, (int, bool)): |
| 665 |
raise TypeError(errmsg % ('keepReftoGeneratedCode', 'boolean')) |
| 666 |
|
| 667 |
if not isinstance(moduleName, (NoneType, string_type)): |
| 668 |
raise TypeError(errmsg % ('moduleName', 'string or None')) |
| 669 |
__orig_file__ = None |
| 670 |
if not moduleName: |
| 671 |
if file and isinstance(file, string_type): |
| 672 |
moduleName = convertTmplPathToModuleName(file) |
| 673 |
__orig_file__ = file |
| 674 |
else: |
| 675 |
moduleName = klass._CHEETAH_defaultModuleNameForTemplates |
| 676 |
|
| 677 |
if className is Unspecified: |
| 678 |
className = klass._CHEETAH_defaultClassNameForTemplates |
| 679 |
|
| 680 |
if not isinstance(className, (NoneType, string_type)): |
| 681 |
raise TypeError(errmsg % ('className', 'string or None')) |
| 682 |
className = re.sub(r'^_+([^0-9])', r'\1', className or moduleName) |
| 683 |
|
| 684 |
if mainMethodName is Unspecified: |
| 685 |
mainMethodName = klass._CHEETAH_defaultMainMethodNameForTemplates |
| 686 |
|
| 687 |
if not isinstance(mainMethodName, (NoneType, string_type)): |
| 688 |
raise TypeError(errmsg % ('mainMethodName', 'string or None')) |
| 689 |
|
| 690 |
if moduleGlobals is Unspecified: |
| 691 |
moduleGlobals = klass._CHEETAH_defaultModuleGlobalsForTemplates |
| 692 |
|
| 693 |
if cacheModuleFilesForTracebacks is Unspecified: |
| 694 |
cacheModuleFilesForTracebacks = \ |
| 695 |
klass._CHEETAH_cacheModuleFilesForTracebacks |
| 696 |
|
| 697 |
if not isinstance(cacheModuleFilesForTracebacks, (int, bool)): |
| 698 |
raise TypeError(errmsg % |
| 699 |
('cacheModuleFilesForTracebacks', 'boolean')) |
| 700 |
|
| 701 |
if cacheDirForModuleFiles is Unspecified: |
| 702 |
cacheDirForModuleFiles = klass._CHEETAH_cacheDirForModuleFiles |
| 703 |
|
| 704 |
if not isinstance(cacheDirForModuleFiles, (NoneType, string_type)): |
| 705 |
raise TypeError(errmsg % |
| 706 |
('cacheDirForModuleFiles', 'string or None')) |
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
if preprocessors: |
| 711 |
source, file = klass._preprocessSource(source, file, preprocessors) |
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
baseclassValue = None |
| 716 |
baseclassName = None |
| 717 |
if baseclass: |
| 718 |
if isinstance(baseclass, string_type): |
| 719 |
baseclassName = baseclass |
| 720 |
elif isinstance(baseclass, type): |
| 721 |
|
| 722 |
baseclassName = \ |
| 723 |
'CHEETAH_dynamicallyAssignedBaseClass_' + \ |
| 724 |
baseclass.__name__ |
| 725 |
baseclassValue = baseclass |
| 726 |
|
| 727 |
cacheHash = None |
| 728 |
cacheItem = None |
| 729 |
if source or isinstance(file, string_type): |
| 730 |
compilerSettingsHash = None |
| 731 |
if compilerSettings: |
| 732 |
compilerSettingsHash = hashDict(compilerSettings) |
| 733 |
|
| 734 |
moduleGlobalsHash = None |
| 735 |
if moduleGlobals: |
| 736 |
moduleGlobalsHash = hashDict(moduleGlobals) |
| 737 |
|
| 738 |
fileHash = None |
| 739 |
if file: |
| 740 |
fileHash = str(hash(file)) |
| 741 |
if globals()['__checkFileMtime']: |
| 742 |
fileHash += str(os.path.getmtime(file)) |
| 743 |
|
| 744 |
try: |
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
cacheHash = ''.join([str(v) for v in |
| 751 |
[hash(source), |
| 752 |
fileHash, |
| 753 |
className, |
| 754 |
moduleName, |
| 755 |
mainMethodName, |
| 756 |
hash(compilerClass), |
| 757 |
hash(baseclass), |
| 758 |
compilerSettingsHash, |
| 759 |
moduleGlobalsHash, |
| 760 |
hash(cacheDirForModuleFiles), |
| 761 |
]]) |
| 762 |
except Exception: |
| 763 |
|
| 764 |
pass |
| 765 |
outputEncoding = 'ascii' |
| 766 |
compiler = None |
| 767 |
if useCache and cacheHash and cacheHash in klass._CHEETAH_compileCache: |
| 768 |
cacheItem = klass._CHEETAH_compileCache[cacheHash] |
| 769 |
generatedModuleCode = cacheItem.code |
| 770 |
else: |
| 771 |
compiler = compilerClass(source, file, |
| 772 |
moduleName=moduleName, |
| 773 |
mainClassName=className, |
| 774 |
baseclassName=baseclassName, |
| 775 |
mainMethodName=mainMethodName, |
| 776 |
settings=(compilerSettings or {})) |
| 777 |
if commandlineopts: |
| 778 |
compiler.setShBang(commandlineopts.shbang) |
| 779 |
compiler.compile() |
| 780 |
generatedModuleCode = compiler.getModuleCode() |
| 781 |
outputEncoding = compiler.getModuleEncoding() |
| 782 |
|
| 783 |
if not returnAClass: |
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
if not outputEncoding == 'ascii': |
| 788 |
generatedModuleCode = generatedModuleCode.split('\n') |
| 789 |
generatedModuleCode.insert( |
| 790 |
1, '# -*- coding: %s -*-' % outputEncoding) |
| 791 |
generatedModuleCode = '\n'.join(generatedModuleCode) |
| 792 |
return generatedModuleCode.encode(outputEncoding) |
| 793 |
else: |
| 794 |
if cacheItem: |
| 795 |
cacheItem.lastCheckoutTime = time.time() |
| 796 |
return cacheItem.klass |
| 797 |
|
| 798 |
try: |
| 799 |
klass._CHEETAH_compileLock.acquire() |
| 800 |
uniqueModuleName = _genUniqueModuleName(moduleName) |
| 801 |
|
| 802 |
__file__ = uniqueModuleName + '.py' |
| 803 |
|
| 804 |
if cacheModuleFilesForTracebacks: |
| 805 |
if not os.path.exists(cacheDirForModuleFiles): |
| 806 |
raise Exception('%s does not exist' |
| 807 |
% cacheDirForModuleFiles) |
| 808 |
|
| 809 |
__file__ = os.path.join(cacheDirForModuleFiles, __file__) |
| 810 |
|
| 811 |
open(__file__, 'w').write(generatedModuleCode) |
| 812 |
|
| 813 |
|
| 814 |
mod = types.ModuleType(str(uniqueModuleName)) |
| 815 |
if moduleGlobals: |
| 816 |
for k, v in moduleGlobals.items(): |
| 817 |
setattr(mod, k, v) |
| 818 |
mod.__file__ = __file__ |
| 819 |
if __orig_file__ and os.path.exists(__orig_file__): |
| 820 |
|
| 821 |
mod.__orig_file__ = __orig_file__ |
| 822 |
|
| 823 |
if baseclass and baseclassValue: |
| 824 |
setattr(mod, baseclassName, baseclassValue) |
| 825 |
|
| 826 |
try: |
| 827 |
co = compile(generatedModuleCode, __file__, 'exec') |
| 828 |
exec(co, mod.__dict__) |
| 829 |
except SyntaxError as e: |
| 830 |
try: |
| 831 |
parseError = genParserErrorFromPythonException( |
| 832 |
source, file, generatedModuleCode, exception=e) |
| 833 |
except Exception: |
| 834 |
updateLinecache(__file__, generatedModuleCode) |
| 835 |
e.generatedModuleCode = generatedModuleCode |
| 836 |
raise e |
| 837 |
else: |
| 838 |
raise parseError |
| 839 |
except Exception as e: |
| 840 |
updateLinecache(__file__, generatedModuleCode) |
| 841 |
e.generatedModuleCode = generatedModuleCode |
| 842 |
raise |
| 843 |
|
| 844 |
sys.modules[uniqueModuleName] = mod |
| 845 |
finally: |
| 846 |
klass._CHEETAH_compileLock.release() |
| 847 |
|
| 848 |
templateClass = getattr(mod, className) |
| 849 |
|
| 850 |
if (cacheCompilationResults and cacheHash |
| 851 |
and cacheHash not in klass._CHEETAH_compileCache): |
| 852 |
cacheItem = CompileCacheItem() |
| 853 |
cacheItem.cacheTime = cacheItem.lastCheckoutTime = time.time() |
| 854 |
cacheItem.code = generatedModuleCode |
| 855 |
cacheItem.klass = templateClass |
| 856 |
templateClass._CHEETAH_isInCompilationCache = True |
| 857 |
klass._CHEETAH_compileCache[cacheHash] = cacheItem |
| 858 |
else: |
| 859 |
templateClass._CHEETAH_isInCompilationCache = False |
| 860 |
|
| 861 |
if keepRefToGeneratedCode or cacheCompilationResults: |
| 862 |
templateClass._CHEETAH_generatedModuleCode = \ |
| 863 |
generatedModuleCode |
| 864 |
|
| 865 |
|
| 866 |
|
| 867 |
if compiler: |
| 868 |
templateClass._CHEETAH_compilerInstance = compiler |
| 869 |
return templateClass |
| 870 |
|
| 871 |
@classmethod |
| 872 |
def subclass(klass, *args, **kws): |
| 873 |
"""Takes the same args as the .compile() classmethod and returns a |
| 874 |
template that is a subclass of the template this method is called from. |
| 875 |
|
| 876 |
T1 = Template.compile( |
| 877 |
'foo - $meth1 - bar\\n#def meth1: this is T1.meth1') |
| 878 |
T2 = T1.subclass('#implements meth1\\n this is T2.meth1') |
| 879 |
""" |
| 880 |
kws['baseclass'] = klass |
| 881 |
if isinstance(klass, Template): |
| 882 |
templateAPIClass = klass |
| 883 |
else: |
| 884 |
templateAPIClass = Template |
| 885 |
return templateAPIClass.compile(*args, **kws) |
| 886 |
|
| 887 |
@classmethod |
| 888 |
def _preprocessSource(klass, source, file, preprocessors): |
| 889 |
"""Iterates through the .compile() classmethod's preprocessors argument |
| 890 |
and pipes the source code through each each preprocessor. |
| 891 |
|
| 892 |
It returns the tuple (source, file) which is then used by |
| 893 |
Template.compile to finish the compilation. |
| 894 |
""" |
| 895 |
if not isinstance(preprocessors, (list, tuple)): |
| 896 |
preprocessors = [preprocessors] |
| 897 |
for preprocessor in preprocessors: |
| 898 |
preprocessor = klass._normalizePreprocessorArg(preprocessor) |
| 899 |
source, file = preprocessor.preprocess(source, file) |
| 900 |
return source, file |
| 901 |
|
| 902 |
@classmethod |
| 903 |
def _normalizePreprocessorArg(klass, arg): |
| 904 |
"""Used to convert the items in the .compile() classmethod's |
| 905 |
preprocessors argument into real source preprocessors. |
| 906 |
This permits the use of several shortcut forms |
| 907 |
for defining preprocessors. |
| 908 |
""" |
| 909 |
if hasattr(arg, 'preprocess'): |
| 910 |
return arg |
| 911 |
elif callable(arg): |
| 912 |
class WrapperPreprocessor: |
| 913 |
def preprocess(self, source, file): |
| 914 |
return arg(source, file) |
| 915 |
return WrapperPreprocessor() |
| 916 |
else: |
| 917 |
class Settings(object): |
| 918 |
placeholderToken = None |
| 919 |
directiveToken = None |
| 920 |
settings = Settings() |
| 921 |
if isinstance(arg, str) or isinstance(arg, (list, tuple)): |
| 922 |
settings.tokens = arg |
| 923 |
elif isinstance(arg, dict): |
| 924 |
for k, v in arg.items(): |
| 925 |
setattr(settings, k, v) |
| 926 |
else: |
| 927 |
settings = arg |
| 928 |
|
| 929 |
settings = klass._normalizePreprocessorSettings(settings) |
| 930 |
return klass._CHEETAH_defaultPreprocessorClass(settings) |
| 931 |
|
| 932 |
@classmethod |
| 933 |
def _normalizePreprocessorSettings(klass, settings): |
| 934 |
settings.keepRefToGeneratedCode = True |
| 935 |
|
| 936 |
def normalizeSearchList(searchList): |
| 937 |
if not isinstance(searchList, (list, tuple)): |
| 938 |
searchList = [searchList] |
| 939 |
return searchList |
| 940 |
|
| 941 |
def normalizeTokens(tokens): |
| 942 |
if isinstance(tokens, str): |
| 943 |
return tokens.split() |
| 944 |
elif isinstance(tokens, (list, tuple)): |
| 945 |
return tokens |
| 946 |
else: |
| 947 |
raise PreprocessError('invalid tokens argument: %r' % tokens) |
| 948 |
|
| 949 |
if hasattr(settings, 'tokens'): |
| 950 |
(settings.placeholderToken, |
| 951 |
settings.directiveToken) = normalizeTokens(settings.tokens) |
| 952 |
|
| 953 |
if (not getattr(settings, 'compilerSettings', None) |
| 954 |
and not getattr(settings, 'placeholderToken', None)): |
| 955 |
raise TypeError( |
| 956 |
'Preprocessor requires either a "tokens" ' |
| 957 |
'or a "compilerSettings" arg. Neither was provided.') |
| 958 |
|
| 959 |
if not hasattr(settings, 'templateInitArgs'): |
| 960 |
settings.templateInitArgs = {} |
| 961 |
if 'searchList' not in settings.templateInitArgs: |
| 962 |
if not hasattr(settings, 'searchList') \ |
| 963 |
and hasattr(settings, 'namespaces'): |
| 964 |
settings.searchList = settings.namespaces |
| 965 |
elif not hasattr(settings, 'searchList'): |
| 966 |
settings.searchList = [] |
| 967 |
settings.templateInitArgs['searchList'] = settings.searchList |
| 968 |
settings.templateInitArgs['searchList'] = ( |
| 969 |
normalizeSearchList(settings.templateInitArgs['searchList'])) |
| 970 |
|
| 971 |
if not hasattr(settings, 'outputTransformer'): |
| 972 |
settings.outputTransformer = unicode |
| 973 |
|
| 974 |
if not hasattr(settings, 'templateAPIClass'): |
| 975 |
class PreprocessTemplateAPIClass(klass): |
| 976 |
pass |
| 977 |
settings.templateAPIClass = PreprocessTemplateAPIClass |
| 978 |
|
| 979 |
if not hasattr(settings, 'compilerSettings'): |
| 980 |
settings.compilerSettings = {} |
| 981 |
|
| 982 |
klass._updateSettingsWithPreprocessTokens( |
| 983 |
compilerSettings=settings.compilerSettings, |
| 984 |
placeholderToken=settings.placeholderToken, |
| 985 |
directiveToken=settings.directiveToken |
| 986 |
) |
| 987 |
return settings |
| 988 |
|
| 989 |
@classmethod |
| 990 |
def _updateSettingsWithPreprocessTokens( |
| 991 |
klass, compilerSettings, placeholderToken, directiveToken): |
| 992 |
|
| 993 |
if (placeholderToken |
| 994 |
and 'cheetahVarStartToken' not in compilerSettings): |
| 995 |
compilerSettings['cheetahVarStartToken'] = placeholderToken |
| 996 |
if directiveToken: |
| 997 |
if 'directiveStartToken' not in compilerSettings: |
| 998 |
compilerSettings['directiveStartToken'] = directiveToken |
| 999 |
if 'directiveEndToken' not in compilerSettings: |
| 1000 |
compilerSettings['directiveEndToken'] = directiveToken |
| 1001 |
if 'commentStartToken' not in compilerSettings: |
| 1002 |
compilerSettings['commentStartToken'] = directiveToken*2 |
| 1003 |
if 'multiLineCommentStartToken' not in compilerSettings: |
| 1004 |
compilerSettings['multiLineCommentStartToken'] = ( |
| 1005 |
directiveToken + '*') |
| 1006 |
if 'multiLineCommentEndToken' not in compilerSettings: |
| 1007 |
compilerSettings['multiLineCommentEndToken'] = ( |
| 1008 |
'*' + directiveToken) |
| 1009 |
if 'EOLSlurpToken' not in compilerSettings: |
| 1010 |
compilerSettings['EOLSlurpToken'] = directiveToken |
| 1011 |
|
| 1012 |
@classmethod |
| 1013 |
def _addCheetahPlumbingCodeToClass(klass, concreteTemplateClass): |
| 1014 |
"""If concreteTemplateClass is not a subclass of Cheetah.Template, add |
| 1015 |
the required cheetah methods and attributes to it. |
| 1016 |
|
| 1017 |
This is called on each new template class after it has been compiled. |
| 1018 |
If concreteTemplateClass is not a subclass of Cheetah.Template but |
| 1019 |
already has method with the same name as one of the required cheetah |
| 1020 |
methods, this will skip that method. |
| 1021 |
""" |
| 1022 |
for methodname in klass._CHEETAH_requiredCheetahMethods: |
| 1023 |
if not hasattr(concreteTemplateClass, methodname): |
| 1024 |
method = getattr(Template, methodname) |
| 1025 |
newMethod = createMethod( |
| 1026 |
getattr(method, '__func__', method), concreteTemplateClass) |
| 1027 |
setattr(concreteTemplateClass, methodname, newMethod) |
| 1028 |
|
| 1029 |
for classMethName in klass._CHEETAH_requiredCheetahClassMethods: |
| 1030 |
if not hasattr(concreteTemplateClass, classMethName): |
| 1031 |
meth = getattr(klass, classMethName) |
| 1032 |
setattr(concreteTemplateClass, classMethName, |
| 1033 |
classmethod(meth.__func__)) |
| 1034 |
|
| 1035 |
for attrname in klass._CHEETAH_requiredCheetahClassAttributes: |
| 1036 |
attrname = '_CHEETAH_' + attrname |
| 1037 |
if not hasattr(concreteTemplateClass, attrname): |
| 1038 |
attrVal = getattr(klass, attrname) |
| 1039 |
setattr(concreteTemplateClass, attrname, attrVal) |
| 1040 |
|
| 1041 |
if (not hasattr(concreteTemplateClass, '__str__') |
| 1042 |
or concreteTemplateClass.__str__ == object.__str__): |
| 1043 |
mainMethNameAttr = '_mainCheetahMethod_for_' \ |
| 1044 |
+ concreteTemplateClass.__name__ |
| 1045 |
mainMethName = getattr(concreteTemplateClass, |
| 1046 |
mainMethNameAttr, None) |
| 1047 |
if mainMethName: |
| 1048 |
def __str__(self): |
| 1049 |
rc = getattr(self, mainMethName)() |
| 1050 |
if PY2 and isinstance(rc, unicode): |
| 1051 |
return rc.encode('utf-8') |
| 1052 |
if not PY2 and isinstance(rc, bytes): |
| 1053 |
return rc.decode('utf-8') |
| 1054 |
return rc |
| 1055 |
|
| 1056 |
def __unicode__(self): |
| 1057 |
return getattr(self, mainMethName)() |
| 1058 |
elif (hasattr(concreteTemplateClass, 'respond') |
| 1059 |
and concreteTemplateClass.respond != Servlet.respond): |
| 1060 |
def __str__(self): |
| 1061 |
rc = self.respond() |
| 1062 |
if PY2 and isinstance(rc, unicode): |
| 1063 |
return rc.encode('utf-8') |
| 1064 |
if not PY2 and isinstance(rc, bytes): |
| 1065 |
return rc.decode('utf-8') |
| 1066 |
return rc |
| 1067 |
|
| 1068 |
def __unicode__(self): |
| 1069 |
return self.respond() |
| 1070 |
else: |
| 1071 |
def __str__(self): |
| 1072 |
rc = None |
| 1073 |
if hasattr(self, mainMethNameAttr): |
| 1074 |
rc = getattr(self, mainMethNameAttr)() |
| 1075 |
elif hasattr(self, 'respond'): |
| 1076 |
rc = self.respond() |
| 1077 |
else: |
| 1078 |
rc = super(self.__class__, self).__str__() |
| 1079 |
if PY2 and isinstance(rc, unicode): |
| 1080 |
return rc.encode('utf-8') |
| 1081 |
if not PY2 and isinstance(rc, bytes): |
| 1082 |
return rc.decode('utf-8') |
| 1083 |
return rc |
| 1084 |
|
| 1085 |
def __unicode__(self): |
| 1086 |
if hasattr(self, mainMethNameAttr): |
| 1087 |
return getattr(self, mainMethNameAttr)() |
| 1088 |
elif hasattr(self, 'respond'): |
| 1089 |
return self.respond() |
| 1090 |
else: |
| 1091 |
return super(self.__class__, self).__unicode__() |
| 1092 |
|
| 1093 |
if not PY2: |
| 1094 |
__str__ = __unicode__ |
| 1095 |
__str__ = createMethod(__str__, concreteTemplateClass) |
| 1096 |
__unicode__ = createMethod(__unicode__, concreteTemplateClass) |
| 1097 |
setattr(concreteTemplateClass, '__str__', __str__) |
| 1098 |
setattr(concreteTemplateClass, '__unicode__', __unicode__) |
| 1099 |
|
| 1100 |
def __init__(self, source=None, |
| 1101 |
|
| 1102 |
namespaces=None, searchList=None, |
| 1103 |
|
| 1104 |
|
| 1105 |
file=None, |
| 1106 |
|
| 1107 |
filter='RawOrEncodedUnicode', |
| 1108 |
filtersLib=Filters, |
| 1109 |
errorCatcher=None, |
| 1110 |
|
| 1111 |
|
| 1112 |
compilerSettings=Unspecified, |
| 1113 |
|
| 1114 |
_globalSetVars=None, |
| 1115 |
|
| 1116 |
_preBuiltSearchList=None |
| 1117 |
): |
| 1118 |
"""a) compiles a new template OR b) instantiates an existing template. |
| 1119 |
|
| 1120 |
Read this docstring carefully as there are two distinct usage patterns. |
| 1121 |
You should also read this class' main docstring. |
| 1122 |
|
| 1123 |
a) to compile a new template:: |
| 1124 |
|
| 1125 |
t = Template(source=aSourceString) |
| 1126 |
# or |
| 1127 |
t = Template(file='some/path') |
| 1128 |
# or |
| 1129 |
t = Template(file=someFileObject) |
| 1130 |
# or |
| 1131 |
namespaces = [{'foo':'bar'}] |
| 1132 |
t = Template(source=aSourceString, namespaces=namespaces) |
| 1133 |
# or |
| 1134 |
t = Template(file='some/path', namespaces=namespaces) |
| 1135 |
|
| 1136 |
print(t) |
| 1137 |
|
| 1138 |
b) to create an instance of an existing, precompiled template class:: |
| 1139 |
|
| 1140 |
## i) first you need a reference to a compiled template class: |
| 1141 |
|
| 1142 |
tclass = Template.compile(source=src) |
| 1143 |
# or just Template.compile(src) |
| 1144 |
# or |
| 1145 |
tclass = Template.compile(file='some/path') |
| 1146 |
# or |
| 1147 |
tclass = Template.compile(file=someFileObject) |
| 1148 |
# or |
| 1149 |
# if you used the command line compiler |
| 1150 |
# or have Cheetah's ImportHooks installed |
| 1151 |
# your template class is also available via Python's |
| 1152 |
# standard import mechanism: |
| 1153 |
from ACompileTemplate import AcompiledTemplate as tclass |
| 1154 |
|
| 1155 |
## ii) then you create an instance |
| 1156 |
t = tclass(namespaces=namespaces) |
| 1157 |
# or |
| 1158 |
t = tclass(namespaces=namespaces, filter='RawOrEncodedUnicode') |
| 1159 |
print(t) |
| 1160 |
|
| 1161 |
Arguments:: |
| 1162 |
|
| 1163 |
for usage pattern a) |
| 1164 |
If you are compiling a new template, you must provide either a |
| 1165 |
'source' or 'file' arg, but not both: |
| 1166 |
- source (string or None) |
| 1167 |
- file (string path, file-like object, or None) |
| 1168 |
|
| 1169 |
Optional args (see below for more) : |
| 1170 |
- compilerSettings |
| 1171 |
Default: Template._CHEETAH_compilerSettings=None |
| 1172 |
|
| 1173 |
a dictionary of settings to override those defined in |
| 1174 |
DEFAULT_COMPILER_SETTINGS. See |
| 1175 |
Cheetah.Template.DEFAULT_COMPILER_SETTINGS and the Users' Guide |
| 1176 |
for details. |
| 1177 |
|
| 1178 |
You can pass the source arg in as a positional arg with this usage |
| 1179 |
pattern. Use keywords for all other args. |
| 1180 |
|
| 1181 |
for usage pattern b) |
| 1182 |
Do not use positional args with this usage pattern, unless your |
| 1183 |
template subclasses something other than Cheetah.Template and you |
| 1184 |
want to pass positional args to that baseclass. E.g.: |
| 1185 |
dictTemplate = Template.compile('hello $name from $caller', |
| 1186 |
baseclass=dict) |
| 1187 |
tmplvars = dict(name='world', caller='me') |
| 1188 |
print(dictTemplate(tmplvars)) |
| 1189 |
This usage requires all Cheetah args to be passed in |
| 1190 |
as keyword args. |
| 1191 |
|
| 1192 |
optional args for both usage patterns: |
| 1193 |
|
| 1194 |
- namespaces (aka 'searchList') |
| 1195 |
Default: None |
| 1196 |
|
| 1197 |
an optional list of namespaces (dictionaries, objects, modules, |
| 1198 |
etc.) which Cheetah will search through to find the variables |
| 1199 |
referenced in $placeholders. |
| 1200 |
|
| 1201 |
If you provide a single namespace instead of a list, Cheetah will |
| 1202 |
automatically convert it into a list. |
| 1203 |
|
| 1204 |
NOTE: Cheetah does NOT force you to use the namespaces |
| 1205 |
search list and related features. It's on by default, |
| 1206 |
but you can turn if off using the compiler settings |
| 1207 |
useSearchList=False or useNameMapper=False. |
| 1208 |
|
| 1209 |
- filter |
| 1210 |
Default: 'EncodeUnicode' |
| 1211 |
|
| 1212 |
Which filter should be used for output filtering. This should |
| 1213 |
either be a string which is the name of a filter in the |
| 1214 |
'filtersLib' or a subclass of Cheetah.Filters.Filter. . See the |
| 1215 |
Users' Guide for more details. |
| 1216 |
|
| 1217 |
- filtersLib |
| 1218 |
Default: Cheetah.Filters |
| 1219 |
|
| 1220 |
A module containing subclasses of Cheetah.Filters.Filter. |
| 1221 |
See the Users' Guide for more details. |
| 1222 |
|
| 1223 |
- errorCatcher |
| 1224 |
Default: None |
| 1225 |
|
| 1226 |
This is a debugging tool. See the Users' Guide for more details. |
| 1227 |
Do not use this or the #errorCatcher diretive with live |
| 1228 |
production systems. |
| 1229 |
|
| 1230 |
Do NOT mess with the args _globalSetVars or _preBuiltSearchList! |
| 1231 |
""" |
| 1232 |
errmsg = "arg '%s' must be %s" |
| 1233 |
errmsgextra = errmsg + "\n%s" |
| 1234 |
|
| 1235 |
if not isinstance(source, (NoneType, string_type)): |
| 1236 |
raise TypeError(errmsg % ('source', 'string or None')) |
| 1237 |
|
| 1238 |
if not isinstance(file, (NoneType, string_type, filetype)): |
| 1239 |
raise TypeError(errmsg % |
| 1240 |
('file', 'string, file open for reading, or None')) |
| 1241 |
|
| 1242 |
if not isinstance(filter, (string_type, type)) \ |
| 1243 |
and not (isinstance(filter, type) |
| 1244 |
and issubclass(filter, Filters.Filter)): |
| 1245 |
raise TypeError(errmsgextra % |
| 1246 |
('filter', 'string or class', |
| 1247 |
'(if class, must be subclass ' |
| 1248 |
'of Cheetah.Filters.Filter)')) |
| 1249 |
if not isinstance(filtersLib, (string_type, types.ModuleType)): |
| 1250 |
raise TypeError(errmsgextra % |
| 1251 |
('filtersLib', 'string or module', |
| 1252 |
'(if module, must contain subclasses ' |
| 1253 |
'of Cheetah.Filters.Filter)')) |
| 1254 |
|
| 1255 |
if errorCatcher is not None: |
| 1256 |
err = True |
| 1257 |
if isinstance(errorCatcher, (string_type, type)): |
| 1258 |
err = False |
| 1259 |
if isinstance(errorCatcher, type) and \ |
| 1260 |
issubclass(errorCatcher, ErrorCatchers.ErrorCatcher): |
| 1261 |
err = False |
| 1262 |
if err: |
| 1263 |
raise TypeError( |
| 1264 |
errmsgextra % ('errorCatcher', 'string, class or None', |
| 1265 |
'(if class, must be subclass of ' |
| 1266 |
'Cheetah.ErrorCatchers.ErrorCatcher)')) |
| 1267 |
if compilerSettings is not Unspecified: |
| 1268 |
if not isinstance(compilerSettings, dict): |
| 1269 |
raise TypeError(errmsg % |
| 1270 |
('compilerSettings', 'dictionary')) |
| 1271 |
|
| 1272 |
if source is not None and file is not None: |
| 1273 |
raise TypeError("you must supply either a source string or the" |
| 1274 |
+ " 'file' keyword argument, but not both") |
| 1275 |
|
| 1276 |
|
| 1277 |
|
| 1278 |
super(Template, self).__init__() |
| 1279 |
|
| 1280 |
|
| 1281 |
|
| 1282 |
if not hasattr(self, '_CHEETAH_versionTuple'): |
| 1283 |
try: |
| 1284 |
mod = sys.modules[self.__class__.__module__] |
| 1285 |
compiledVersion = mod.__CHEETAH_version__ |
| 1286 |
compiledVersionTuple = \ |
| 1287 |
convertVersionStringToTuple(compiledVersion) |
| 1288 |
if compiledVersionTuple < MinCompatibleVersionTuple: |
| 1289 |
raise AssertionError( |
| 1290 |
'This template was compiled with Cheetah version %s.' |
| 1291 |
'Templates compiled before version %s ' |
| 1292 |
'must be recompiled.' |
| 1293 |
% (compiledVersion, MinCompatibleVersion)) |
| 1294 |
except AssertionError: |
| 1295 |
raise |
| 1296 |
except Exception: |
| 1297 |
pass |
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
if searchList: |
| 1303 |
for namespace in searchList: |
| 1304 |
if isinstance(namespace, dict): |
| 1305 |
intersection = self.Reserved_SearchList \ |
| 1306 |
& set(namespace.keys()) |
| 1307 |
warn = False |
| 1308 |
if intersection: |
| 1309 |
warn = True |
| 1310 |
if isinstance(compilerSettings, dict) and \ |
| 1311 |
compilerSettings.get( |
| 1312 |
'prioritizeSearchListOverSelf'): |
| 1313 |
warn = False |
| 1314 |
if warn: |
| 1315 |
logging.info( |
| 1316 |
''' The following keys are members ''' |
| 1317 |
'''of the Template class and will result ''' |
| 1318 |
'''in NameMapper collisions! ''') |
| 1319 |
logging.info( |
| 1320 |
''' > %s ''' % ', '.join(list(intersection))) |
| 1321 |
logging.info( |
| 1322 |
''' Please change the key's name ''' |
| 1323 |
'''or use the compiler setting ''' |
| 1324 |
'''"prioritizeSearchListOverSelf=True" ''' |
| 1325 |
'''to prevent the NameMapper from using ''') |
| 1326 |
logging.info( |
| 1327 |
''' the Template member in place of ''' |
| 1328 |
'''your searchList variable ''') |
| 1329 |
|
| 1330 |
self._initCheetahInstance( |
| 1331 |
searchList=searchList, namespaces=namespaces, |
| 1332 |
filter=filter, filtersLib=filtersLib, |
| 1333 |
errorCatcher=errorCatcher, |
| 1334 |
_globalSetVars=_globalSetVars, |
| 1335 |
compilerSettings=compilerSettings, |
| 1336 |
_preBuiltSearchList=_preBuiltSearchList) |
| 1337 |
|
| 1338 |
|
| 1339 |
|
| 1340 |
if (source is not None) or (file is not None): |
| 1341 |
self._compile(source, file, compilerSettings=compilerSettings) |
| 1342 |
|
| 1343 |
def generatedModuleCode(self): |
| 1344 |
"""Return the module code the compiler generated, or None if no |
| 1345 |
compilation took place. |
| 1346 |
""" |
| 1347 |
|
| 1348 |
return self._CHEETAH_generatedModuleCode |
| 1349 |
|
| 1350 |
def generatedClassCode(self): |
| 1351 |
"""Return the class code the compiler generated, or None if no |
| 1352 |
compilation took place. |
| 1353 |
""" |
| 1354 |
|
| 1355 |
return self._CHEETAH_generatedModuleCode[ |
| 1356 |
self._CHEETAH_generatedModuleCode.find('\nclass '): |
| 1357 |
self._CHEETAH_generatedModuleCode.find( |
| 1358 |
'\n## END CLASS DEFINITION')] |
| 1359 |
|
| 1360 |
def searchList(self): |
| 1361 |
"""Return a reference to the searchlist |
| 1362 |
""" |
| 1363 |
return self._CHEETAH__searchList |
| 1364 |
|
| 1365 |
def errorCatcher(self): |
| 1366 |
"""Return a reference to the current errorCatcher |
| 1367 |
""" |
| 1368 |
return self._CHEETAH__errorCatcher |
| 1369 |
|
| 1370 |
|
| 1371 |
def _getCacheStore(self): |
| 1372 |
if not self._CHEETAH__cacheStore: |
| 1373 |
if self._CHEETAH_cacheStore is not None: |
| 1374 |
self._CHEETAH__cacheStore = self._CHEETAH_cacheStore |
| 1375 |
else: |
| 1376 |
|
| 1377 |
self._CHEETAH__cacheStore = self._CHEETAH_cacheStoreClass() |
| 1378 |
|
| 1379 |
return self._CHEETAH__cacheStore |
| 1380 |
|
| 1381 |
def _getCacheStoreIdPrefix(self): |
| 1382 |
if self._CHEETAH_cacheStoreIdPrefix is not None: |
| 1383 |
return self._CHEETAH_cacheStoreIdPrefix |
| 1384 |
else: |
| 1385 |
return str(id(self)) |
| 1386 |
|
| 1387 |
def _createCacheRegion(self, regionID): |
| 1388 |
return self._CHEETAH_cacheRegionClass( |
| 1389 |
regionID=regionID, |
| 1390 |
templateCacheIdPrefix=self._getCacheStoreIdPrefix(), |
| 1391 |
cacheStore=self._getCacheStore()) |
| 1392 |
|
| 1393 |
def getCacheRegion(self, regionID, cacheInfo=None, create=True): |
| 1394 |
cacheRegion = self._CHEETAH__cacheRegions.get(regionID) |
| 1395 |
if not cacheRegion and create: |
| 1396 |
cacheRegion = self._createCacheRegion(regionID) |
| 1397 |
self._CHEETAH__cacheRegions[regionID] = cacheRegion |
| 1398 |
return cacheRegion |
| 1399 |
|
| 1400 |
def getCacheRegions(self): |
| 1401 |
"""Returns a dictionary of the 'cache regions' initialized in a |
| 1402 |
template. |
| 1403 |
|
| 1404 |
Each #cache directive block or $*cachedPlaceholder is a separate 'cache |
| 1405 |
region'. |
| 1406 |
""" |
| 1407 |
|
| 1408 |
return self._CHEETAH__cacheRegions.copy() |
| 1409 |
|
| 1410 |
def refreshCache(self, cacheRegionId=None, cacheItemId=None): |
| 1411 |
"""Refresh a cache region or a specific cache item within a region. |
| 1412 |
""" |
| 1413 |
|
| 1414 |
if not cacheRegionId: |
| 1415 |
for cacheRegion in self.getCacheRegions().values(): |
| 1416 |
cacheRegion.clear() |
| 1417 |
else: |
| 1418 |
cregion = self._CHEETAH__cacheRegions.get(cacheRegionId) |
| 1419 |
if not cregion: |
| 1420 |
return |
| 1421 |
if not cacheItemId: |
| 1422 |
|
| 1423 |
cregion.clear() |
| 1424 |
else: |
| 1425 |
cache = cregion.getCacheItem(cacheItemId) |
| 1426 |
if cache: |
| 1427 |
cache.clear() |
| 1428 |
|
| 1429 |
|
| 1430 |
|
| 1431 |
def shutdown(self): |
| 1432 |
"""Break reference cycles before discarding a servlet. |
| 1433 |
""" |
| 1434 |
try: |
| 1435 |
Servlet.shutdown(self) |
| 1436 |
except Exception: |
| 1437 |
pass |
| 1438 |
self._CHEETAH__searchList = None |
| 1439 |
self.__dict__ = {} |
| 1440 |
|
| 1441 |
|
| 1442 |
|
| 1443 |
def getVar(self, varName, default=Unspecified, autoCall=True): |
| 1444 |
"""Get a variable from the searchList. If the variable can't be found |
| 1445 |
in the searchList, it returns the default value if one was given, or |
| 1446 |
raises NameMapper.NotFound. |
| 1447 |
""" |
| 1448 |
|
| 1449 |
try: |
| 1450 |
return valueFromSearchList( |
| 1451 |
self.searchList(), varName.replace('$', ''), autoCall) |
| 1452 |
except NotFound: |
| 1453 |
if default is not Unspecified: |
| 1454 |
return default |
| 1455 |
else: |
| 1456 |
raise |
| 1457 |
|
| 1458 |
def varExists(self, varName, autoCall=True): |
| 1459 |
"""Test if a variable name exists in the searchList. |
| 1460 |
""" |
| 1461 |
try: |
| 1462 |
valueFromSearchList(self.searchList(), |
| 1463 |
varName.replace('$', ''), autoCall) |
| 1464 |
return True |
| 1465 |
except NotFound: |
| 1466 |
return False |
| 1467 |
|
| 1468 |
hasVar = varExists |
| 1469 |
|
| 1470 |
def i18n(self, message, |
| 1471 |
plural=None, |
| 1472 |
n=None, |
| 1473 |
id=None, |
| 1474 |
domain=None, |
| 1475 |
source=None, |
| 1476 |
target=None, |
| 1477 |
comment=None |
| 1478 |
): |
| 1479 |
"""This is just a stub at this time. |
| 1480 |
|
| 1481 |
:: |
| 1482 |
|
| 1483 |
plural = the plural form of the message |
| 1484 |
n = a sized argument to distinguish |
| 1485 |
between single and plural forms |
| 1486 |
id = msgid in the translation catalog |
| 1487 |
domain = translation domain |
| 1488 |
source = source lang |
| 1489 |
target = a specific target lang |
| 1490 |
comment = a comment to the translation team |
| 1491 |
|
| 1492 |
See the following for some ideas |
| 1493 |
http://www.zope.org/DevHome/Wikis/DevSite/Projects/ComponentArchitecture/ZPTInternationalizationSupport |
| 1494 |
|
| 1495 |
Other notes:: |
| 1496 |
|
| 1497 |
- There is no need to replicate the i18n:name attribute |
| 1498 |
from plone / PTL, as cheetah placeholders serve the same purpose. |
| 1499 |
""" |
| 1500 |
return message |
| 1501 |
|
| 1502 |
def getFileContents(self, path): |
| 1503 |
"""A hook for getting the contents of a file. The default |
| 1504 |
implementation just uses the Python open() function |
| 1505 |
to load local files. This method could be reimplemented |
| 1506 |
to allow reading of remote files via various protocols, |
| 1507 |
as PHP allows with its 'URL fopen wrapper'. |
| 1508 |
""" |
| 1509 |
fp = open(path, 'r') |
| 1510 |
output = fp.read() |
| 1511 |
fp.close() |
| 1512 |
return output |
| 1513 |
|
| 1514 |
def runAsMainProgram(self): |
| 1515 |
"""Allows the Template to function as a standalone command-line program |
| 1516 |
for static page generation. |
| 1517 |
|
| 1518 |
Type 'python yourtemplate.py --help to see what it's capabable of. |
| 1519 |
""" |
| 1520 |
|
| 1521 |
from .TemplateCmdLineIface import CmdLineIface |
| 1522 |
CmdLineIface(templateObj=self).run() |
| 1523 |
|
| 1524 |
|
| 1525 |
|
| 1526 |
|
| 1527 |
def _initCheetahInstance(self, |
| 1528 |
searchList=None, |
| 1529 |
namespaces=None, |
| 1530 |
|
| 1531 |
filter='RawOrEncodedUnicode', |
| 1532 |
filtersLib=Filters, |
| 1533 |
errorCatcher=None, |
| 1534 |
_globalSetVars=None, |
| 1535 |
compilerSettings=None, |
| 1536 |
_preBuiltSearchList=None): |
| 1537 |
"""Sets up the instance attributes that cheetah templates use at |
| 1538 |
run-time. |
| 1539 |
|
| 1540 |
This is automatically called by the __init__ method of compiled |
| 1541 |
templates. |
| 1542 |
|
| 1543 |
Note that the names of instance attributes used by Cheetah are prefixed |
| 1544 |
with '_CHEETAH__' (2 underscores), where class attributes are prefixed |
| 1545 |
with '_CHEETAH_' (1 underscore). |
| 1546 |
""" |
| 1547 |
if getattr(self, '_CHEETAH__instanceInitialized', False): |
| 1548 |
return |
| 1549 |
|
| 1550 |
if namespaces is not None: |
| 1551 |
assert searchList is None, ( |
| 1552 |
'Provide "namespaces" or "searchList", not both!') |
| 1553 |
searchList = namespaces |
| 1554 |
if searchList is not None \ |
| 1555 |
and not isinstance(searchList, (list, tuple)): |
| 1556 |
searchList = [searchList] |
| 1557 |
|
| 1558 |
self._CHEETAH__globalSetVars = {} |
| 1559 |
if _globalSetVars is not None: |
| 1560 |
|
| 1561 |
|
| 1562 |
self._CHEETAH__globalSetVars = _globalSetVars |
| 1563 |
|
| 1564 |
if _preBuiltSearchList is not None: |
| 1565 |
|
| 1566 |
self._CHEETAH__searchList = list(_preBuiltSearchList) |
| 1567 |
self._CHEETAH__searchList.append(self) |
| 1568 |
else: |
| 1569 |
|
| 1570 |
self._CHEETAH__searchList = [self._CHEETAH__globalSetVars, self] |
| 1571 |
if searchList is not None: |
| 1572 |
if isinstance(compilerSettings, dict) and \ |
| 1573 |
compilerSettings.get('prioritizeSearchListOverSelf'): |
| 1574 |
self._CHEETAH__searchList = searchList + \ |
| 1575 |
self._CHEETAH__searchList |
| 1576 |
else: |
| 1577 |
self._CHEETAH__searchList.extend(list(searchList)) |
| 1578 |
self._CHEETAH__cheetahIncludes = {} |
| 1579 |
self._CHEETAH__cacheRegions = {} |
| 1580 |
self._CHEETAH__indenter = Indenter() |
| 1581 |
|
| 1582 |
|
| 1583 |
self._CHEETAH__filtersLib = filtersLib |
| 1584 |
self._CHEETAH__filters = {} |
| 1585 |
if isinstance(filter, string_type): |
| 1586 |
filterName = filter |
| 1587 |
klass = getattr(self._CHEETAH__filtersLib, filterName) |
| 1588 |
else: |
| 1589 |
klass = filter |
| 1590 |
filterName = klass.__name__ |
| 1591 |
self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName] = \ |
| 1592 |
klass(self).filter |
| 1593 |
self._CHEETAH__initialFilter = self._CHEETAH__currentFilter |
| 1594 |
|
| 1595 |
self._CHEETAH__errorCatchers = {} |
| 1596 |
if errorCatcher: |
| 1597 |
if isinstance(errorCatcher, string_type): |
| 1598 |
errorCatcherClass = getattr(ErrorCatchers, errorCatcher) |
| 1599 |
elif isinstance(errorCatcher, type): |
| 1600 |
errorCatcherClass = errorCatcher |
| 1601 |
|
| 1602 |
self._CHEETAH__errorCatcher = ec = errorCatcherClass(self) |
| 1603 |
self._CHEETAH__errorCatchers[errorCatcher.__class__.__name__] = ec |
| 1604 |
|
| 1605 |
else: |
| 1606 |
self._CHEETAH__errorCatcher = None |
| 1607 |
self._CHEETAH__initErrorCatcher = self._CHEETAH__errorCatcher |
| 1608 |
|
| 1609 |
if not hasattr(self, 'transaction'): |
| 1610 |
self.transaction = None |
| 1611 |
self._CHEETAH__instanceInitialized = True |
| 1612 |
self._CHEETAH__isBuffering = False |
| 1613 |
self._CHEETAH__isControlledByWebKit = False |
| 1614 |
|
| 1615 |
self._CHEETAH__cacheStore = None |
| 1616 |
if self._CHEETAH_cacheStore is not None: |
| 1617 |
self._CHEETAH__cacheStore = self._CHEETAH_cacheStore |
| 1618 |
|
| 1619 |
def _compile(self, source=None, file=None, compilerSettings=Unspecified, |
| 1620 |
moduleName=None, mainMethodName=None): |
| 1621 |
"""Compile the template. This method is automatically called by |
| 1622 |
Template.__init__ it is provided with 'file' or 'source' args. |
| 1623 |
|
| 1624 |
USERS SHOULD \\*NEVER\\* CALL THIS METHOD THEMSELVES. |
| 1625 |
Use Template.compile instead. |
| 1626 |
""" |
| 1627 |
if compilerSettings is Unspecified: |
| 1628 |
compilerSettings = self._getCompilerSettings(source, file) or {} |
| 1629 |
mainMethodName = mainMethodName or self._CHEETAH_defaultMainMethodName |
| 1630 |
self._fileMtime = None |
| 1631 |
self._fileDirName = None |
| 1632 |
self._fileBaseName = None |
| 1633 |
if file and isinstance(file, string_type): |
| 1634 |
file = self.serverSidePath(file) |
| 1635 |
self._fileMtime = os.path.getmtime(file) |
| 1636 |
self._fileDirName, self._fileBaseName = os.path.split(file) |
| 1637 |
self._filePath = file |
| 1638 |
templateClass = self.compile(source, file, |
| 1639 |
moduleName=moduleName, |
| 1640 |
mainMethodName=mainMethodName, |
| 1641 |
compilerSettings=compilerSettings, |
| 1642 |
keepRefToGeneratedCode=True) |
| 1643 |
|
| 1644 |
if not self.__class__ == Template: |
| 1645 |
|
| 1646 |
|
| 1647 |
for k, v in self.__class__.__dict__.items(): |
| 1648 |
if not v or k.startswith('__'): |
| 1649 |
continue |
| 1650 |
|
| 1651 |
|
| 1652 |
|
| 1653 |
setattr(self, k, v) |
| 1654 |
|
| 1655 |
self.__class__ = templateClass |
| 1656 |
|
| 1657 |
templateClass.__init__(self, |
| 1658 |
|
| 1659 |
|
| 1660 |
) |
| 1661 |
if not hasattr(self, 'transaction'): |
| 1662 |
self.transaction = None |
| 1663 |
|
| 1664 |
def _handleCheetahInclude(self, srcArg, trans=None, |
| 1665 |
includeFrom='file', raw=False): |
| 1666 |
"""Called at runtime to handle #include directives. |
| 1667 |
""" |
| 1668 |
_includeID = srcArg |
| 1669 |
if _includeID not in self._CHEETAH__cheetahIncludes: |
| 1670 |
if not raw: |
| 1671 |
if includeFrom == 'file': |
| 1672 |
source = None |
| 1673 |
if isinstance(srcArg, string_type): |
| 1674 |
if hasattr(self, 'serverSidePath'): |
| 1675 |
file = path = self.serverSidePath(srcArg) |
| 1676 |
else: |
| 1677 |
file = path = os.path.normpath(srcArg) |
| 1678 |
else: |
| 1679 |
file = srcArg |
| 1680 |
else: |
| 1681 |
source = srcArg |
| 1682 |
file = None |
| 1683 |
|
| 1684 |
|
| 1685 |
|
| 1686 |
compiler = \ |
| 1687 |
self._getTemplateAPIClassForIncludeDirectiveCompilation( |
| 1688 |
source, file) |
| 1689 |
nestedTemplateClass = compiler.compile(source=source, |
| 1690 |
file=file) |
| 1691 |
nestedTemplate = nestedTemplateClass( |
| 1692 |
_preBuiltSearchList=self.searchList(), |
| 1693 |
_globalSetVars=self._CHEETAH__globalSetVars) |
| 1694 |
|
| 1695 |
|
| 1696 |
|
| 1697 |
|
| 1698 |
nestedTemplate._CHEETAH__initialFilter = \ |
| 1699 |
self._CHEETAH__initialFilter |
| 1700 |
nestedTemplate._CHEETAH__currentFilter = \ |
| 1701 |
self._CHEETAH__initialFilter |
| 1702 |
self._CHEETAH__cheetahIncludes[_includeID] = nestedTemplate |
| 1703 |
else: |
| 1704 |
if includeFrom == 'file': |
| 1705 |
path = self.serverSidePath(srcArg) |
| 1706 |
self._CHEETAH__cheetahIncludes[_includeID] = \ |
| 1707 |
self.getFileContents(path) |
| 1708 |
else: |
| 1709 |
self._CHEETAH__cheetahIncludes[_includeID] = srcArg |
| 1710 |
|
| 1711 |
if not raw: |
| 1712 |
self._CHEETAH__cheetahIncludes[_includeID].respond(trans) |
| 1713 |
else: |
| 1714 |
trans.response().write(self._CHEETAH__cheetahIncludes[_includeID]) |
| 1715 |
|
| 1716 |
def _getTemplateAPIClassForIncludeDirectiveCompilation(self, source, file): |
| 1717 |
"""Returns the subclass of Template which should be used to compile |
| 1718 |
#include directives. |
| 1719 |
|
| 1720 |
This abstraction allows different compiler settings to be used in the |
| 1721 |
included template than were used in the parent. |
| 1722 |
""" |
| 1723 |
if issubclass(self.__class__, Template): |
| 1724 |
return self.__class__ |
| 1725 |
else: |
| 1726 |
return Template |
| 1727 |
|
| 1728 |
|
| 1729 |
def webInput(self, names, namesMulti=(), default='', src='f', |
| 1730 |
defaultInt=0, defaultFloat=0.00, badInt=0, badFloat=0.00, |
| 1731 |
debug=False): |
| 1732 |
"""Method for importing web transaction variables in bulk. |
| 1733 |
|
| 1734 |
This works for GET/POST fields both in Webware servlets and in CGI |
| 1735 |
scripts, and for cookies and session variables in Webware servlets. |
| 1736 |
If you try to read a cookie or session variable in a CGI script, |
| 1737 |
you'll get a RuntimeError. 'In a CGI script' here means |
| 1738 |
'not running as a Webware servlet'. If the CGI environment |
| 1739 |
is not properly set up, Cheetah will act like there's no input. |
| 1740 |
|
| 1741 |
The public method provided is:: |
| 1742 |
|
| 1743 |
def webInput(self, names, namesMulti=(), default='', src='f', |
| 1744 |
defaultInt=0, defaultFloat=0.00, |
| 1745 |
badInt=0, badFloat=0.00, debug=False): |
| 1746 |
|
| 1747 |
This method places the specified GET/POST fields, cookies or session |
| 1748 |
variables into a dictionary, which is both returned and put at the |
| 1749 |
beginning of the searchList. It handles:: |
| 1750 |
|
| 1751 |
* single vs multiple values |
| 1752 |
* conversion to integer or float for specified names |
| 1753 |
* default values/exceptions for missing or bad values |
| 1754 |
* printing a snapshot of all values retrieved for debugging |
| 1755 |
|
| 1756 |
All the 'default*' and 'bad*' arguments have 'use or raise' behavior, |
| 1757 |
meaning that if they're a subclass of Exception, they're raised. If |
| 1758 |
they're anything else, that value is substituted for the missing/bad |
| 1759 |
value. |
| 1760 |
|
| 1761 |
|
| 1762 |
The simplest usage is:: |
| 1763 |
|
| 1764 |
#silent $webInput(['choice']) |
| 1765 |
$choice |
| 1766 |
|
| 1767 |
dic = self.webInput(['choice']) |
| 1768 |
write(dic['choice']) |
| 1769 |
|
| 1770 |
Both these examples retrieves the GET/POST field 'choice' and print it. |
| 1771 |
If you leave off the'#silent', all the values would be printed too. |
| 1772 |
But a better way to preview the values is:: |
| 1773 |
|
| 1774 |
#silent $webInput(['name'], $debug=1) |
| 1775 |
|
| 1776 |
because this pretty-prints all the values inside HTML <PRE> tags. |
| 1777 |
|
| 1778 |
\\*\\*\\* KLUDGE: 'debug' is supposed to insert |
| 1779 |
into the template output, |
| 1780 |
but it wasn't working so I changed it to a'print' statement. |
| 1781 |
So the debugging output will appear wherever standard output |
| 1782 |
is pointed, whether at the terminal, in a Webware log file, |
| 1783 |
or whatever. \\*\\*\\* |
| 1784 |
|
| 1785 |
Since we didn't specify any coversions, the value is a string. It's a |
| 1786 |
'single' value because we specified it in 'names' rather than |
| 1787 |
'namesMulti'. Single values work like this:: |
| 1788 |
|
| 1789 |
* If one value is found, take it. |
| 1790 |
* If several values are found, choose one arbitrarily |
| 1791 |
and ignore the rest. |
| 1792 |
* If no values are found, use or raise |
| 1793 |
the appropriate 'default*' value. |
| 1794 |
|
| 1795 |
Multi values work like this:: |
| 1796 |
|
| 1797 |
* If one value is found, put it in a list. |
| 1798 |
* If several values are found, leave them in a list. |
| 1799 |
* If no values are found, use the empty list ([]). The 'default*' |
| 1800 |
arguments are *not* consulted in this case. |
| 1801 |
|
| 1802 |
Example: assume 'days' came from a set of checkboxes |
| 1803 |
or a multiple combo box on a form, and the user chose'Monday', |
| 1804 |
'Tuesday' and 'Thursday':: |
| 1805 |
|
| 1806 |
#silent $webInput([], ['days']) |
| 1807 |
The days you chose are: #slurp |
| 1808 |
#for $day in $days |
| 1809 |
$day #slurp |
| 1810 |
#end for |
| 1811 |
|
| 1812 |
dic = self.webInput([], ['days']) |
| 1813 |
write('The days you chose are: ') |
| 1814 |
for day in dic['days']: |
| 1815 |
write(day + ' ') |
| 1816 |
|
| 1817 |
Both these examples print: 'The days you chose are: |
| 1818 |
Monday Tuesday Thursday'. |
| 1819 |
|
| 1820 |
By default, missing strings are replaced by '' and missing/bad numbers |
| 1821 |
by zero. (A'bad number' means the converter raised an exception for |
| 1822 |
it, usually because of non-numeric characters in the value.) This |
| 1823 |
mimics Perl/PHP behavior, and simplifies coding for many applications |
| 1824 |
where missing/bad values *should* be blank/zero. In those relatively |
| 1825 |
few cases where you must distinguish between empty-string/zero on the |
| 1826 |
one hand and missing/bad on the other, change the appropriate |
| 1827 |
'default*' and 'bad*' arguments to something like:: |
| 1828 |
|
| 1829 |
* None |
| 1830 |
* another constant value |
| 1831 |
* $NonNumericInputError/self.NonNumericInputError |
| 1832 |
* $ValueError/ValueError |
| 1833 |
|
| 1834 |
(NonNumericInputError is defined in this class and is useful for |
| 1835 |
distinguishing between bad input vs a TypeError/ValueError thrown for |
| 1836 |
some other rason.) |
| 1837 |
|
| 1838 |
Here's an example using multiple values to schedule newspaper |
| 1839 |
deliveries. 'checkboxes' comes from a form with checkboxes for all the |
| 1840 |
days of the week. The days the user previously chose are preselected. |
| 1841 |
The user checks/unchecks boxes as desired and presses Submit. |
| 1842 |
The value of 'checkboxes' is a list of checkboxes that were checked |
| 1843 |
when Submit was pressed. Our task now is to turn on the days |
| 1844 |
the user checked, turn off the days he unchecked, and leave on or off |
| 1845 |
the days he didn't change. |
| 1846 |
|
| 1847 |
:: |
| 1848 |
|
| 1849 |
dic = self.webInput([], ['dayCheckboxes']) |
| 1850 |
wantedDays = dic['dayCheckboxes'] # The days the user checked. |
| 1851 |
for day, on in self.getAllValues(): |
| 1852 |
if not on and day in wantedDays: |
| 1853 |
self.TurnOn(day) |
| 1854 |
# ... Set a flag or insert a database record ... |
| 1855 |
elif on and day not in wantedDays: |
| 1856 |
self.TurnOff(day) |
| 1857 |
# ... Unset a flag or delete a database record ... |
| 1858 |
|
| 1859 |
'source' allows you to look up the variables from a number of different |
| 1860 |
sources:: |
| 1861 |
|
| 1862 |
'f' fields (CGI GET/POST parameters) |
| 1863 |
'c' cookies |
| 1864 |
's' session variables |
| 1865 |
'v' 'values', meaning fields or cookies |
| 1866 |
|
| 1867 |
In many forms, you're dealing only with strings, which is why the |
| 1868 |
'default' argument is third and the numeric arguments are banished to |
| 1869 |
the end. But sometimes you want automatic number conversion, so that |
| 1870 |
you can do numeric comparisions in your templates without having to |
| 1871 |
write a bunch of conversion/exception handling code. Example:: |
| 1872 |
|
| 1873 |
#silent $webInput(['name', 'height:int']) |
| 1874 |
$name is $height cm tall. |
| 1875 |
#if $height >= 300 |
| 1876 |
Wow, you're tall! |
| 1877 |
#else |
| 1878 |
Pshaw, you're short. |
| 1879 |
#end if |
| 1880 |
|
| 1881 |
dic = self.webInput(['name', 'height:int']) |
| 1882 |
name = dic[name] |
| 1883 |
height = dic[height] |
| 1884 |
write('%s is %s cm tall.' % (name, height)) |
| 1885 |
if height > 300: |
| 1886 |
write('Wow, you're tall!') |
| 1887 |
else: |
| 1888 |
write('Pshaw, you're short.') |
| 1889 |
|
| 1890 |
To convert a value to a number, suffix ':int' or ':float' to the name. |
| 1891 |
The method will search first for a 'height:int' variable |
| 1892 |
and then for a 'height' variable. (It will be called 'height' |
| 1893 |
in the final dictionary.) If a numeric conversion fails, |
| 1894 |
use or raise 'badInt' or 'badFloat'. Missing values work the same way |
| 1895 |
as for strings, except the default is 'defaultInt' |
| 1896 |
or 'defaultFloat' instead of 'default'. |
| 1897 |
|
| 1898 |
If a name represents an uploaded file, the entire file will be read |
| 1899 |
into memory. For more sophistocated file-upload handling, |
| 1900 |
leave that name out of the list and do your own handling, |
| 1901 |
or wait for Cheetah.Utils.UploadFileMixin. |
| 1902 |
|
| 1903 |
This only in a subclass that also inherits from Webware's Servlet or |
| 1904 |
HTTPServlet. Otherwise you'll get an AttributeError on 'self.request'. |
| 1905 |
|
| 1906 |
EXCEPTIONS: ValueError if 'source' is not one of the stated characters. |
| 1907 |
TypeError if a conversion suffix is not ':int' or ':float'. |
| 1908 |
|
| 1909 |
FUTURE EXPANSION: a future version of this method may allow source |
| 1910 |
cascading; e.g., 'vs' would look first in 'values' and then in session |
| 1911 |
variables. |
| 1912 |
|
| 1913 |
Meta-Data:: |
| 1914 |
|
| 1915 |
Author: Mike Orr <[email protected]> |
| 1916 |
License: This software is released for unlimited distribution |
| 1917 |
under the terms of the MIT license. See the LICENSE file. |
| 1918 |
Version: 1.186 |
| 1919 |
Start Date: 2002/03/17 |
| 1920 |
Last Revision Date: 2008/03/10 04:48:11 |
| 1921 |
""" |
| 1922 |
src = src.lower() |
| 1923 |
isCgi = not self._CHEETAH__isControlledByWebKit |
| 1924 |
if isCgi and src in ('f', 'v'): |
| 1925 |
global _formUsedByWebInput |
| 1926 |
if cgi is None: |
| 1927 |
if _formUsedByWebInput is None: |
| 1928 |
_formUsedByWebInput = \ |
| 1929 |
parse_qs(os.environ.get('QUERY_STRING', '')) |
| 1930 |
source, func = 'field', _formUsedByWebInput.get |
| 1931 |
else: |
| 1932 |
if _formUsedByWebInput is None: |
| 1933 |
_formUsedByWebInput = cgi.FieldStorage() |
| 1934 |
source, func = 'field', _formUsedByWebInput.getvalue |
| 1935 |
elif isCgi and src == 'c': |
| 1936 |
raise RuntimeError("can't get cookies from a CGI script") |
| 1937 |
elif isCgi and src == 's': |
| 1938 |
raise RuntimeError("can't get session variables from a CGI script") |
| 1939 |
elif isCgi and src == 'v': |
| 1940 |
source, func = 'value', self.request().value |
| 1941 |
elif isCgi and src == 's': |
| 1942 |
source, func = 'session', self.request().session().value |
| 1943 |
elif src == 'f': |
| 1944 |
source, func = 'field', self.request().field |
| 1945 |
elif src == 'c': |
| 1946 |
source, func = 'cookie', self.request().cookie |
| 1947 |
elif src == 'v': |
| 1948 |
source, func = 'value', self.request().value |
| 1949 |
elif src == 's': |
| 1950 |
source, func = 'session', self.request().session().value |
| 1951 |
else: |
| 1952 |
raise TypeError("arg 'src' invalid") |
| 1953 |
converters = { |
| 1954 |
'': _Converter('string', None, default, default), |
| 1955 |
'int': _Converter('int', int, defaultInt, badInt), |
| 1956 |
'float': _Converter('float', float, defaultFloat, badFloat), |
| 1957 |
} |
| 1958 |
|
| 1959 |
dic = {} |
| 1960 |
for name in names: |
| 1961 |
k, v = _lookup(name, func, False, converters) |
| 1962 |
dic[k] = v |
| 1963 |
for name in namesMulti: |
| 1964 |
k, v = _lookup(name, func, True, converters) |
| 1965 |
dic[k] = v |
| 1966 |
|
| 1967 |
|
| 1968 |
|
| 1969 |
|
| 1970 |
|
| 1971 |
|
| 1972 |
if debug: |
| 1973 |
print("<PRE>\n" + pprint.pformat(dic) + "\n</PRE>\n\n") |
| 1974 |
self.searchList().insert(0, dic) |
| 1975 |
return dic |
| 1976 |
|
| 1977 |
|
| 1978 |
T = Template |
| 1979 |
Template.Reserved_SearchList = set(dir(Template)) |
| 1980 |
|
| 1981 |
|
| 1982 |
def genParserErrorFromPythonException(source, file, |
| 1983 |
generatedPyCode, exception): |
| 1984 |
|
| 1985 |
filename = isinstance(file, (str, unicode)) and file or None |
| 1986 |
|
| 1987 |
sio = StringIO() |
| 1988 |
traceback.print_exc(1, sio) |
| 1989 |
formatedExc = sio.getvalue() |
| 1990 |
|
| 1991 |
if hasattr(exception, 'lineno'): |
| 1992 |
pyLineno = exception.lineno |
| 1993 |
else: |
| 1994 |
pyLineno = int( |
| 1995 |
re.search('[ \t]*File.*line (\\d+)', formatedExc).group(1)) |
| 1996 |
|
| 1997 |
lines = generatedPyCode.splitlines() |
| 1998 |
|
| 1999 |
prevLines = [] |
| 2000 |
for i in range(1, 4): |
| 2001 |
if pyLineno - i <= 0: |
| 2002 |
break |
| 2003 |
prevLines.append((pyLineno + 1 - i, lines[pyLineno - i])) |
| 2004 |
|
| 2005 |
nextLines = [] |
| 2006 |
for i in range(1, 4): |
| 2007 |
if not pyLineno + i < len(lines): |
| 2008 |
break |
| 2009 |
nextLines.append((pyLineno + i, lines[pyLineno + i])) |
| 2010 |
nextLines.reverse() |
| 2011 |
report = 'Line|Python Code\n' |
| 2012 |
report += '----|--------------------------' \ |
| 2013 |
'-----------------------------------\n' |
| 2014 |
while prevLines: |
| 2015 |
lineInfo = prevLines.pop() |
| 2016 |
report += "%(row)-4d|%(line)s\n" \ |
| 2017 |
% {'row': lineInfo[0], 'line': lineInfo[1]} |
| 2018 |
|
| 2019 |
if hasattr(exception, 'offset'): |
| 2020 |
report += ' '*(3 + (exception.offset or 0)) + '^\n' |
| 2021 |
|
| 2022 |
while nextLines: |
| 2023 |
lineInfo = nextLines.pop() |
| 2024 |
report += "%(row)-4d|%(line)s\n" \ |
| 2025 |
% {'row': lineInfo[0], 'line': lineInfo[1]} |
| 2026 |
|
| 2027 |
message = [ |
| 2028 |
"Error in the Python code which Cheetah generated for this template:", |
| 2029 |
'='*80, |
| 2030 |
'', |
| 2031 |
str(exception), |
| 2032 |
'', |
| 2033 |
report, |
| 2034 |
'='*80, |
| 2035 |
] |
| 2036 |
cheetahPosMatch = re.search('line (\\d+), col (\\d+)', formatedExc) |
| 2037 |
if cheetahPosMatch: |
| 2038 |
lineno = int(cheetahPosMatch.group(1)) |
| 2039 |
col = int(cheetahPosMatch.group(2)) |
| 2040 |
|
| 2041 |
|
| 2042 |
message.append('\nHere is the corresponding Cheetah code:\n') |
| 2043 |
else: |
| 2044 |
lineno = None |
| 2045 |
col = None |
| 2046 |
cheetahPosMatch = re.search('line (\\d+), col (\\d+)', |
| 2047 |
'\n'.join(lines[max(pyLineno - 2, 0):])) |
| 2048 |
if cheetahPosMatch: |
| 2049 |
lineno = int(cheetahPosMatch.group(1)) |
| 2050 |
col = int(cheetahPosMatch.group(2)) |
| 2051 |
message.append('\nHere is the corresponding Cheetah code.') |
| 2052 |
message.append('** I had to guess the line & column numbers,' |
| 2053 |
' so they are probably incorrect:\n') |
| 2054 |
|
| 2055 |
message = '\n'.join(message) |
| 2056 |
reader = SourceReader(source, filename=filename) |
| 2057 |
return ParseError(reader, message, lineno=lineno, col=col) |
| 2058 |
|
| 2059 |
|
| 2060 |
|