Debian Codegraph @

docs/users_guide/webware.rst

raw
1 Using Cheetah with Webware
2 ==========================
3
4
5 { Webware for Python} is a 'Python-Powered Internet Platform' that
6 runs servlets in a manner similar to Java servlets. { WebKit} is
7 the name of Webware's application server. For more details, please
8 visit https://cito.github.io/w4py/.
9
10 All comments below refer to the official version of Webware, the
11 DamnSimple! offshoot at ?, and the now-abandoned
12 WebwareExperimental implementation at
13 http://sourceforge.net/projects/expwebware/, except where noted.
14 All the implementations are 95% identical to the servlet writer:
15 their differences lie in their internal structure and configuration
16 files. One difference is that the executable you run to launch
17 standard Webware is called {AppServer}, whereas in
18 WebwareExperimental it's called {webkit}. But to servlets they're
19 both "WebKit, Webware's application server", so it's one half dozen
20 to the other. In this document, we generally use the term { WebKit}
21 to refer to the currently-running application server.
22
23 Installing Cheetah on a Webware system
24 --------------------------------------
25
26
27 Install Cheetah after you have installed Webware, following the
28 instructions in chapter gettingStarted.
29
30 The standard Cheetah test suite ('cheetah test') does not test
31 Webware features. We plan to build a test suite that can run as a
32 Webware servlet, containing Webware-specific tests, but that has
33 not been built yet. In the meantime, you can make a simple template
34 containing something like "This is a very small template.", compile
35 it, put the \*.py template module in a servlet directory, and see
36 if Webware serves it up OK.
37
38 { You must not have a Webware context called "Cheetah".} If you do,
39 Webware will mistake that directory for the Cheetah module
40 directory, and all template-servlets will bomb out with a
41 "ImportError: no module named Template". (This applies only to the
42 standard Webware; WebwareExperimental does not have contexts.)
43
44 If Webware complains that it cannot find your servlet, make sure
45 '.tmpl' is listed in 'ExtensionsToIgnore' in your
46 'Application.config' file.
47
48 Containment vs Inheritance
49 --------------------------
50
51
52 Because Cheetah's core is flexible, there are many ways to
53 integrate it with Webware servlets. There are two broad strategies:
54 the { Inheritance approach} and the { Containment approach}. The
55 difference is that in the Inheritance approach, your template
56 object { is} the servlet, whereas in the Containment approach, the
57 servlet is not a template but merely { uses} template(s) for
58 portion(s) of its work.
59
60 The Inheritance approach is recommended for new sites because it's
61 simpler, and because it scales well for large sites with a
62 site->section->subsection->servlet hierarchy. The Containment
63 approach is better for existing servlets that you don't want to
64 restructure. For instance, you can use the Containment approach to
65 embed a discussion-forum table at the bottom of a web page.
66
67 However, most people who use Cheetah extensively seem to prefer the
68 Inheritance approach because even the most analytical servlet needs
69 to produce { some} output, and it has to fit the site's look and
70 feel { anyway}, so you may as well use a template-servlet as the
71 place to put the output. Especially since it's so easy to add a
72 template-servlet to a site once the framework is established. So we
73 recommend you at least evaluate the effort that would be required
74 to convert your site framework to template superclasses as
75 described below, vs the greater flexibility and manageability it
76 might give the site over the long term. You don't necessarily have
77 to convert all your existing servlets right away: just build common
78 site templates that are visually and behaviorally compatible with
79 your specification, and use them for new servlets. Existing
80 servlets can be converted later, if at all.
81
82 Edmund Liam is preparing a section on a hybrid approach, in which
83 the servlet is not a template, but still calls template(s) in an
84 inheritance chain to produce the output. The advantage of this
85 approach is that you aren't dealing with {Template} methods and
86 Webware methods in the same object.
87
88 The Containment Approach
89 ~~~~~~~~~~~~~~~~~~~~~~~~
90
91
92 In the Containment approach, your servlet is not a template.
93 Instead, it it makes its own arrangements to create and use
94 template object(s) for whatever it needs. The servlet must
95 explicitly call the template objects' {.respond()} (or
96 {.\_\_str\_\_()}) method each time it needs to fill the template.
97 This does not present the output to the user; it merely gives the
98 output to the servlet. The servlet then calls its
99 {#self.response().write()} method to send the output to the user.
100
101 The developer has several choices for managing her templates. She
102 can store the template definition in a string, file or database and
103 call {Cheetah.Template.Template} manually on it. Or she can put the
104 template definition in a \*.tmpl file and use { cheetah compile}
105 (section howWorks.cheetah-compile) to convert it to a Python class
106 in a \*.py module, and then import it into her servlet.
107
108 Because template objects are not thread safe, you should not store
109 one in a module variable and allow multiple servlets to fill it
110 simultaneously. Instead, each servlet should instantiate its own
111 template object. Template { classes}, however, are thread safe,
112 since they don't change once created. So it's safe to store a
113 template class in a module global variable.
114
115 The Inheritance Approach
116 ~~~~~~~~~~~~~~~~~~~~~~~~
117
118
119 In the Inheritance approach, your template object doubles as as
120 Webware servlet, thus these are sometimes called {
121 template-servlets}. { cheetah compile} (section
122 howWorks.cheetah-compile) automatically creates modules containing
123 valid Webware servlets. A servlet is a subclass of Webware's
124 {WebKit.HTTPServlet} class, contained in a module with the same
125 name as the servlet. WebKit uses the request URL to find the
126 module, and then instantiates the servlet/template. The servlet
127 must have a {.respond()} method (or {.respondToGet()},
128 {.respondToPut()}, etc., but the Cheetah default is {.respond()}).
129 Servlets created by {cheetah compile} meet all these requirements.
130
131 (Cheetah has a Webware plugin that automatically converts a {.tmpl
132 servlet file} into a {.py servlet file} when the {.tmpl servlet
133 file} is requested by a browser. However, that plugin is currently
134 unavailable because it's being redesigned. For now, use {cheetah
135 compile} instead.)
136
137 What about logic code? Cheetah promises to keep content (the
138 placeholder values), graphic design (the template definition and is
139 display logic), and algorithmic logic (complex calculations and
140 side effects) separate. How? Where do you do form processing?
141
142 The answer is that your template class can inherit from a pure
143 Python class containing the analytical logic. You can either use
144 the {#extends} directive in Cheetah to indicate the superclass(es),
145 or write a Python {class} statement to do the same thing. See the
146 template {Cheetah.Templates.SkeletonPage.tmpl} and its pure Python
147 class {Cheetah.Templates.\_SkeletonPage.py} for an example of a
148 template inheriting logic code. (See sections
149 inheritanceEtc.extends and inheritanceEtc.implements for more
150 information about {#extends} and {#implements}. They have to be
151 used a certain right way.)
152
153 If {#WebKit.HTTPServlet} is not available, Cheetah fakes it with a
154 dummy class to satisfy the dependency. This allows servlets to be
155 tested on the command line even on systems where Webware is not
156 installed. This works only with servlets that don't call back into
157 WebKit for information about the current web transaction, since
158 there is no web transaction. Trying to access form input, for
159 instance, will raise an exception because it depends on a live web
160 request object, and in the dummy class the request object is
161 {None}.
162
163 Because Webware servlets must be valid Python modules, and
164 "cheetah compile" can produce only valid module names, if you're
165 converting an existing site that has .html filenames with hyphens
166 (-), extra dots (.), etc, you'll have to rename them (and possibly
167 use redirects).
168
169 Site frameworks
170 ---------------
171
172
173 Web sites are normally arranged hierarchically, with certain
174 features common to every page on the site, other features common to
175 certain sections or subsections, and others unique to each page.
176 You can model this easily with a hierarchy of classes, with
177 specific servlets inheriting from their more general superclasses.
178 Again, you can do this two ways, using Cheetah's { Containment}
179 approach or { Inheritance} approach.
180
181 In the Inheritance approach, parents provide {#block}s and children
182 override them using {#def}. Each child {#extend}s its immediate
183 parent. Only the leaf servlets need to be under WebKit's document
184 root directory. The superclass servlets can live anywhere in the
185 filesystem that's in the Python path. (You may want to modify your
186 WebKit startup script to add that library directory to your
187 {PYTHONPATH} before starting WebKit.)
188
189 Section libraries.templates.skeletonPage contains information on a
190 stock template that simplifies defining the basic HTML structure of
191 your web page templates.
192
193 In the Containment approach, your hierarchy of servlets are not
194 templates, but each uses one or more templates as it wishes.
195 Children provide callback methods to to produce the various
196 portions of the page that are their responsibility, and parents
197 call those methods. Webware's {WebKit.Page} and
198 {WebKit.SidebarPage} classes operate like this.
199
200 Note that the two approaches are not compatible! {WebKit.Page} was
201 not designed to intermix with {Cheetah.Templates.SkeletonPage}.
202 Choose either one or the other, or expect to do some integration
203 work.
204
205 If you come up with a different strategy you think is worth noting
206 in this chapter, let us know.
207
208 Directory structure
209 -------------------
210
211
212 Here's one way to organize your files for Webware+Cheetah.
213
214 ::
215
216 www/ # Web root directory.
217 site1.example.com/ # Site subdirectory.
218 apache/ # Web server document root (for non-servlets).
219 www/ # WebKit document root.
220 index.py # http://site1.example.com/
221 index.tmpl # Source for above.
222 servlet2.py # http://site1.example.com/servlet2
223 servlet2.tmpl # Source for above.
224 lib/ # Directory for helper classes.
225 Site.py # Site superclass ("#extends Site").
226 Site.tmpl # Source for above.
227 Logic.py # Logic class inherited by some template.
228 webkit.config # Configuration file (for WebwareExperimental).
229 Webware/ # Standard Webware's MakeAppWorkDir directory.
230 AppServer # Startup program (for standard Webware).
231 Configs/ # Configuration directory (for standard Webware).
232 Application.config
233 # Configuration file (for standard Webware).
234 site2.example.org/ # Another virtual host on this computer....
235
236 Initializing your template-servlet with Python code
237 ---------------------------------------------------
238
239
240 If you need a place to initialize variables or do calculations for
241 your template-servlet, you can put it in an {.awake()} method
242 because WebKit automatically calls that early when processing the
243 web transaction. If you do override {.awake()}, be sure to call the
244 superclass {.awake} method. You probably want to do that first so
245 that you have access to the web transaction data {Servlet.awake}
246 provides. You don't have to worry about whether your parent class
247 has its own {.awake} method, just call it anyway, and somebody up
248 the inheritance chain will respond, or at minimum {Servlet.awake}
249 will respond. Section tips.callingSuperclassMethods gives examples
250 of how to call a superclass method.
251
252 As an alternative, you can put all your calculations in your own
253 method and call it near the top of your template. ({#silent},
254 section output.silent).
255
256 Form processing
257 ---------------
258
259
260 There are many ways to display and process HTML forms with Cheetah.
261 But basically, all form processing involves two steps.
262
263
264 #. Display the form.
265
266 #. In the next web request, read the parameters the user submitted,
267 check for user errors, perform any side effects (e.g.,
268 reading/writing a database or session data) and present the user an
269 HTML response or another form.
270
271
272 The second step may involve choosing between several templates to
273 fill (or several servlets to redirect to), or a big
274 if-elif-elif-else construct to display a different portion of the
275 template depending on the situation.
276
277 In the oldest web applications, step 1 and step 2 were handled by
278 separate objects. Step 1 was a static HTML file, and step 2 was a
279 CGI script. Frequently, a better strategy is to have a single
280 servlet handle both steps. That way, the servlet has better control
281 over the entire situation, and if the user submits unacceptable
282 data, the servlet can redisplay the form with a "try again" error
283 message at the top and and all the previous input filled in. The
284 servlet can use the presence or absence of certain CGI parameters
285 (e.g., the submit button, or a hidden mode field) to determine
286 which step to take.
287
288 One neat way to build a servlet that can handle both the form
289 displaying and form processing is like this:
290
291
292 #. Put your form HTML into an ordinary template-servlet. In each
293 input field, use a placeholder for the value of the {VALUE=}
294 attribue. Place another placeholder next to each field, for that
295 field's error message.
296
297 #. Above the form, put a {$processFormData} method call.
298
299 #. Define that method in a Python class your template {#extend}s.
300 (Or if it's a simple method, you can define it in a {#def}.) The
301 method should:
302
303
304 #. Get the form input if any.
305
306 #. If the input variable corresponding to the submit field is
307 empty, there is no form input, so we're showing the form for the
308 first time. Initialize all VALUE= variables to their default value
309 (usually ""), and all error variables to "". Return "", which will
310 be the value for {$processFormData}.
311
312 #. If the submit variable is not empty, fill the VALUE= variables
313 with the input data the user just submitted.
314
315 #. Now check the input for errors and put error messages in the
316 error placeholders.
317
318 #. If there were any user errors, return a general error message
319 string; this will be the value for {$processFormData}.
320
321 #. If there were no errors, do whatever the form's job is (e.g.,
322 update a database) and return a success message; this will be the
323 value for {$processFormData}.
324
325
326 #. The top of the page will show your success/failure message (or
327 nothing the first time around), with the form below. If there are
328 errors, the user will have a chance to correct them. After a
329 successful submit, the form will appear again, so the user can
330 either review their entry, or change it and submit it again.
331 Depending on the application, this may make the servlet update the
332 same database record again, or it may generate a new record.
333
334
335 {FunFormKit} is a third-party Webware package that makes it easier
336 to produce forms and handle their logic. It has been successfully
337 been used with Cheetah. You can download FunFormKit from
338 http://colorstudy.net/software/funformkit/ and try it out for
339 yourself.
340
341 Form input, cookies, session variables and web server variables
342 ---------------------------------------------------------------
343
344
345 General variable tips that also apply to servlets are in section
346 tips.placeholder.
347
348 To look up a CGI GET or POST parameter (with POST overriding):
349
350 ::
351
352 $request.field('myField')
353 self.request().field('myField')
354
355 These will fail if Webware is not available, because {$request}
356 (aka {self.request()} will be {None} rather than a Webware
357 {WebKit.Request} object. If you plan to read a lot of CGI
358 parameters, you may want to put the {.fields} method into a local
359 variable for convenience:
360
361 ::
362
363 #set $fields = $request.fields
364 $fields.myField
365
366 But remember to do complicated calculations in Python, and assign
367 the results to simple variables in the searchList for display.
368 These {$request} forms are useful only for occasions where you just
369 need one or two simple request items that going to Python for would
370 be overkill.
371
372 To get a cookie or session parameter, subsitute "cookie" or
373 "session" for "field" above. To get a dictionary of all CGI
374 parameters, substitute "fields" (ditto for "cookies"). To verify a
375 field exists, substitute "hasField" (ditto for "hasCookie").
376
377 Other useful request goodies:
378
379 ::
380
381 ## Defined in WebKit.Request
382 $request.field('myField', 'default value')
383 $request.time ## Time this request began in Unix ticks.
384 $request.timeStamp ## Time in human-readable format ('asctime' format).
385 ## Defined in WebKit.HTTPRequest
386 $request.hasField.myField ## Is a CGI parameter defined?
387 $request.fields ## Dictionary of all CGI parameters.
388 $request.cookie.myCookie ## A cookie parameter (also .hasCookie, .cookies).
389 $request.value.myValue ## A field or cookie variable (field overrides)
390 ## (also .hasValue).
391 $request.session.mySessionVar # A session variable.
392 $request.extraURLPath ## URL path components to right of servlet, if any.
393 $request.serverDictionary ## Dict of environmental vars from web server.
394 $request.remoteUser ## Authenticated username. HTTPRequest.py source
395 ## suggests this is broken and always returns None.
396 $request.remoteAddress ## User's IP address (string).
397 $request.remoteName ## User's domain name, or IP address if none.
398 $request.urlPath ## URI of this servlet.
399 $request.urlPathDir ## URI of the directory containing this servlet.
400 $request.serverSidePath ## Absolute path of this servlet on local filesystem.
401 $request.serverURL ## URL of this servlet, without "http://" prefix,
402 ## extra path info or query string.
403 $request.serverURLDir ## URL of this servlet's directory, without "http://".
404 $log("message") ## Put a message in the Webware server log. (If you
405 ## define your own 'log' variable, it will override
406 ## this; use $self.log("message") in that case.
407
408 .webInput()
409 ~~~~~~~~~~~
410
411
412 From the method docstring:
413
414 ::
415
416 def webInput(self, names, namesMulti=(), default='', src='f',
417 defaultInt=0, defaultFloat=0.00, badInt=0, badFloat=0.00, debug=False):
418
419 This method places the specified GET/POST fields, cookies or session variables
420 into a dictionary, which is both returned and put at the beginning of the
421 searchList. It handles:
422 * single vs multiple values
423 * conversion to integer or float for specified names
424 * default values/exceptions for missing or bad values
425 * printing a snapshot of all values retrieved for debugging
426 All the 'default*' and 'bad*' arguments have "use or raise" behavior, meaning
427 that if they're a subclass of Exception, they're raised. If they're anything
428 else, that value is substituted for the missing/bad value.
429
430 The simplest usage is:
431
432 #silent $webInput(['choice'])
433 $choice
434
435 dic = self.webInput(['choice'])
436 write(dic['choice'])
437
438 Both these examples retrieves the GET/POST field 'choice' and print it. If you
439 leave off the "#silent", all the values would be printed too. But a better way
440 to preview the values is
441
442 #silent $webInput(['name'], $debug=1)
443
444 because this pretty-prints all the values inside HTML <PRE> tags.
445
446 Since we didn't specify any coversions, the value is a string. It's a "single"
447 value because we specified it in 'names' rather than 'namesMulti'. Single
448 values work like this:
449 * If one value is found, take it.
450 * If several values are found, choose one arbitrarily and ignore the rest.
451 * If no values are found, use or raise the appropriate 'default*' value.
452
453 Multi values work like this:
454 * If one value is found, put it in a list.
455 * If several values are found, leave them in a list.
456 * If no values are found, use the empty list ([]). The 'default*'
457 arguments are *not* consulted in this case.
458
459 Example: assume 'days' came from a set of checkboxes or a multiple combo box
460 on a form, and the user chose "Monday", "Tuesday" and "Thursday".
461
462 #silent $webInput([], ['days'])
463 The days you chose are: #slurp
464 #for $day in $days
465 $day #slurp
466 #end for
467
468 dic = self.webInput([], ['days'])
469 write("The days you chose are: ")
470 for day in dic['days']:
471 write(day + " ")
472
473 Both these examples print: "The days you chose are: Monday Tuesday Thursday".
474
475 By default, missing strings are replaced by "" and missing/bad numbers by zero.
476 (A "bad number" means the converter raised an exception for it, usually because
477 of non-numeric characters in the value.) This mimics Perl/PHP behavior, and
478 simplifies coding for many applications where missing/bad values *should* be
479 blank/zero. In those relatively few cases where you must distinguish between
480 ""/zero on the one hand and missing/bad on the other, change the appropriate
481 'default*' and 'bad*' arguments to something like:
482 * None
483 * another constant value
484 * $NonNumericInputError/self.NonNumericInputError
485 * $ValueError/ValueError
486 (NonNumericInputError is defined in this class and is useful for
487 distinguishing between bad input vs a TypeError/ValueError
488 thrown for some other reason.)
489
490 Here's an example using multiple values to schedule newspaper deliveries.
491 'checkboxes' comes from a form with checkboxes for all the days of the week.
492 The days the user previously chose are preselected. The user checks/unchecks
493 boxes as desired and presses Submit. The value of 'checkboxes' is a list of
494 checkboxes that were checked when Submit was pressed. Our task now is to
495 turn on the days the user checked, turn off the days he unchecked, and leave
496 on or off the days he didn't change.
497
498 dic = self.webInput([], ['dayCheckboxes'])
499 wantedDays = dic['dayCheckboxes'] # The days the user checked.
500 for day, on in self.getAllValues():
501 if not on and day in wantedDays:
502 self.TurnOn(day)
503 # ... Set a flag or insert a database record ...
504 elif on and day not in wantedDays:
505 self.TurnOff(day)
506 # ... Unset a flag or delete a database record ...
507
508 'source' allows you to look up the variables from a number of different
509 sources:
510 'f' fields (CGI GET/POST parameters)
511 'c' cookies
512 's' session variables
513 'v' "values", meaning fields or cookies
514
515 In many forms, you're dealing only with strings, which is why the
516 'default' argument is third and the numeric arguments are banished to
517 the end. But sometimes you want automatic number conversion, so that
518 you can do numeric comparisons in your templates without having to
519 write a bunch of conversion/exception handling code. Example:
520
521 #silent $webInput(['name', 'height:int'])
522 $name is $height cm tall.
523 #if $height >= 300
524 Wow, you're tall!
525 #else
526 Pshaw, you're short.
527 #end if
528
529 dic = self.webInput(['name', 'height:int'])
530 name = dic[name]
531 height = dic[height]
532 write("%s is %s cm tall." % (name, height))
533 if height > 300:
534 write("Wow, you're tall!")
535 else:
536 write("Pshaw, you're short.")
537
538 To convert a value to a number, suffix ":int" or ":float" to the name. The
539 method will search first for a "height:int" variable and then for a "height"
540 variable. (It will be called "height" in the final dictionary.) If a numeric
541 conversion fails, use or raise 'badInt' or 'badFloat'. Missing values work
542 the same way as for strings, except the default is 'defaultInt' or
543 'defaultFloat' instead of 'default'.
544
545 If a name represents an uploaded file, the entire file will be read into
546 memory. For more sophisticated file-upload handling, leave that name out of
547 the list and do your own handling, or wait for Cheetah.Utils.UploadFileMixin.
548
549 This mixin class works only in a subclass that also inherits from
550 Webware's Servlet or HTTPServlet. Otherwise you'll get an AttributeError
551 on 'self.request'.
552
553 EXCEPTIONS: ValueError if 'source' is not one of the stated characters.
554 TypeError if a conversion suffix is not ":int" or ":float".
555
556 More examples
557 -------------
558
559
560 Example A - a standalone servlet
561 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
562
563 Example B - a servlet under a site framework
564 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565
566 Example C - several servlets with a common template
567 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
568
569 Other Tips
570 ----------
571
572
573 If your servlet accesses external files (e.g., via an {#include}
574 directive), remember that the current directory is not necessarily
575 directory the servlet is in. It's probably some other directory
576 WebKit chose. To find a file relative to the servlet's directory,
577 prefix the path with whatever {self.serverSidePath()} returns (from
578 {Servlet.serverSidePath()}.
579
580 If you don't understand how {#extends} and {#implements} work, and
581 about a template's main method, read the chapter on inheritance
582 (sections inheritanceEtc.extends and inheritanceEtc.implements).
583 This may help you avoid buggy servlets.
584
585