Debian Codegraph @

docs/users_guide/tipsAndTricks.rst

raw
1 Tips, Tricks and Troubleshooting
2 ================================
3
4
5 This chapter contains short stuff that doesn't fit anywhere else.
6
7 See the Cheetah FAQ for more specialized issues and for
8 troubleshooting tips. Check the wiki periodically for recent tips
9 contributed by users. If you get stuck and none of these resources
10 help, ask on the mailing list.
11
12 Placeholder Tips
13 ----------------
14
15
16 Here's how to do certain important lookups that may not be obvious.
17 For each, we show first the Cheetah expression and then the Python
18 equivalent, because you can use these either in templates or in
19 pure Python subclasses. The Cheetah examples use NameMapper
20 shortcuts (uniform dotted notation, autocalling) as much as
21 possible.
22
23 To verify whether a variable exists in the searchList:
24
25 ::
26
27 $varExists('theVariable')
28 self.varExists('theVariable')
29
30 This is useful in {#if} or {#unless} constructs to avoid a
31 {#NameMapper.NotFound} error if the variable doesn't exist. For
32 instance, a CGI GET parameter that is normally supplied but in this
33 case the user typed the URL by hand and forgot the parameter (or
34 didn't know about it). ({.hasVar} is a synonym for {.varExists}.)
35
36 To look up a variable in the searchList from a Python method:
37
38 ::
39
40 self.getVar('theVariable')
41 self.getVar('theVariable', myDefault)
42
43 This is the equivalent to {$theVariable} in the template. If the
44 variable is missing, it returns the second argument, {myDefault},
45 if present, or raises {NameMapper.NotFound} if there is no second
46 argument. However, it usually easier to write your method so that
47 all needed searchList values come in as method arguments. That way
48 the caller can just use a {$placeholder} to specify the argument,
49 which is less verbose than you writing a getVar call.
50
51 To do a "safe" placeholder lookup that returns a default value if
52 the variable is missing:
53
54 ::
55
56 $getVar('theVariable', None)
57 $getVar('theVariable', $myDefault)
58
59 To get an environmental variable, put {os.environ} on the
60 searchList as a container. Or read the envvar in Python code and
61 set a placeholder variable for it.
62
63 Remember that variables found earlier in the searchList override
64 same-name variables located in a later searchList object. Be
65 careful when adding objects containing other variables besides the
66 ones you want (e.g., {os.environ}, CGI parameters). The "other"
67 variables may override variables your application depends on,
68 leading to hard-to-find bugs. Also, users can inadvertently or
69 maliciously set an environmental variable or CGI parameter you
70 didn't expect, screwing up your program. To avoid all this, know
71 what your namespaces contain, and place the namespaces you have the
72 most control over first. For namespaces that could contain
73 user-supplied "other" variables, don't put the namespace itself in
74 the searchList; instead, copy the needed variables into your own
75 "safe" namespace.
76
77 Diagnostic Output
78 -----------------
79
80
81 If you need send yourself some debugging output, you can use
82 {#silent} to output it to standard error:
83
84 ::
85
86 #silent $sys.stderr.write("Incorrigible var is '$incorrigible'.\n")
87 #silent $sys.stderr.write("Is 'unknown' in the searchList? " +
88 $getVar("unknown", "No.") + "\n" )
89
90
91 When to use Python methods
92 --------------------------
93
94
95 You always have a choice whether to code your methods as Cheetah
96 {#def} methods or Python methods (the Python methods being located
97 in a class your template inherits). So how do you choose?
98
99 Generally, if the method consists mostly of text and placeholders,
100 use a Cheetah method (a {#def} method). That's why {#def} exists,
101 to take the tedium out of writing those kinds of methods. And if
102 you have a couple {#if} stanzas to {#set} some variables, followed
103 by a {#for} loop, no big deal. But if your method consists mostly
104 of directives and only a little text, you're better off writing it
105 in Python. Especially be on the watch for extensive use of {#set},
106 {#echo} and {#silent} in a Cheetah method-it's a sure sign you're
107 probably using the wrong language. Of course, though, you are free
108 to do so if you wish.
109
110 Another thing that's harder to do in Cheetah is adjacent or nested
111 multiline stanzas (all those directives with an accompanying {#end}
112 directive). Python uses indentation to show the beginning and end
113 of nested stanzas, but Cheetah can't do that because any
114 indentation shows up in the output, which may not be desired. So
115 unless all those extra spaces and tabs in the output are
116 acceptable, you have to keep directives flush with the left margin
117 or the preceding text.
118
119 The most difficult decisions come when you have conflicting goals.
120 What if a method generates its output in parts (i.e., output
121 concatenation), contains many searchList placeholders and lots of
122 text, { and} requires lots of {#if ... #set ... #else #set ... #end
123 if} stanzas. A Cheetah method would be more advantageous in some
124 ways, but a Python method in others. You'll just have to choose,
125 perhaps coding groups of methods all the same way. Or maybe you can
126 split your method into two, one Cheetah and one Python, and have
127 one method call the other. Usually this means the Cheetah method
128 calling the Python method to calculate the needed values, then the
129 Cheetah method produces the output. One snag you might run into
130 though is that {#set} currently can set only one variable per
131 statement, so if your Python method needs to return multiple values
132 to your Cheetah method, you'll have to do it another way.
133
134 Calling superclass methods, and why you have to
135 -----------------------------------------------
136
137
138 If your template or pure Python class overrides a standard method
139 or attribute of {Template} or one of its base classes, you should
140 call the superclass method in your method to prevent various things
141 from breaking. The most common methods to override are {.awake} and
142 {.\_\_init\_\_}. {.awake} is called automatically by Webware early
143 during the web transaction, so it makes a convenient place to put
144 Python initialization code your template needs. You'll definitely
145 want to call the superclass {.awake} because it sets up many
146 wonderful attributes and methods, such as those to access the CGI
147 input fields.
148
149 There's nothing Cheetah-specific to calling superclass methods, but
150 because it's vital, we'll recap the standard Python techniques
151 here. We mention only the solution for old-style classes because
152 Cheetah classes are old-style (in other Python documentation, you
153 will find the technique for new-style classes, but they are not
154 listed here because they cannot be used with Cheetah if you use
155 dynamically-compiled templates).
156
157 ::
158
159 from Cheetah.Template import Template
160 class MyClass(Template):
161 def awake(self, trans):
162 Template.awake(self, trans)
163 ... great and exciting features written by me ...
164
165 [ @@MO: Need to test this. .awake is in Servlet, which is a
166 superclass of Template. Do we really need both imports? Can we call
167 Template.awake? ]
168
169 To avoid hardcoding the superclass name, you can use this function
170 {callbase()}, which emulates {super()} for older versions of
171 Python. It also works even {super()} does exist, so you don't have
172 to change your servlets immediately when upgrading. Note that the
173 argument sequence is different than {super} uses.
174
175 ::
176
177 ===========================================================================
178 # Place this in a module SOMEWHERE.py . Contributed by Edmund Lian.
179 class CallbaseError(AttributeError):
180 pass
181
182 def callbase(obj, base, methodname='__init__', args=(), kw={},
183 raiseIfMissing=None):
184 try: method = getattr(base, methodname)
185 except AttributeError:
186 if raiseIfMissing:
187 raise CallbaseError, methodname
188 return None
189 if args is None: args = ()
190 return method(obj, *args, **kw)
191 ===========================================================================
192 # Place this in your class that's overriding .awake (or any method).
193 from SOMEWHERE import callbase
194 class MyMixin:
195 def awake(self, trans):
196 args = (trans,)
197 callbase(self, MyMixin, 'awake', args)
198 ... everything else you want to do ...
199 ===========================================================================
200
201 All methods
202 -----------
203
204
205 Here is a list of all the standard methods and attributes that can
206 be accessed from a placeholder. Some of them exist for you to call,
207 others are mainly used by Cheetah internally but you can call them
208 if you wish, and others are only for internal use by Cheetah or
209 Webware. Do not use these method names in mixin classes
210 ({#extends}, section inheritanceEtc.extends) unless you intend to
211 override the standard method.
212
213 Variables with a star prefix ({ \*}) are frequently used in
214 templates or in pure Python classes.
215
216 \*{Inherited from Cheetah.Template}
217
218 Compile the template. Automatically called by {.\_\_init\_\_}.
219
220 Return the module code the compiler generated, or {None} if no
221 compilation took place.
222
223 Return the class code the compiler generated, or {None} if no
224 compilation took place.
225
226 Return a reference to the underlying search list. (a list of
227 objects). Use this to print out your searchList for debugging.
228 Modifying the returned list will affect your placeholder searches!
229
230 Return a reference to the current error catcher.
231
232 If 'cacheKey' is not {None}, refresh that item in the cache. If
233 {None}, delete all items in the cache so they will be recalculated
234 the next time they are encountered.
235
236 Break reference cycles before discarding a servlet.
237
238 Look up a variable in the searchList. Same as {$varName} but allows
239 you to specify a default value and control whether autocalling
240 occurs.
241
242 Read the named file. If used as a placeholder, inserts the file's
243 contents in the output without interpretation, like {#include raw}.
244 If used in an expression, returns the file's content (e.g., to
245 assign it to a variable).
246
247 This is what happens if you run a .py template module as a
248 standalone program.
249
250
251 \*{Inherited from Cheetah.Utils.WebInputMixin}
252
253 Exception raised by {.webInput}.
254
255 Convenience method to access GET/POST variables from a Webware
256 servlet or CGI script, or Webware cookie or session variables. See
257 section webware.webInput for usage information.
258
259
260 \*{Inherited from Cheetah.SettingsManager}
261
262 Get a compiler setting.
263
264 Does this compiler setting exist?
265
266 Set setting 'name' to 'value'. See {#compiler-settings}, section
267 parserInstructions.compiler-settings.
268
269 Return the underlying settings dictionary. (Warning: modifying this
270 dictionary will change Cheetah's behavior.)
271
272 Return a copy of the underlying settings dictionary.
273
274 Return a deep copy of the underlying settings dictionary. See
275 Python's {copy} module.
276
277 Update Cheetah's compiler settings from the 'newSettings'
278 dictionary. If 'merge' is true, update only the names in
279 newSettings and leave the other names alone. (The SettingsManager
280 is smart enough to update nested dictionaries one key at a time
281 rather than overwriting the entire old dictionary.) If 'merge' is
282 false, delete all existing settings so that the new ones are the
283 only settings.
284
285 Same, but pass a string of {name=value} pairs rather than a
286 dictionary, the same as you would provide in a {#compiler-settings}
287 directive, section parserInstructions.compiler-settings.
288
289 Same, but exec a Python source file and use the variables it
290 contains as the new settings. (e.g.,
291 {cheetahVarStartToken = "@"}).
292
293 Same, but get the new settings from a text file in ConfigParser
294 format (similar to Windows' \*.ini file format). See Python's
295 {ConfigParser} module.
296
297 Same, but read the open file object 'inFile' for the new settings.
298
299 Same, but read the new settings from a string in ConfigParser
300 format.
301
302 Write the current compiler settings to a file named 'path' in
303 \*.ini format.
304
305 Return a string containing the current compiler settings in \*.ini
306 format.
307
308
309 \*{Inherited from Cheetah.Servlet}
310
311 { Do not override these in a subclass or assign to them as
312 attributes if your template will be used as a servlet,} otherwise
313 Webware will behave unpredictably. However, it { is} OK to put
314 same-name variables in the searchList, because Webware does not use
315 the searchList.
316
317 EXCEPTION: It's OK to override { awake} and { sleep} as long as you
318 call the superclass methods. (See section
319 tips.callingSuperclassMethods.)
320
321 True if this template instance is part of a live transaction in a
322 running WebKit servlet.
323
324 True if Webware is installed and the template instance inherits
325 from WebKit.Servlet. If not, it inherits from
326 Cheetah.Servlet.DummyServlet.
327
328 Called by WebKit at the beginning of the web transaction.
329
330 Called by WebKit at the end of the web transaction.
331
332 Called by WebKit to produce the web transaction content. For a
333 template-servlet, this means filling the template.
334
335 Break reference cycles before deleting instance.
336
337 The filesystem pathname of the template-servlet (as opposed to the
338 URL path).
339
340 The current Webware transaction.
341
342 The current Webware application.
343
344 The current Webware response.
345
346 The current Webware request.
347
348 The current Webware session.
349
350 Call this method to insert text in the filled template output.
351
352
353 Several other goodies are available to template-servlets under the
354 {request} attribute, see section webware.input.
355
356 {transaction}, {response}, {request} and {session} are created from
357 the current transaction when WebKit calls {awake}, and don't exist
358 otherwise. Calling {awake} yourself (rather than letting WebKit
359 call it) will raise an exception because the {transaction} argument
360 won't have the right attributes.
361
362 \*{Inherited from WebKit.Servlet} These are accessible only if
363 Cheetah knows Webware is installed. This listing is based on a CVS
364 snapshot of Webware dated 22 September 2002, and may not include
365 more recent changes.
366
367 The same caveats about overriding these methods apply.
368
369 The simple name of the class. Used by Webware's logging and
370 debugging routines.
371
372 Used by Webware's logging and debugging routines.
373
374 True if the servlet can be multithreaded.
375
376 True if the servlet can be used for another transaction after the
377 current transaction is finished.
378
379 Depreciated by {.serverSidePath()}.
380
381
382 Optimizing templates
383 --------------------
384
385
386 Here are some things you can do to make your templates fill faster
387 and user fewer CPU cycles. Before you put a lot of energy into
388 this, however, make sure you really need to. In many situations,
389 templates appear to initialize and fill instantaneously, so no
390 optimization is necessary. If you do find a situation where your
391 templates are filling slowly or taking too much memory or too many
392 CPU cycles, we'd like to hear about it on the mailing list.
393
394 Cache $placeholders whose values don't change frequently. (Section
395 output.caching).
396
397 Use {#set} for values that are very frequently used, especially if
398 they come out of an expensive operation like a
399 deeply.nested.structure or a database lookup. {#set} variables are
400 set to Python local variables, which have a faster lookup time than
401 Python globals or values from Cheetah's searchList.
402
403 Moving variable lookups into Python code may provide a speedup in
404 certain circumstances. If you're just reading {self} attributes,
405 there's no reason to use NameMapper lookup ($placeholders) for
406 them. NameMapper does a lot more work than simply looking up a
407 {self} attribute.
408
409 On the other hand, if you don't know exactly where the value will
410 come from (maybe from {self}, maybe from the searchList, maybe from
411 a CGI input variable, etc), it's easier to just make that an
412 argument to your method, and then the template can handle all the
413 NameMapper lookups for you:
414
415 ::
416
417 #silent $myMethod($arg1, $arg2, $arg3)
418
419 Otherwise you'd have to call {self.getVar('arg1')} etc in your
420 method, which is more wordy, and tedious.
421
422 PSP-style tags
423 --------------
424
425
426 {<%= ... %>} and {<% ... %>} allow an escape to Python syntax
427 inside the template. You do not need it to use Cheetah effectively,
428 and we're hard pressed to think of a case to recommend it.
429 Nevertheless, it's there in case you encounter a situation you
430 can't express adequately in Cheetah syntax. For instance, to set a
431 local variable to an elaborate initializer.
432
433 {<%= ... %>} encloses a Python expression whose result will be
434 printed in the output.
435
436 {<% ... %>} encloses a Python statement or expression (or set of
437 statements or expressions) that will be included as-is into the
438 generated method. The statements themselves won't produce any
439 output, but you can use the local function {write(EXPRESSION)} to
440 produce your own output. (Actually, it's a method of a file-like
441 object, but it looks like a local function.) This syntax also may
442 be used to set a local variable with a complicated initializer.
443
444 To access Cheetah services, you must use Python code like you would
445 in an inherited Python class. For instance, use {self.getVar()} to
446 look up something in the searchList.
447
448 { Warning:} { No error checking is done!} If you write:
449
450 ::
451
452 <% break %> ## Wrong!
453
454 you'll get a {SyntaxError} when you fill the template, but that's
455 what you deserve.
456
457 Note that these are PSP-{ style} tags, not PSP tags. A Cheetah
458 template is not a PSP document, and you can't use PSP commands in
459 it.
460
461 Calling one template from another
462 ---------------------------------
463
464 Cheetah templates are really python modules in disguise. I.e., when
465 Cheetah loads a template it compiles it to python code and then to byte
466 code. Every template is compiled as a single class. The thing is,
467 neither the source code nor byte code are saved to files automatically.
468
469 There are a few ways to allow a user to import one template (python
470 module!) from another.
471
472 1. A user can compile templates to `*.py` files using `cheetah compile`
473 command line program. Then import works at the Python level.
474
475 To semi-automatically compile all templates after editing them one can
476 use the following `Makefile` (GNU flavour)::
477
478 .SUFFIXES: # Clear the suffix list
479 .SUFFIXES: .py .tmpl
480
481 %.py: %.tmpl
482 cheetah compile --nobackup $<
483 python -m compile $@
484
485 templates = $(shell echo \*.tmpl)
486 modules = $(patsubst %.tmpl,%.py,$(templates))
487
488 .PHONY: all
489 all: $(modules)
490
491 (Don't forget - makefiles require indent with tabs, not spaces.)
492
493 2. Subvert Python import to make Cheetah import directly from `*.tmpl`
494 files using `import hooks <../api/Cheetah.ImportHooks.html>`_.
495
496 Example code::
497
498 from Cheetah import ImportHooks
499 ImportHooks.install()
500
501 import sys
502 sys.path.insert(0, 'path/to/template_dir') # or sys.path.append
503
504 ImportHooks try to import from `*.pyc`, `*.py` and `*.tmpl` - whatever
505 is found first. ImportHooks automatically compile `*.tmpl` to `*.py` and
506 `*.pyc`.
507
508 Makefiles
509 ---------
510
511
512 If your project has several templates and you get sick of typing
513 "cheetah compile FILENAME.tmpl" all the time-much less remembering
514 which commands to type when-and your system has the {make} command
515 available, consider building a Makefile to make your life easier.
516
517 Here's a simple Makefile that controls two templates,
518 ErrorsTemplate and InquiryTemplate. Two external commands,
519 {inquiry} and {receive}, depend on ErrorsTemplate.py. Aditionally,
520 InquiryTemplate itself depends on ErrorsTemplate.
521
522 ::
523
524 all: inquiry receive
525
526 .PHONY: all receive inquiry printsource
527
528 printsource:
529 a2ps InquiryTemplate.tmpl ErrorsTemplate.tmpl
530
531 ErrorsTemplate.py: ErrorsTemplate.tmpl
532 cheetah compile ErrorsTemplate.tmpl
533
534 InquiryTemplate.py: InquiryTemplate.tmpl ErrorsTemplate.py
535 cheetah compile InquiryTemplate.tmpl
536
537 inquiry: InquiryTemplate.py ErrorsTemplate.py
538
539 receive: ErrorsTemplate.py
540
541 Now you can type {make} anytime and it will recompile all the
542 templates that have changed, while ignoring the ones that haven't.
543 Or you can recompile all the templates {receive} needs by typing
544 {make receive}. Or you can recompile only ErrorsTemplate by typing
545 {make ErrorsTemplate}. There's also another target, "printsource":
546 this sends a Postscript version of the project's source files to
547 the printer. The .PHONY target is explained in the {make}
548 documentation; essentially, you have it depend on every target that
549 doesn't produce an output file with the same name as the target.
550
551 Using Cheetah in a Multi-Threaded Application
552 ---------------------------------------------
553
554
555 Template classes may be shared freely between threads. However,
556 template instances should not be shared unless you either:
557
558
559 - Use a lock (mutex) to serialize template fills, to prevent two
560 threads from filling the template at the same time.
561
562 - Avoid thread-unsafe features:
563
564
565 - Modifying searchList values or instance variables.
566
567 - Caching ({$\*var}, {#cache}, etc).
568
569 - {#set global}, {#filter}, {#errorCatcher}.
570
571
572 Any changes to these in one thread will be visible in other
573 threads, causing them to give inconsistent output.
574
575
576 About the only advantage in sharing a template instance is building
577 up the placeholder cache. But template instances are so low
578 overhead that it probably wouldn't take perceptibly longer to let
579 each thread instantiate its own template instance. Only if you're
580 filling templates several times a second would the time difference
581 be significant, or if some of the placeholders trigger extremely
582 slow calculations (e.g., parsing a long text file each time). The
583 biggest overhead in Cheetah is importing the {Template} module in
584 the first place, but that has to be done only once in a
585 long-running application.
586
587 You can use Python's {mutex} module for the lock, or any similar
588 mutex. If you have to change searchList values or instance
589 variables before each fill (which is usually the case), lock the
590 mutex before doing this, and unlock it only after the fill is
591 complete.
592
593 For Webware servlets, you're probably better off using Webware's
594 servlet caching rather than Cheetah's caching. Don't override the
595 servlet's {.canBeThreaded()} method unless you avoid the unsafe
596 operations listed above.
597
598 Using Cheetah with gettext
599 --------------------------
600
601
602 { gettext} is a project for creating internationalized
603 applications. For more details, visit
604 http://docs.python.org/lib/module-gettext.html. gettext can be used
605 with Cheetah to create internationalized applications, even for CJK
606 character sets, but you must keep a couple things in mind:
607
608
609 - xgettext is used on compiled templates, not on the templates
610 themselves.
611
612 - The way the NameMapper syntax gets compiled to Python gets in
613 the way of the syntax that xgettext recognizes. Hence, a special
614 case exists for the functions {\_}, {N\_}, and {ngettext}. If you
615 need to use a different set of functions for marking strings for
616 translation, you must set the Cheetah setting {gettextTokens} to a
617 list of strings representing the names of the functions you are
618 using to mark strings for translation.
619
620
621