Update of /cvsroot/jtoolkit/jToolkit/web
In directory sc8-pr-cvs1:/tmp/cvs-serv30884
Modified Files:
__init__.py server.py
Added Files:
httpcodes.py
Log Message:
added new module httpcodes as more generic way to return http status
modified server.py to use httpcodes wherever possible, __init__.py to convert them for modpython/apache
also moved reading the arguments from the request out of the server (to make it more generic)
so now each handle object takes a argdict parameter
this makes things more flexible as each server can processargs without worrying about others...
added error trapping for import code in __init__.py
rearranged logging code to make it cleaner
--- NEW FILE: httpcodes.py ---
#!/usr/bin/python
"""constants for HTTP status codes"""
# Copyright 2002, 2003 St James Software
#
# This file is part of jToolkit.
#
# jToolkit is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# jToolkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with jToolkit; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
CONTINUE = 100
SWITCHING_PROTOCOLS = 101
PROCESSING = 102
OK = 200
CREATED = 201
ACCEPTED = 202
NON_AUTHORITATIVE = 203
NO_CONTENT = 204
RESET_CONTENT = 205
PARTIAL_CONTENT = 206
MULTI_STATUS = 207
MULTIPLE_CHOICES = 300
MOVED_PERMANENTLY = 301
MOVED_TEMPORARILY = 302
SEE_OTHER = 303
NOT_MODIFIED = 304
USE_PROXY = 305
TEMPORARY_REDIRECT = 307
BAD_REQUEST = 400
UNAUTHORIZED = 401
PAYMENT_REQUIRED = 402
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
NOT_ACCEPTABLE = 406
PROXY_AUTHENTICATION_REQUIRED= 407
REQUEST_TIME_OUT = 408
CONFLICT = 409
GONE = 410
LENGTH_REQUIRED = 411
PRECONDITION_FAILED = 412
REQUEST_ENTITY_TOO_LARGE = 413
REQUEST_URI_TOO_LARGE = 414
UNSUPPORTED_MEDIA_TYPE = 415
RANGE_NOT_SATISFIABLE = 416
EXPECTATION_FAILED = 417
UNPROCESSABLE_ENTITY = 422
LOCKED = 423
FAILED_DEPENDENCY = 424
INTERNAL_SERVER_ERROR = 500
NOT_IMPLEMENTED = 501
BAD_GATEWAY = 502
SERVICE_UNAVAILABLE = 503
GATEWAY_TIME_OUT = 504
VERSION_NOT_SUPPORTED = 505
VARIANT_ALSO_VARIES = 506
INSUFFICIENT_STORAGE = 507
NOT_EXTENDED = 510
Index: __init__.py
===================================================================
RCS file: /cvsroot/jtoolkit/jToolkit/web/__init__.py,v
retrieving revision 1.5
retrieving revision 1.6
diff -C2 -d -r1.5 -r1.6
*** __init__.py 14 Oct 2003 08:25:55 -0000 1.5
--- __init__.py 14 Oct 2003 15:47:25 -0000 1.6
***************
*** 20,23 ****
--- 20,25 ----
import sys
+ from jToolkit.web import safeapache
+ from jToolkit.web import httpcodes
# list of modules in this package
***************
*** 30,33 ****
--- 32,49 ----
logtimes = 0
+ def logtimetofile(message):
+ osid = os.getpid()
+ threadid = thread.get_ident()
+ t = time.time()
+ ms = int((t - int(t))*1000.0)
+ timestr = time.strftime('%Y-%m-%d %H:%M:%S') + '.%03d' % ms
+ f = open(logfilename, 'a')
+ f.write('%s: pid %r tid %r: %s\n' % (timestr, osid, threadid, message))
+ f.close()
+
+ def logtimetonowhere(message):
+ """don't log anything as we aren't in logtimes mode"""
+ pass
+
if logtimes:
import os, time
***************
*** 42,59 ****
thread.get_ident = thread_get_ident
logfilename = '/tmp/threads.log'
!
! def logtime(message):
! osid = os.getpid()
! threadid = thread.get_ident()
! t = time.time()
! ms = int((t - int(t))*1000.0)
! timestr = time.strftime('%Y-%m-%d %H:%M:%S') + '.%03d' % ms
! f = open(logfilename, 'a')
! f.write('%s: pid %r tid %r: %s\n' % (timestr, osid, threadid, message))
! f.close()
else:
! def logtime(message):
! """don't log anything as we aren't in logtimes mode"""
! pass
def getserver(modulename, instancename):
--- 58,64 ----
thread.get_ident = thread_get_ident
logfilename = '/tmp/threads.log'
! logtime = logtimetofile
else:
! logtime = logtimetonowhere
def getserver(modulename, instancename):
***************
*** 93,101 ****
server = getserver(modulename, instancename)
pathwords = filter(None, req.uri.split('/')) # split into bits, strip out empty strings
logtime('calling server.handle: ' + req.uri)
! thepage = server.handle(req, pathwords)
logtime('calling server.sendpage: ' + req.uri)
result = server.sendpage(req, thepage)
logtime('done: ' + req.uri)
return result
--- 98,109 ----
server = getserver(modulename, instancename)
pathwords = filter(None, req.uri.split('/')) # split into bits, strip out empty strings
+ argdict = safeapache.util.FieldStorage(req)
logtime('calling server.handle: ' + req.uri)
! thepage = server.handle(req, pathwords, argdict)
logtime('calling server.sendpage: ' + req.uri)
result = server.sendpage(req, thepage)
logtime('done: ' + req.uri)
+ if result is None: return safeapache.apache.DECLINED
+ if result == httpcodes.OK: return safeapache.apache.OK
return result
Index: server.py
===================================================================
RCS file: /cvsroot/jtoolkit/jToolkit/web/server.py,v
retrieving revision 1.6
retrieving revision 1.7
diff -C2 -d -r1.6 -r1.7
*** server.py 14 Oct 2003 09:36:49 -0000 1.6
--- server.py 14 Oct 2003 15:47:25 -0000 1.7
***************
*** 25,29 ****
from jToolkit.data import database
! from jToolkit.web import safeapache
from jToolkit.web import session
from jToolkit import errors
--- 25,29 ----
from jToolkit.data import database
! from jToolkit.web import httpcodes
from jToolkit.web import session
from jToolkit import errors
***************
*** 39,43 ****
widgets.Page.__init__(self, title, contents=[])
self.confirmlogin = confirmlogin
! self.processargs(extraargs)
self.specialmessage = specialmessage
self.languagenames = languagenames
--- 39,43 ----
widgets.Page.__init__(self, title, contents=[])
self.confirmlogin = confirmlogin
! self.handleextraargs(extraargs)
self.specialmessage = specialmessage
self.languagenames = languagenames
***************
*** 48,52 ****
return session.localize("Login for %s") % (session.instance.__name__)
! def processargs(self, extraargs):
"""process the arguments given, and add neccessary args to a hidden widgets list"""
self.action = ''
--- 48,52 ----
return session.localize("Login for %s") % (session.instance.__name__)
! def handleextraargs(self, extraargs):
"""process the arguments given, and add neccessary args to a hidden widgets list"""
self.action = ''
***************
*** 139,150 ****
req.send_http_header()
req.write(response)
! return safeapache.apache.OK
else:
req.headers_out.add('Location', self.location)
if self.ispermanent:
! req.status = safeapache.apache.HTTP_MOVED_PERMANENTLY
else:
! req.status = safeapache.apache.HTTP_MOVED_TEMPORARILY
! return safeapache.apache.OK
class AppServer(object):
--- 139,149 ----
req.send_http_header()
req.write(response)
! return httpcodes.OK
else:
req.headers_out.add('Location', self.location)
if self.ispermanent:
! return httpcodes.MOVED_PERMANENTLY
else:
! return httpcodes.MOVED_TEMPORARILY
class AppServer(object):
***************
*** 179,185 ****
self.defaultlanguage = localize.getdefaultlanguage(self.languagelist)
! def handle(self, req, pathwords):
"""handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, req)
session = self.getsession(req, argdict)
session.pagecount += 1
--- 178,184 ----
self.defaultlanguage = localize.getdefaultlanguage(self.languagelist)
! def handle(self, req, pathwords, argdict):
"""handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, argdict)
session = self.getsession(req, argdict)
session.pagecount += 1
***************
*** 212,227 ****
else:
req.write(response)
! return safeapache.apache.OK
elif isinstance(thepage, Redirect):
return thepage.sendredirect(req)
elif thepage is None:
! return safeapache.apache.DECLINED
else:
# a non-widget means a return code... actually an integer, not a page
return thepage
! def processargs(self, instance, req):
"""return a dictionary of the set of arguments in a request..."""
- argdict = safeapache.util.FieldStorage(req)
newdict = {}
for key in argdict.keys():
--- 211,226 ----
else:
req.write(response)
! return httpcodes.OK
elif isinstance(thepage, Redirect):
return thepage.sendredirect(req)
elif thepage is None:
! # return None to indicate we didn't produce a page (usually means Apache/webserver will handle it)
! return None
else:
# a non-widget means a return code... actually an integer, not a page
return thepage
! def processargs(self, instance, argdict):
"""return a dictionary of the set of arguments in a request..."""
newdict = {}
for key in argdict.keys():
***************
*** 279,285 ****
self.loginpageclass = loginpageclass
! def handle(self, req, pathwords):
"""handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, req)
session = self.getsession(req, argdict)
if session.isopen:
--- 278,284 ----
self.loginpageclass = loginpageclass
! def handle(self, req, pathwords, argdict):
"""handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, argdict)
session = self.getsession(req, argdict)
if session.isopen:
***************
*** 339,363 ****
if len(pathwords) > 0:
top = pathwords[0]
- tail = pathwords[1:]
if top not in ('', 'index.htm', 'index.html'):
return 1
return 0
! def handledefer(self, req, pathwords):
"""handles deferring the request to another server"""
server = self.getserver(pathwords)
if server is None:
return None
! return server.handle(req, pathwords[1:])
! def handle(self, req, pathwords):
"""handles the request and returns a page object in response"""
if self.shoulddefer(pathwords):
if pathwords[0] in self.instances:
! return self.handledefer(req, pathwords)
else:
return None
else:
! argdict = self.processargs(self.instance, req)
return self.getpage(pathwords, None, argdict)
--- 338,361 ----
if len(pathwords) > 0:
top = pathwords[0]
if top not in ('', 'index.htm', 'index.html'):
return 1
return 0
! def handledefer(self, req, pathwords, argdict):
"""handles deferring the request to another server"""
server = self.getserver(pathwords)
if server is None:
return None
! return server.handle(req, pathwords[1:], argdict)
! def handle(self, req, pathwords, argdict):
"""handles the request and returns a page object in response"""
if self.shoulddefer(pathwords):
if pathwords[0] in self.instances:
! return self.handledefer(req, pathwords, argdict)
else:
return None
else:
! argdict = self.processargs(self.instance, argdict)
return self.getpage(pathwords, None, argdict)
***************
*** 380,386 ****
class SharedLoginAppServer(LoginAppServer):
"""allows instance to be passed a shared session..."""
! def handle(self, req, pathwords, sharedsession=None):
"""handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, req)
exitapp = argdict.get('exitapp', 0)
session = self.getsession(req, argdict, sharedsession)
--- 378,384 ----
class SharedLoginAppServer(LoginAppServer):
"""allows instance to be passed a shared session..."""
! def handle(self, req, pathwords, argdict, sharedsession=None):
"""handles the request and returns a page object in response"""
! argdict = self.processargs(self.instance, argdict)
exitapp = argdict.get('exitapp', 0)
session = self.getsession(req, argdict, sharedsession)
***************
*** 411,420 ****
"""constructs the multi-app server"""
if sessioncache is None:
! sessioncache = session.SessionCache(sessionclass=LoginSession,sessioncookiename=instance.__name__+'session')
super(SharedLoginMultiAppServer, self).__init__(instance, sessioncache, errorhandler, loginpageclass)
self.instances = self.instance.instances
self.servers = {}
! def handledefer(self, req, pathwords, session=None):
"""handles deferring the request to another server"""
server = self.getserver(pathwords)
--- 409,418 ----
"""constructs the multi-app server"""
if sessioncache is None:
! sessioncache = session.SessionCache(sessionclass=session.LoginSession,sessioncookiename=instance.__name__+'session')
super(SharedLoginMultiAppServer, self).__init__(instance, sessioncache, errorhandler, loginpageclass)
self.instances = self.instance.instances
self.servers = {}
! def handledefer(self, req, pathwords, argdict, session=None):
"""handles deferring the request to another server"""
server = self.getserver(pathwords)
***************
*** 422,441 ****
return None
if isinstance(server, SharedLoginAppServer):
! return server.handle(req, pathwords[1:], sharedsession=session)
else:
! return server.handle(req, pathwords[1:])
! def handle(self, req, pathwords):
"""handles the request and returns a page object in response"""
if self.shoulddefer(pathwords):
- # can't do self.processargs otherwise the other server won't be able to...
if pathwords[0] in self.instances:
session = self.sessioncache.getsession(req, self)
if session.isopen:
! return self.handledefer(req, pathwords, session)
else:
return None
else:
! argdict = self.processargs(self.instance, req)
session = self.getsession(req, argdict)
if session.isopen:
--- 420,438 ----
return None
if isinstance(server, SharedLoginAppServer):
! return server.handle(req, pathwords[1:], argdict, sharedsession=session)
else:
! return server.handle(req, pathwords[1:], argdict)
! def handle(self, req, pathwords, argdict):
"""handles the request and returns a page object in response"""
if self.shoulddefer(pathwords):
if pathwords[0] in self.instances:
session = self.sessioncache.getsession(req, self)
if session.isopen:
! return self.handledefer(req, pathwords, session, argdict)
else:
return None
else:
! argdict = self.processargs(self.instance, argdict)
session = self.getsession(req, argdict)
if session.isopen:
***************
*** 469,473 ****
class SharedLoginMiddleAppServer(SharedLoginAppServer, SharedLoginMultiAppServer):
"""a server that can be a parent *and* a child"""
! def handle(self, req, pathwords, sharedsession=None):
"""handles the request and returns a page object in response"""
if self.shoulddefer(pathwords):
--- 466,470 ----
class SharedLoginMiddleAppServer(SharedLoginAppServer, SharedLoginMultiAppServer):
"""a server that can be a parent *and* a child"""
! def handle(self, req, pathwords, argdict, sharedsession=None):
"""handles the request and returns a page object in response"""
if self.shoulddefer(pathwords):
***************
*** 475,483 ****
if pathwords[0] in self.instances:
session = self.sessioncache.getsession(req, self)
! return self.handledefer(req, pathwords, session)
else:
return None
else:
! argdict = self.processargs(self.instance, req)
exitapp = argdict.get('exitapp', 0)
session = self.getsession(req, argdict, sharedsession)
--- 472,480 ----
if pathwords[0] in self.instances:
session = self.sessioncache.getsession(req, self)
! return self.handledefer(req, pathwords, argdict, session)
else:
return None
else:
! argdict = self.processargs(self.instance, argdict)
exitapp = argdict.get('exitapp', 0)
session = self.getsession(req, argdict, sharedsession)
|