This repository has been archived by the owner on Mar 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Template.py
1913 lines (1602 loc) · 82.2 KB
/
Template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Provides the core API for Cheetah.
See the docstring in the Template class and the Users' Guide for more information
'''
################################################################################
## DEPENDENCIES
import sys # used in the error handling code
import re # used to define the internal delims regex
import new # used to bind methods and create dummy modules
import logging
import string
import os.path
import time # used in the cache refresh code
from random import randrange
import imp
import inspect
import StringIO
import traceback
import pprint
import cgi # Used by .webInput() if the template is a CGI script.
import types
from types import StringType, ClassType
try:
from types import StringTypes
except ImportError:
StringTypes = (types.StringType,types.UnicodeType)
try:
from threading import Lock
except ImportError:
class Lock:
def acquire(self):
pass
def release(self):
pass
try:
x = set()
except NameError:
# Python 2.3 compatibility
from sets import Set as set
from Cheetah.Version import convertVersionStringToTuple, MinCompatibleVersionTuple
from Cheetah.Version import MinCompatibleVersion
# Base classes for Template
from Cheetah.Servlet import Servlet
# More intra-package imports ...
from Cheetah.Parser import ParseError, SourceReader
from Cheetah.Compiler import Compiler, DEFAULT_COMPILER_SETTINGS
from Cheetah import ErrorCatchers # for placeholder tags
from Cheetah import Filters # the output filters
from Cheetah.convertTmplPathToModuleName import convertTmplPathToModuleName
from Cheetah.Utils.Misc import checkKeywords # Used in Template.__init__
from Cheetah.Utils.Indenter import Indenter # Used in Template.__init__ and for
# placeholders
from Cheetah.NameMapper import NotFound, valueFromSearchList
from Cheetah.CacheStore import MemoryCacheStore, MemcachedCacheStore
from Cheetah.CacheRegion import CacheRegion
from Cheetah.Utils.WebInputMixin import _Converter, _lookup, NonNumericInputError
from Cheetah.Unspecified import Unspecified
# Decide whether to use the file modification time in file's cache key
__checkFileMtime = True
def checkFileMtime(value):
globals()['__checkFileMtime'] = value
class Error(Exception):
pass
class PreprocessError(Error):
pass
def hashList(l):
hashedList = []
for v in l:
if isinstance(v, dict):
v = hashDict(v)
elif isinstance(v, list):
v = hashList(v)
hashedList.append(v)
return hash(tuple(hashedList))
def hashDict(d):
items = d.items()
items.sort()
hashedList = []
for k, v in items:
if isinstance(v, dict):
v = hashDict(v)
elif isinstance(v, list):
v = hashList(v)
hashedList.append((k,v))
return hash(tuple(hashedList))
################################################################################
## MODULE GLOBALS AND CONSTANTS
def _genUniqueModuleName(baseModuleName):
"""The calling code is responsible for concurrency locking.
"""
if baseModuleName not in sys.modules:
finalName = baseModuleName
else:
finalName = ('cheetah_%s_%s_%s'%(baseModuleName,
str(time.time()).replace('.','_'),
str(randrange(10000, 99999))))
return finalName
# Cache of a cgi.FieldStorage() instance, maintained by .webInput().
# This is only relavent to templates used as CGI scripts.
_formUsedByWebInput = None
def updateLinecache(filename, src):
import linecache
size = len(src)
mtime = time.time()
lines = src.splitlines()
fullname = filename
linecache.cache[filename] = size, mtime, lines, fullname
class CompileCacheItem(object):
pass
class TemplatePreprocessor(object):
'''
This is used with the preprocessors argument to Template.compile().
See the docstring for Template.compile
** Preprocessors are an advanced topic **
'''
def __init__(self, settings):
self._settings = settings
def preprocess(self, source, file):
"""Create an intermediate template and return the source code
it outputs
"""
settings = self._settings
if not source: # @@TR: this needs improving
if isinstance(file, (str, unicode)): # it's a filename.
f = open(file)
source = f.read()
f.close()
elif hasattr(file, 'read'):
source = file.read()
file = None
templateAPIClass = settings.templateAPIClass
possibleKwArgs = [
arg for arg in
inspect.getargs(templateAPIClass.compile.im_func.func_code)[0]
if arg not in ('klass', 'source', 'file',)]
compileKwArgs = {}
for arg in possibleKwArgs:
if hasattr(settings, arg):
compileKwArgs[arg] = getattr(settings, arg)
tmplClass = templateAPIClass.compile(source=source, file=file, **compileKwArgs)
tmplInstance = tmplClass(**settings.templateInitArgs)
outputSource = settings.outputTransformer(tmplInstance)
outputFile = None
return outputSource, outputFile
class Template(Servlet):
'''
This class provides a) methods used by templates at runtime and b)
methods for compiling Cheetah source code into template classes.
This documentation assumes you already know Python and the basics of object
oriented programming. If you don't know Python, see the sections of the
Cheetah Users' Guide for non-programmers. It also assumes you have read
about Cheetah's syntax in the Users' Guide.
The following explains how to use Cheetah from within Python programs or via
the interpreter. If you statically compile your templates on the command
line using the 'cheetah' script, this is not relevant to you. Statically
compiled Cheetah template modules/classes (e.g. myTemplate.py:
MyTemplateClasss) are just like any other Python module or class. Also note,
most Python web frameworks (Webware, Aquarium, mod_python, Turbogears,
CherryPy, Quixote, etc.) provide plugins that handle Cheetah compilation for
you.
There are several possible usage patterns:
1) tclass = Template.compile(src)
t1 = tclass() # or tclass(namespaces=[namespace,...])
t2 = tclass() # or tclass(namespaces=[namespace2,...])
outputStr = str(t1) # or outputStr = t1.aMethodYouDefined()
Template.compile provides a rich and very flexible API via its
optional arguments so there are many possible variations of this
pattern. One example is:
tclass = Template.compile('hello $name from $caller', baseclass=dict)
print tclass(name='world', caller='me')
See the Template.compile() docstring for more details.
2) tmplInstance = Template(src)
# or Template(src, namespaces=[namespace,...])
outputStr = str(tmplInstance) # or outputStr = tmplInstance.aMethodYouDefined(...args...)
Notes on the usage patterns:
usage pattern 1)
This is the most flexible, but it is slightly more verbose unless you
write a wrapper function to hide the plumbing. Under the hood, all
other usage patterns are based on this approach. Templates compiled
this way can #extend (subclass) any Python baseclass: old-style or
new-style (based on object or a builtin type).
usage pattern 2)
This was Cheetah's original usage pattern. It returns an instance,
but you can still access the generated class via
tmplInstance.__class__. If you want to use several different
namespace 'searchLists' with a single template source definition,
you're better off with Template.compile (1).
Limitations (use pattern 1 instead):
- Templates compiled this way can only #extend subclasses of the
new-style 'object' baseclass. Cheetah.Template is a subclass of
'object'. You also can not #extend dict, list, or other builtin
types.
- If your template baseclass' __init__ constructor expects args there
is currently no way to pass them in.
If you need to subclass a dynamically compiled Cheetah class, do something like this:
from Cheetah.Template import Template
T1 = Template.compile('$meth1 #def meth1: this is meth1 in T1')
T2 = Template.compile('#implements meth1\nthis is meth1 redefined in T2', baseclass=T1)
print T1, T1()
print T2, T2()
Note about class and instance attribute names:
Attributes used by Cheetah have a special prefix to avoid confusion with
the attributes of the templates themselves or those of template
baseclasses.
Class attributes which are used in class methods look like this:
klass._CHEETAH_useCompilationCache (_CHEETAH_xxx)
Instance attributes look like this:
klass._CHEETAH__globalSetVars (_CHEETAH__xxx with 2 underscores)
'''
# this is used by ._addCheetahPlumbingCodeToClass()
_CHEETAH_requiredCheetahMethods = (
'_initCheetahInstance',
'searchList',
'errorCatcher',
'getVar',
'varExists',
'getFileContents',
'i18n',
'runAsMainProgram',
'respond',
'shutdown',
'webInput',
'serverSidePath',
'generatedClassCode',
'generatedModuleCode',
'_getCacheStore',
'_getCacheStoreIdPrefix',
'_createCacheRegion',
'getCacheRegion',
'getCacheRegions',
'refreshCache',
'_handleCheetahInclude',
'_getTemplateAPIClassForIncludeDirectiveCompilation',
)
_CHEETAH_requiredCheetahClassMethods = ('subclass',)
_CHEETAH_requiredCheetahClassAttributes = ('cacheRegionClass','cacheStore',
'cacheStoreIdPrefix','cacheStoreClass')
## the following are used by .compile(). Most are documented in its docstring.
_CHEETAH_cacheModuleFilesForTracebacks = False
_CHEETAH_cacheDirForModuleFiles = None # change to a dirname
_CHEETAH_compileCache = dict() # cache store for compiled code and classes
# To do something other than simple in-memory caching you can create an
# alternative cache store. It just needs to support the basics of Python's
# mapping/dict protocol. E.g.:
# class AdvCachingTemplate(Template):
# _CHEETAH_compileCache = MemoryOrFileCache()
_CHEETAH_compileLock = Lock() # used to prevent race conditions
_CHEETAH_defaultMainMethodName = None
_CHEETAH_compilerSettings = None
_CHEETAH_compilerClass = Compiler
_CHEETAH_cacheCompilationResults = True
_CHEETAH_useCompilationCache = True
_CHEETAH_keepRefToGeneratedCode = True
_CHEETAH_defaultBaseclassForTemplates = None
_CHEETAH_defaultClassNameForTemplates = None
# defaults to DEFAULT_COMPILER_SETTINGS['mainMethodName']:
_CHEETAH_defaultMainMethodNameForTemplates = None
_CHEETAH_defaultModuleNameForTemplates = 'DynamicallyCompiledCheetahTemplate'
_CHEETAH_defaultModuleGlobalsForTemplates = None
_CHEETAH_preprocessors = None
_CHEETAH_defaultPreprocessorClass = TemplatePreprocessor
## The following attributes are used by instance methods:
_CHEETAH_generatedModuleCode = None
NonNumericInputError = NonNumericInputError
_CHEETAH_cacheRegionClass = CacheRegion
_CHEETAH_cacheStoreClass = MemoryCacheStore
#_CHEETAH_cacheStoreClass = MemcachedCacheStore
_CHEETAH_cacheStore = None
_CHEETAH_cacheStoreIdPrefix = None
def _getCompilerClass(klass, source=None, file=None):
return klass._CHEETAH_compilerClass
_getCompilerClass = classmethod(_getCompilerClass)
def _getCompilerSettings(klass, source=None, file=None):
return klass._CHEETAH_compilerSettings
_getCompilerSettings = classmethod(_getCompilerSettings)
def compile(klass, source=None, file=None,
returnAClass=True,
compilerSettings=Unspecified,
compilerClass=Unspecified,
moduleName=None,
className=Unspecified,
mainMethodName=Unspecified,
baseclass=Unspecified,
moduleGlobals=Unspecified,
cacheCompilationResults=Unspecified,
useCache=Unspecified,
preprocessors=Unspecified,
cacheModuleFilesForTracebacks=Unspecified,
cacheDirForModuleFiles=Unspecified,
commandlineopts=None,
keepRefToGeneratedCode=Unspecified,
):
"""
The core API for compiling Cheetah source code into template classes.
This class method compiles Cheetah source code and returns a python
class. You then create template instances using that class. All
Cheetah's other compilation API's use this method under the hood.
Internally, this method a) parses the Cheetah source code and generates
Python code defining a module with a single class in it, b) dynamically
creates a module object with a unique name, c) execs the generated code
in that module's namespace then inserts the module into sys.modules, and
d) returns a reference to the generated class. If you want to get the
generated python source code instead, pass the argument
returnAClass=False.
It caches generated code and classes. See the descriptions of the
arguments'cacheCompilationResults' and 'useCache' for details. This
doesn't mean that templates will automatically recompile themselves when
the source file changes. Rather, if you call Template.compile(src) or
Template.compile(file=path) repeatedly it will attempt to return a
cached class definition instead of recompiling.
Hooks are provided template source preprocessing. See the notes on the
'preprocessors' arg.
If you are an advanced user and need to customize the way Cheetah parses
source code or outputs Python code, you should check out the
compilerSettings argument.
Arguments:
You must provide either a 'source' or 'file' arg, but not both:
- source (string or None)
- file (string path, file-like object, or None)
The rest of the arguments are strictly optional. All but the first
have defaults in attributes of the Template class which can be
overridden in subclasses of this class. Working with most of these is
an advanced topic.
- returnAClass=True
If false, return the generated module code rather than a class.
- compilerSettings (a dict)
Default: Template._CHEETAH_compilerSettings=None
a dictionary of settings to override those defined in
DEFAULT_COMPILER_SETTINGS. These can also be overridden in your
template source code with the #compiler or #compiler-settings
directives.
- compilerClass (a class)
Default: Template._CHEETAH_compilerClass=Cheetah.Compiler.Compiler
a subclass of Cheetah.Compiler.Compiler. Mucking with this is a
very advanced topic.
- moduleName (a string)
Default:
Template._CHEETAH_defaultModuleNameForTemplates
='DynamicallyCompiledCheetahTemplate'
What to name the generated Python module. If the provided value is
None and a file arg was given, the moduleName is created from the
file path. In all cases if the moduleName provided is already in
sys.modules it is passed through a filter that generates a unique
variant of the name.
- className (a string)
Default: Template._CHEETAH_defaultClassNameForTemplates=None
What to name the generated Python class. If the provided value is
None, the moduleName is use as the class name.
- mainMethodName (a string)
Default:
Template._CHEETAH_defaultMainMethodNameForTemplates
=None (and thus DEFAULT_COMPILER_SETTINGS['mainMethodName'])
What to name the main output generating method in the compiled
template class.
- baseclass (a string or a class)
Default: Template._CHEETAH_defaultBaseclassForTemplates=None
Specifies the baseclass for the template without manually
including an #extends directive in the source. The #extends
directive trumps this arg.
If the provided value is a string you must make sure that a class
reference by that name is available to your template, either by
using an #import directive or by providing it in the arg
'moduleGlobals'.
If the provided value is a class, Cheetah will handle all the
details for you.
- moduleGlobals (a dict)
Default: Template._CHEETAH_defaultModuleGlobalsForTemplates=None
A dict of vars that will be added to the global namespace of the
module the generated code is executed in, prior to the execution
of that code. This should be Python values, not code strings!
- cacheCompilationResults (True/False)
Default: Template._CHEETAH_cacheCompilationResults=True
Tells Cheetah to cache the generated code and classes so that they
can be reused if Template.compile() is called multiple times with
the same source and options.
- useCache (True/False)
Default: Template._CHEETAH_useCompilationCache=True
Should the compilation cache be used? If True and a previous
compilation created a cached template class with the same source
code, compiler settings and other options, the cached template
class will be returned.
- cacheModuleFilesForTracebacks (True/False)
Default: Template._CHEETAH_cacheModuleFilesForTracebacks=False
In earlier versions of Cheetah tracebacks from exceptions that
were raised inside dynamically compiled Cheetah templates were
opaque because Python didn't have access to a python source file
to use in the traceback:
File "xxxx.py", line 192, in getTextiledContent
content = str(template(searchList=searchList))
File "cheetah_yyyy.py", line 202, in __str__
File "cheetah_yyyy.py", line 187, in respond
File "cheetah_yyyy.py", line 139, in writeBody
ZeroDivisionError: integer division or modulo by zero
It is now possible to keep those files in a cache dir and allow
Python to include the actual source lines in tracebacks and makes
them much easier to understand:
File "xxxx.py", line 192, in getTextiledContent
content = str(template(searchList=searchList))
File "/tmp/CheetahCacheDir/cheetah_yyyy.py", line 202, in __str__
def __str__(self): return self.respond()
File "/tmp/CheetahCacheDir/cheetah_yyyy.py", line 187, in respond
self.writeBody(trans=trans)
File "/tmp/CheetahCacheDir/cheetah_yyyy.py", line 139, in writeBody
__v = 0/0 # $(0/0)
ZeroDivisionError: integer division or modulo by zero
- cacheDirForModuleFiles (a string representing a dir path)
Default: Template._CHEETAH_cacheDirForModuleFiles=None
See notes on cacheModuleFilesForTracebacks.
- preprocessors
Default: Template._CHEETAH_preprocessors=None
** THIS IS A VERY ADVANCED TOPIC **
These are used to transform the source code prior to compilation.
They provide a way to use Cheetah as a code generator for Cheetah
code. In other words, you use one Cheetah template to output the
source code for another Cheetah template.
The major expected use cases are:
a) 'compile-time caching' aka 'partial template binding',
wherein an intermediate Cheetah template is used to output
the source for the final Cheetah template. The intermediate
template is a mix of a modified Cheetah syntax (the
'preprocess syntax') and standard Cheetah syntax. The
preprocessor syntax is executed at compile time and outputs
Cheetah code which is then compiled in turn. This approach
allows one to completely soft-code all the elements in the
template which are subject to change yet have it compile to
extremely efficient Python code with everything but the
elements that must be variable at runtime (per browser
request, etc.) compiled as static strings. Examples of this
usage pattern will be added to the Cheetah Users' Guide.
The'preprocess syntax' is just Cheetah's standard one with
alternatives for the $ and # tokens:
e.g. '@' and '%' for code like this
@aPreprocessVar $aRuntimeVar
%if aCompileTimeCondition then yyy else zzz
%% preprocessor comment
#if aRunTimeCondition then aaa else bbb
## normal comment
$aRuntimeVar
b) adding #import and #extends directives dynamically based on
the source
If preprocessors are provided, Cheetah pipes the source code
through each one in the order provided. Each preprocessor should
accept the args (source, file) and should return a tuple (source,
file).
The argument value should be a list, but a single non-list value
is acceptable and will automatically be converted into a list.
Each item in the list will be passed through
Template._normalizePreprocessor(). The items should either match
one of the following forms:
- an object with a .preprocess(source, file) method
- a callable with the following signature:
source, file = f(source, file)
or one of the forms below:
- a single string denoting the 2 'tokens' for the preprocess
syntax. The tokens should be in the order (placeholderToken,
directiveToken) and should separated with a space:
e.g. '@ %'
klass = Template.compile(src, preprocessors='@ %')
# or
klass = Template.compile(src, preprocessors=['@ %'])
- a dict with the following keys or an object with the
following attributes (all are optional, but nothing will
happen if you don't provide at least one):
- tokens: same as the single string described above. You can
also provide a tuple of 2 strings.
- searchList: the searchList used for preprocess $placeholders
- compilerSettings: used in the compilation of the intermediate
template
- templateAPIClass: an optional subclass of `Template`
- outputTransformer: a simple hook for passing in a callable
which can do further transformations of the preprocessor
output, or do something else like debug logging. The
default is str().
+ any keyword arguments to Template.compile which you want to
provide for the compilation of the intermediate template.
klass = Template.compile(src,
preprocessors=[ dict(tokens='@ %', searchList=[...]) ] )
"""
##################################################
## normalize and validate args
N = types.NoneType; S = types.StringType; U = types.UnicodeType
D = types.DictType; F = types.FileType
C = types.ClassType; M = types.ModuleType
I = types.IntType; B = types.BooleanType
errmsg = "arg '%s' must be %s"
t = type(source)
if not (t is N or t is S or t is U):
raise TypeError(errmsg % ('source', 'string or None'))
t = type(file)
if not (t is N or t is S or t is U or t is F):
raise TypeError(errmsg %
('file', 'string, file-like object, or None'))
if baseclass is Unspecified:
baseclass = klass._CHEETAH_defaultBaseclassForTemplates
if isinstance(baseclass, Template):
baseclass = baseclass.__class__
t = type(baseclass)
if not (t is N or t is S or t is C or t is type):
raise TypeError(errmsg % ('baseclass', 'string, class or None'))
if cacheCompilationResults is Unspecified:
cacheCompilationResults = klass._CHEETAH_cacheCompilationResults
t = type(cacheCompilationResults)
if not (t is I or t is B):
raise TypeError(errmsg % ('cacheCompilationResults', 'boolean'))
if useCache is Unspecified:
useCache = klass._CHEETAH_useCompilationCache
t = type(useCache)
if not (t is I or t is B):
raise TypeError(errmsg % ('useCache', 'boolean'))
if compilerSettings is Unspecified:
compilerSettings = klass._getCompilerSettings(source, file) or {}
if type(compilerSettings) is not D:
raise TypeError(errmsg % ('compilerSettings', 'dictionary'))
if compilerClass is Unspecified:
compilerClass = klass._getCompilerClass(source, file)
if preprocessors is Unspecified:
preprocessors = klass._CHEETAH_preprocessors
if keepRefToGeneratedCode is Unspecified:
keepRefToGeneratedCode = klass._CHEETAH_keepRefToGeneratedCode
t = type(keepRefToGeneratedCode)
if not (t is I or t is B):
raise TypeError(errmsg % ('keepReftoGeneratedCode', 'boolean'))
t = type(moduleName)
if not (t is N or t is S):
raise TypeError(errmsg % ('moduleName', 'string or None'))
__orig_file__ = None
if not moduleName:
if file and type(file) in StringTypes:
moduleName = convertTmplPathToModuleName(file)
__orig_file__ = file
else:
moduleName = klass._CHEETAH_defaultModuleNameForTemplates
if className is Unspecified:
className = klass._CHEETAH_defaultClassNameForTemplates
t = type(className)
if not (t is N or t is S):
raise TypeError(errmsg % ('className', 'string or None'))
className = className or moduleName
if mainMethodName is Unspecified:
mainMethodName = klass._CHEETAH_defaultMainMethodNameForTemplates
t = type(mainMethodName)
if not (t is N or t is S):
raise TypeError(errmsg % ('mainMethodName', 'string or None'))
if moduleGlobals is Unspecified:
moduleGlobals = klass._CHEETAH_defaultModuleGlobalsForTemplates
if cacheModuleFilesForTracebacks is Unspecified:
cacheModuleFilesForTracebacks = klass._CHEETAH_cacheModuleFilesForTracebacks
t = type(cacheModuleFilesForTracebacks)
if not (t is I or t is B):
raise TypeError(errmsg %
('cacheModuleFilesForTracebacks', 'boolean'))
if cacheDirForModuleFiles is Unspecified:
cacheDirForModuleFiles = klass._CHEETAH_cacheDirForModuleFiles
t = type(cacheDirForModuleFiles)
if not (t is N or t is S):
raise TypeError(errmsg %
('cacheDirForModuleFiles', 'string or None'))
##################################################
## handle any preprocessors
if preprocessors:
origSrc = source
source, file = klass._preprocessSource(source, file, preprocessors)
##################################################
## compilation, using cache if requested/possible
baseclassValue = None
baseclassName = None
if baseclass:
if type(baseclass) in StringTypes:
baseclassName = baseclass
elif type(baseclass) in (ClassType, type):
# @@TR: should soft-code this
baseclassName = 'CHEETAH_dynamicallyAssignedBaseClass_'+baseclass.__name__
baseclassValue = baseclass
cacheHash = None
cacheItem = None
if source or isinstance(file, basestring):
compilerSettingsHash = None
if compilerSettings:
compilerSettingsHash = hashDict(compilerSettings)
moduleGlobalsHash = None
if moduleGlobals:
moduleGlobalsHash = hashDict(moduleGlobals)
fileHash = None
if file:
fileHash = str(hash(file))
if globals()['__checkFileMtime']:
fileHash += str(os.path.getmtime(file))
try:
# @@TR: find some way to create a cacheHash that is consistent
# between process restarts. It would allow for caching the
# compiled module on disk and thereby reduce the startup time
# for applications that use a lot of dynamically compiled
# templates.
cacheHash = ''.join([str(v) for v in
[hash(source),
fileHash,
className,
moduleName,
mainMethodName,
hash(compilerClass),
hash(baseclass),
compilerSettingsHash,
moduleGlobalsHash,
hash(cacheDirForModuleFiles),
]])
except:
#@@TR: should add some logging to this
pass
outputEncoding = 'ascii'
if useCache and cacheHash and cacheHash in klass._CHEETAH_compileCache:
cacheItem = klass._CHEETAH_compileCache[cacheHash]
generatedModuleCode = cacheItem.code
else:
compiler = compilerClass(source, file,
moduleName=moduleName,
mainClassName=className,
baseclassName=baseclassName,
mainMethodName=mainMethodName,
settings=(compilerSettings or {}))
if commandlineopts:
compiler.setShBang(commandlineopts.shbang)
compiler.compile()
generatedModuleCode = compiler.getModuleCode()
outputEncoding = compiler.getModuleEncoding()
if not returnAClass:
# This is a bit of a hackish solution to make sure we're setting the proper
# encoding on generated code that is destined to be written to a file
if not outputEncoding == 'ascii':
generatedModuleCode = generatedModuleCode.split('\n')
generatedModuleCode.insert(1, '# -*- coding: %s -*-' % outputEncoding)
generatedModuleCode = '\n'.join(generatedModuleCode)
return generatedModuleCode.encode(outputEncoding)
else:
if cacheItem:
cacheItem.lastCheckoutTime = time.time()
return cacheItem.klass
try:
klass._CHEETAH_compileLock.acquire()
uniqueModuleName = _genUniqueModuleName(moduleName)
__file__ = uniqueModuleName+'.py' # relative file path with no dir part
if cacheModuleFilesForTracebacks:
if not os.path.exists(cacheDirForModuleFiles):
raise Exception('%s does not exist'%cacheDirForModuleFiles)
__file__ = os.path.join(cacheDirForModuleFiles, __file__)
# @@TR: might want to assert that it doesn't already exist
open(__file__, 'w').write(generatedModuleCode)
# @@TR: should probably restrict the perms, etc.
mod = new.module(str(uniqueModuleName))
if moduleGlobals:
for k, v in moduleGlobals.items():
setattr(mod, k, v)
mod.__file__ = __file__
if __orig_file__ and os.path.exists(__orig_file__):
# this is used in the WebKit filemonitoring code
mod.__orig_file__ = __orig_file__
if baseclass and baseclassValue:
setattr(mod, baseclassName, baseclassValue)
##
try:
co = compile(generatedModuleCode, __file__, 'exec')
exec co in mod.__dict__
except SyntaxError, e:
try:
parseError = genParserErrorFromPythonException(
source, file, generatedModuleCode, exception=e)
except:
updateLinecache(__file__, generatedModuleCode)
e.generatedModuleCode = generatedModuleCode
raise e
else:
raise parseError
except Exception, e:
updateLinecache(__file__, generatedModuleCode)
e.generatedModuleCode = generatedModuleCode
raise
##
sys.modules[uniqueModuleName] = mod
finally:
klass._CHEETAH_compileLock.release()
templateClass = getattr(mod, className)
if (cacheCompilationResults
and cacheHash
and cacheHash not in klass._CHEETAH_compileCache):
cacheItem = CompileCacheItem()
cacheItem.cacheTime = cacheItem.lastCheckoutTime = time.time()
cacheItem.code = generatedModuleCode
cacheItem.klass = templateClass
templateClass._CHEETAH_isInCompilationCache = True
klass._CHEETAH_compileCache[cacheHash] = cacheItem
else:
templateClass._CHEETAH_isInCompilationCache = False
if keepRefToGeneratedCode or cacheCompilationResults:
templateClass._CHEETAH_generatedModuleCode = generatedModuleCode
return templateClass
compile = classmethod(compile)
def subclass(klass, *args, **kws):
"""Takes the same args as the .compile() classmethod and returns a
template that is a subclass of the template this method is called from.
T1 = Template.compile(' foo - $meth1 - bar\n#def meth1: this is T1.meth1')
T2 = T1.subclass('#implements meth1\n this is T2.meth1')
"""
kws['baseclass'] = klass
if isinstance(klass, Template):
templateAPIClass = klass
else:
templateAPIClass = Template
return templateAPIClass.compile(*args, **kws)
subclass = classmethod(subclass)
def _preprocessSource(klass, source, file, preprocessors):
"""Iterates through the .compile() classmethod's preprocessors argument
and pipes the source code through each each preprocessor.
It returns the tuple (source, file) which is then used by
Template.compile to finish the compilation.
"""
if not isinstance(preprocessors, (list, tuple)):
preprocessors = [preprocessors]
for preprocessor in preprocessors:
preprocessor = klass._normalizePreprocessorArg(preprocessor)
source, file = preprocessor.preprocess(source, file)
return source, file
_preprocessSource = classmethod(_preprocessSource)
def _normalizePreprocessorArg(klass, arg):
"""Used to convert the items in the .compile() classmethod's
preprocessors argument into real source preprocessors. This permits the
use of several shortcut forms for defining preprocessors.
"""
if hasattr(arg, 'preprocess'):
return arg
elif callable(arg):
class WrapperPreprocessor:
def preprocess(self, source, file):
return arg(source, file)
return WrapperPreprocessor()
else:
class Settings(object):
placeholderToken = None
directiveToken = None
settings = Settings()
if isinstance(arg, str) or isinstance(arg, (list, tuple)):
settings.tokens = arg
elif isinstance(arg, dict):
for k, v in arg.items():
setattr(settings, k, v)
else:
settings = arg
settings = klass._normalizePreprocessorSettings(settings)
return klass._CHEETAH_defaultPreprocessorClass(settings)
_normalizePreprocessorArg = classmethod(_normalizePreprocessorArg)
def _normalizePreprocessorSettings(klass, settings):
settings.keepRefToGeneratedCode = True
def normalizeSearchList(searchList):
if not isinstance(searchList, (list, tuple)):
searchList = [searchList]
return searchList
def normalizeTokens(tokens):
if isinstance(tokens, str):
return tokens.split() # space delimited string e.g.'@ %'
elif isinstance(tokens, (list, tuple)):
return tokens
else:
raise PreprocessError('invalid tokens argument: %r'%tokens)
if hasattr(settings, 'tokens'):
(settings.placeholderToken,
settings.directiveToken) = normalizeTokens(settings.tokens)
if (not getattr(settings,'compilerSettings', None)
and not getattr(settings, 'placeholderToken', None) ):
raise TypeError(
'Preprocessor requires either a "tokens" or a "compilerSettings" arg.'
' Neither was provided.')
if not hasattr(settings, 'templateInitArgs'):
settings.templateInitArgs = {}
if 'searchList' not in settings.templateInitArgs:
if not hasattr(settings, 'searchList') and hasattr(settings, 'namespaces'):
settings.searchList = settings.namespaces
elif not hasattr(settings, 'searchList'):
settings.searchList = []
settings.templateInitArgs['searchList'] = settings.searchList
settings.templateInitArgs['searchList'] = (
normalizeSearchList(settings.templateInitArgs['searchList']))
if not hasattr(settings, 'outputTransformer'):
settings.outputTransformer = unicode
if not hasattr(settings, 'templateAPIClass'):
class PreprocessTemplateAPIClass(klass): pass
settings.templateAPIClass = PreprocessTemplateAPIClass
if not hasattr(settings, 'compilerSettings'):
settings.compilerSettings = {}
klass._updateSettingsWithPreprocessTokens(
compilerSettings=settings.compilerSettings,
placeholderToken=settings.placeholderToken,
directiveToken=settings.directiveToken
)
return settings
_normalizePreprocessorSettings = classmethod(_normalizePreprocessorSettings)
def _updateSettingsWithPreprocessTokens(
klass, compilerSettings, placeholderToken, directiveToken):
if (placeholderToken and 'cheetahVarStartToken' not in compilerSettings):
compilerSettings['cheetahVarStartToken'] = placeholderToken
if directiveToken:
if 'directiveStartToken' not in compilerSettings:
compilerSettings['directiveStartToken'] = directiveToken
if 'directiveEndToken' not in compilerSettings:
compilerSettings['directiveEndToken'] = directiveToken
if 'commentStartToken' not in compilerSettings:
compilerSettings['commentStartToken'] = directiveToken*2
if 'multiLineCommentStartToken' not in compilerSettings:
compilerSettings['multiLineCommentStartToken'] = (
directiveToken+'*')
if 'multiLineCommentEndToken' not in compilerSettings:
compilerSettings['multiLineCommentEndToken'] = (
'*'+directiveToken)
if 'EOLSlurpToken' not in compilerSettings:
compilerSettings['EOLSlurpToken'] = directiveToken
_updateSettingsWithPreprocessTokens = classmethod(_updateSettingsWithPreprocessTokens)
def _addCheetahPlumbingCodeToClass(klass, concreteTemplateClass):
"""If concreteTemplateClass is not a subclass of Cheetah.Template, add
the required cheetah methods and attributes to it.
This is called on each new template class after it has been compiled.
If concreteTemplateClass is not a subclass of Cheetah.Template but
already has method with the same name as one of the required cheetah
methods, this will skip that method.
"""
for methodname in klass._CHEETAH_requiredCheetahMethods:
if not hasattr(concreteTemplateClass, methodname):
method = getattr(Template, methodname)
newMethod = new.instancemethod(method.im_func, None, concreteTemplateClass)
#print methodname, method
setattr(concreteTemplateClass, methodname, newMethod)
for classMethName in klass._CHEETAH_requiredCheetahClassMethods:
if not hasattr(concreteTemplateClass, classMethName):
meth = getattr(klass, classMethName)
setattr(concreteTemplateClass, classMethName, classmethod(meth.im_func))
for attrname in klass._CHEETAH_requiredCheetahClassAttributes:
attrname = '_CHEETAH_'+attrname
if not hasattr(concreteTemplateClass, attrname):
attrVal = getattr(klass, attrname)
setattr(concreteTemplateClass, attrname, attrVal)
if (not hasattr(concreteTemplateClass, '__str__')
or concreteTemplateClass.__str__ is object.__str__):
mainMethNameAttr = '_mainCheetahMethod_for_'+concreteTemplateClass.__name__