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
|
"""
This implements all of the Webware servlets (Servlet, HTTPServlet, and
Page), as WSGI applications. The servlets themselves are
applications, and __call__ is provided to do this.
"""
import wkcommon
from wktransaction import Transaction
class Servlet(object):
# This is nested in Servlet so that transactions can access it as
# an attribute, instead of having to import this module. (If they
# had to import this module, there would be a circular import)
# @@: Why not just put this in wktransaction?
class ReturnIterException(Exception):
def __init__(self, app_iter):
self.app_iter = app_iter
def __call__(self, environ, start_response):
"""
The core WSGI method, and the core of the servlet execution.
"""
trans = Transaction(environ, start_response)
trans.setServlet(self)
try:
trans.runTransaction()
trans.response().deliver()
return trans.response().wsgiIterator()
except self.ReturnIterException, e:
return e.app_iter
except self.EndResponse:
trans.response().deliver()
return trans.response().wsgiIterator()
## Access ##
def name(self):
"""
Returns the name which is simple the name of the
class. Subclasses should *not* override this method. It is
used for logging and debugging. """
return self.__class__.__name__
def awake(self, trans):
"""
This message is sent to all objects that participate in the
request-response cycle in a top-down fashion, prior to
respond(). Subclasses must invoke super.
"""
self._transaction = trans
def respond(self, trans):
raise AbstractError, self.__class__
def sleep(self, trans):
pass
## Abilities ##
def canBeThreaded(self):
""" Returns 0 or 1 to indicate if the servlet can be
multithreaded. This value should not change during the
lifetime of the object. The default implementation returns
0. Note: This is not currently used. """
return 0
def canBeReused(self):
""" Returns 0 or 1 to indicate if a single servlet instance
can be reused. The default is 1, but subclasses con override
to return 0. Keep in mind that performance may seriously be
degraded if instances can't be reused. Also, there's no known
good reasons not to reuse and instance. Remember the awake()
and sleep() methods are invoked for every transaction. But
just in case, your servlet can refuse to be reused. """
return 1
class HTTPServlet(Servlet):
def __init__(self):
Servlet.__init__(self)
self._methodForRequestType = {} # a cache; see respond()
## From WebKit.HTTPServlet ##
def respond(self, trans):
"""
Invokes the appropriate respondToSomething() method
depending on the type of request (e.g., GET, POST, PUT,
...). """
httpMethodName = trans.request().method()
method = self._methodForRequestType.get(httpMethodName, None)
if not method:
methName = 'respondTo' + httpMethodName.capitalize()
method = getattr(self, methName, self.notImplemented)
self._methodForRequestType[httpMethodName] = method
method(trans)
def notImplemented(self, trans):
trans.response().setHeader('Status', '501 Not Implemented')
def respondToHead(self, trans):
"""
A correct but inefficient implementation.
Should at least provide Last-Modified and Content-Length.
"""
res = trans.response()
w = res.write
res.write = lambda *args: None
self.respondToGet(trans)
res.write = w
class Page(HTTPServlet):
class EndResponse(Exception):
pass
## Server side filesystem ##
def serverSidePath(self, path=None):
raise NotImplementedError
## From WebKit.Page ##
def awake(self, transaction):
self._transaction = transaction
self._response = transaction.response()
self._request = transaction.request()
self._session = None # don't create unless needed
assert self._transaction is not None
assert self._response is not None
assert self._request is not None
def respondToGet(self, transaction):
""" Invokes _respond() to handle the transaction. """
self._respond(transaction)
def respondToPost(self, transaction):
""" Invokes _respond() to handle the transaction. """
self._respond(transaction)
def _respond(self, transaction):
"""
Handles actions if an _action_ field is defined, otherwise
invokes writeHTML().
Invoked by both respondToGet() and respondToPost().
"""
req = transaction.request()
# Check for actions
for action in self.actions():
if req.hasField('_action_%s' % action) or \
req.field('_action_', None) == action or \
(req.hasField('_action_%s.x' % action) and \
req.hasField('_action_%s.y' % action)):
if self._actionSet().has_key(action):
self.handleAction(action)
return
self.writeHTML()
def sleep(self, transaction):
self._session = None
self._request = None
self._response = None
self._transaction = None
## Access ##
def application(self):
return self.transaction().application()
def transaction(self):
return self._transaction
def request(self):
return self._request
def response(self):
return self._response
def session(self):
if not self._session:
self._session = self._transaction.session()
return self._session
## Generating results ##
def title(self):
""" Subclasses often override this method to provide a custom title. This title should be absent of HTML tags. This implementation returns the name of the class, which is sometimes appropriate and at least informative. """
return self.__class__.__name__
def htTitle(self):
""" Return self.title(). Subclasses sometimes override this to provide an HTML enhanced version of the title. This is the method that should be used when including the page title in the actual page contents. """
return self.title()
def htBodyArgs(self):
"""
Returns the arguments used for the HTML <body> tag. Invoked by
writeBody().
With the prevalence of stylesheets (CSS), you can probably skip
this particular HTML feature.
"""
return 'color=black bgcolor=white'
def writeHTML(self):
"""
Writes all the HTML for the page.
Subclasses may override this method (which is invoked by
respondToGet() and respondToPost()) or more commonly its
constituent methods, writeDocType(), writeHead() and
writeBody().
"""
self.writeDocType()
self.writeln('<html>')
self.writeHead()
self.writeBody()
self.writeln('</html>')
def writeDocType(self):
"""
Invoked by writeHTML() to write the <!DOCTYPE ...> tag.
@@ sgd-2003-01-29 - restored the 4.01 transitional as per discussions
on the mailing list for the 0.8 release.
# This implementation USED TO specify HTML 4.01 Transitional, but
# some versions of Mozilla acted strangely with that. The current
# implementation does nothing.
Subclasses may override to specify something else.
You can find out more about doc types by searching for DOCTYPE
on the web, or visiting:
http://www.htmlhelp.com/tools/validator/doctype.html
"""
self.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">')
pass
def writeHead(self):
"""
Writes the <head> portion of the page by writing the
<head>...</head> tags and invoking writeHeadParts() in between.
"""
wr = self.writeln
wr('<head>')
self.writeHeadParts()
wr('</head>')
def writeHeadParts(self):
"""
Writes the parts inside the <head>...</head> tags. Invokes
writeTitle() and writeStyleSheet(). Subclasses can override this
to add additional items and should invoke super.
"""
self.writeTitle()
self.writeStyleSheet()
def writeTitle(self):
"""
Writes the <title> portion of the page. Uses title().
"""
self.writeln('\t<title>%s</title>' % self.title())
def writeStyleSheet(self):
"""
Writes the style sheet for the page, however, this default
implementation does nothing. Subclasses should override if
necessary. A typical implementation is:
self.writeln('\t<link rel=stylesheet href=StyleSheet.css type=text/css>')
"""
pass
def writeBody(self):
"""
Writes the <body> portion of the page by writing the
<body>...</body> (making use of self.htBodyArgs()) and invoking
self.writeBodyParts() in between.
"""
wr = self.writeln
bodyArgs = self.htBodyArgs()
if bodyArgs:
wr('<body %s>' % bodyArgs)
else:
wr('<body>')
self.writeBodyParts()
wr('</body>')
def writeBodyParts(self):
"""
Invokes writeContent(). Subclasses should only override this
method to provide additional page parts such as a header,
sidebar and footer, that a subclass doesn't normally have to
worry about writing.
For writing page-specific content, subclasses should override
writeContent() instead.
See SidebarPage for an example override of this method.
Invoked by writeBody().
"""
self.writeContent()
def writeContent(self):
"""
Writes the unique, central content for the page.
Subclasses should override this method (not invoking super) to
write their unique page content.
Invoked by writeBodyParts().
"""
self.writeln('<p> This page has not yet customized its content. </p>')
## Writing ##
def write(self, *args):
for arg in args:
self._response.write(str(arg))
def writeln(self, *args):
for arg in args:
self._response.write(str(arg))
self._response.write('\n')
## Threading ##
def canBeThreaded(self):
""" Returns 0 because of the ivars we set up in awake(). """
return 0
## Actions ##
def handleAction(self, action):
"""
Invoked by `_respond` when a legitimate action has
been found in a form. Invokes `preAction`, the actual
action method and `postAction`.
Subclasses rarely override this method.
"""
self.preAction(action)
getattr(self, action)()
self.postAction(action)
def actions(self):
return []
def preAction(self, actionName):
raise NotImplementedError
def postAction(self, actionName):
raise NotImplementedError
def methodNameForAction(self, name):
raise NotImplementedError
## Convenience ##
def htmlEncode(self, s):
return wkcommon.htmlEncode(s)
def htmlDecode(self, s):
return wkcommon.htmlDecode(s)
def urlEncode(self, s):
return wkcommon.urlEncode(s)
def urlDecode(self, s):
return wkcommon.urlDecode(s)
def forward(self, URL):
self.application().forward(self.transaction(), URL)
def includeURL(self, URL):
raise NotImplementedError
def callMethodOfServlet(self, URL, method, *args, **kwargs):
raise NotImplementedError
def endResponse(self):
raise self.EndResponse()
def sendRedirectAndEnd(self, url):
"""
Sends a redirect back to the client and ends the response. This
is a very popular pattern.
"""
self.response().sendRedirect(url)
self.endResponse()
## Self utility ##
def sessionEncode(self, url=None):
"""
Utility function to access session.sessionEncode.
Takes a url and adds the session ID as a parameter. This is for cases where
you don't know if the client will accepts cookies.
"""
if url == None:
url = self.request().uri()
return self.session().sessionEncode(url)
## Private utility ##
def _actionSet(self):
""" Returns a dictionary whose keys are the names returned by actions(). The dictionary is used for a quick set-membership-test in self._respond. Subclasses don't generally override this method or invoke it. """
if not hasattr(self, '_actionDict'):
self._actionDict = {}
for action in self.actions():
self._actionDict[action] = 1
return self._actionDict
## Validate HTML output (developer debugging) ##
def validateHTML(self, closingTags='</body></html>'):
raise NotImplementedError
|