diff options
author | Robert Brewer <fumanchu@aminus.org> | 2005-06-25 20:37:39 +0000 |
---|---|---|
committer | Robert Brewer <fumanchu@aminus.org> | 2005-06-25 20:37:39 +0000 |
commit | 931880f918dc3d056640a521b2cab4ff7f0894e7 (patch) | |
tree | f73ee8133eba3d4540dd531e13ade80aa5d2e101 | |
parent | 95b1f7e9c51fde72758e60bd69c0875719ab2117 (diff) | |
download | cherrypy-git-931880f918dc3d056640a521b2cab4ff7f0894e7.tar.gz |
Implements ticket #195.
1. cpg module removed, all content moved into cherrypy.__init__.
2. Removed some circular imports in sessionfilter by moving sessionfilter.sessionfilter and _sessionTypes into sessionfilter.__init__.
3. renamed _cpconfig to "config".
4. renamed _cpserver to "server".
5. renamed cperror to _cperror; cherrypy.__init__ now imports * from _cperror.
61 files changed, 1175 insertions, 1116 deletions
diff --git a/cherrypy/__init__.py b/cherrypy/__init__.py index 3c0bd3ef..3ddaf2f5 100644 --- a/cherrypy/__init__.py +++ b/cherrypy/__init__.py @@ -1 +1,52 @@ +""" +Copyright (c) 2004, CherryPy Team (team@cherrypy.org) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the CherryPy Team nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +""" +Global module that all modules developing with CherryPy should import. +""" + __version__ = '2.1.0 alpha' + +from _cperror import * + +import config +import server + +_httpserver = None + +# decorator function for exposing methods +def expose(func): + func.exposed = True + return func + +def log(msg, context='', severity=0): + """Syntactic sugar for writing to the log.""" + import _cputil + logfunc = _cputil.getSpecialAttribute('_cpLogMessage') + logfunc(msg, context, severity) + diff --git a/cherrypy/cperror.py b/cherrypy/_cperror.py index 22c5c521..52867e2e 100644 --- a/cherrypy/cperror.py +++ b/cherrypy/_cperror.py @@ -39,7 +39,7 @@ class NotFound(Error): pass class WrongResponseType(Error): - """ Happens when the cpg.response.body is not a string """ + """ Happens when the cherrypy.response.body is not a string """ pass class WrongUnreprValue(Error): @@ -64,20 +64,20 @@ class InternalRedirect(Exception): """ def __init__(self, path, queryString=None): - from cherrypy import cpg + import cherrypy import cgi self.path = path if queryString is not None: - cpg.request.queryString = queryString + cherrypy.request.queryString = queryString - pm = cgi.parse_qs(cpg.request.queryString, keep_blank_values=True) + pm = cgi.parse_qs(cherrypy.request.queryString, keep_blank_values=True) for key, val in pm.items(): if len(val) == 1: pm[key] = val[0] - cpg.request.paramMap = pm + cherrypy.request.paramMap = pm - cpg.request.browserUrl = cpg.request.base + path + cherrypy.request.browserUrl = cherrypy.request.base + path @@ -90,7 +90,7 @@ class HTTPRedirect(Exception): def __init__(self, urls, status=None): import urlparse - from cherrypy import cpg + import cherrypy if isinstance(urls, basestring): urls = [urls] @@ -98,7 +98,7 @@ class HTTPRedirect(Exception): abs_urls = [] for url in urls: if url.startswith("/"): - url = urlparse.urljoin(cpg.request.base, url) + url = urlparse.urljoin(cherrypy.request.base, url) abs_urls.append(url) self.urls = abs_urls @@ -106,7 +106,7 @@ class HTTPRedirect(Exception): # browser support for 301 is quite messy. Do 302 instead. # http://ppewww.ph.gla.ac.uk/~flavell/www/post-redirect.html if status is None: - if cpg.request.protocol == "HTTP/1.1": + if cherrypy.request.protocol == "HTTP/1.1": status = 303 else: status = 302 @@ -118,14 +118,14 @@ class HTTPRedirect(Exception): self.status = status def set_response(self): - import cpg - cpg.response.status = status = self.status - cpg.response.headerMap['Content-Type'] = "text/html" + import cherrypy + cherrypy.response.status = status = self.status + cherrypy.response.headerMap['Content-Type'] = "text/html" if status in (300, 301, 302, 303, 307): # "The ... URI SHOULD be given by the Location field # in the response." - cpg.response.headerMap['Location'] = self.urls[0] + cherrypy.response.headerMap['Location'] = self.urls[0] # "Unless the request method was HEAD, the entity of the response # SHOULD contain a short hypertext note with a hyperlink to the @@ -136,7 +136,7 @@ class HTTPRedirect(Exception): 303: "This resource can be found at <a href='%s'>%s</a>.", 307: "This resource has moved temporarily to <a href='%s'>%s</a>.", }[status] - cpg.response.body = "<br />\n".join([msg % (url, url) + cherrypy.response.body = "<br />\n".join([msg % (url, url) for url in self.urls]) elif status == 304: # Not Modified. @@ -145,11 +145,11 @@ class HTTPRedirect(Exception): # The "Date" header should have been set in Request.__init__ # "The 304 response MUST NOT contain a message-body." - cpg.response.body = [] + cherrypy.response.body = [] elif status == 305: # Use Proxy. # self.urls[0] should be the URI of the proxy. - cpg.response.headerMap['Location'] = self.urls[0] - cpg.response.body = [] + cherrypy.response.headerMap['Location'] = self.urls[0] + cherrypy.response.body = [] else: raise ValueError("The %s status code is unknown." % status) diff --git a/cherrypy/_cphttpserver.py b/cherrypy/_cphttpserver.py index 3f56406f..91d6d7b8 100644 --- a/cherrypy/_cphttpserver.py +++ b/cherrypy/_cphttpserver.py @@ -27,7 +27,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import threading, SocketServer, BaseHTTPServer, socket, Queue -import cpg, _cpserver, _cphttptools +import cherrypy +from cherrypy import _cphttptools try: import cStringIO as StringIO @@ -48,7 +49,7 @@ class CherryHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def address_string(self): """ Try to do a reverse DNS based on [server]reverseDNS in the config file """ - if cpg.config.get('server.reverseDNS'): + if cherrypy.config.get('server.reverseDNS'): return BaseHTTPServer.BaseHTTPRequestHandler.address_string(self) else: return self.client_address[0] @@ -79,22 +80,22 @@ class CherryHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): if not self.parse_request(): # An error code has been sent, just exit return - cpg.request.multithread = cpg.config.get("server.threadPool") > 1 - cpg.request.multiprocess = False - _cpserver.request(self.client_address[0], - self.address_string(), - self.raw_requestline, - self._headerlist(), - self.rfile) + cherrypy.request.multithread = cherrypy.config.get("server.threadPool") > 1 + cherrypy.request.multiprocess = False + cherrypy.server.request(self.client_address[0], + self.address_string(), + self.raw_requestline, + self._headerlist(), + self.rfile) wfile = self.wfile - wfile.write("%s %s\r\n" % (self.protocol_version, cpg.response.status)) + wfile.write("%s %s\r\n" % (self.protocol_version, cherrypy.response.status)) - for name, value in cpg.response.headers: + for name, value in cherrypy.response.headers: wfile.write("%s: %s\r\n" % (name, value)) wfile.write("\r\n") try: - for chunk in cpg.response.body: + for chunk in cherrypy.response.body: wfile.write(chunk) except: s, h, b = _cphttptools.bareError() @@ -106,7 +107,7 @@ class CherryHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def log_message(self, format, *args): """ We have to override this to use our own logging mechanism """ - cpg.log(format % args, "HTTP") + cherrypy.log(format % args, "HTTP") class CherryHTTPServer(BaseHTTPServer.HTTPServer): @@ -140,7 +141,7 @@ class CherryHTTPServer(BaseHTTPServer.HTTPServer): # interrupts on Win32, which don't interrupt accept() by default return 1 except (KeyboardInterrupt, SystemExit): - cpg.log("<Ctrl-C> hit: shutting down http server", "HTTP") + cherrypy.log("<Ctrl-C> hit: shutting down http server", "HTTP") self.shutdown() def serve_forever(self): @@ -194,7 +195,7 @@ class ServerThread(threading.Thread): def handle_error(self, request, client_address): """Handle an error gracefully. May be overridden.""" errorBody = _cphttptools.formatExc() - cpg.log(errorBody) + cherrypy.log(errorBody) class PooledThreadServer(SocketServer.TCPServer): @@ -272,7 +273,7 @@ class PooledThreadServer(SocketServer.TCPServer): try: request, client_address = self.get_request() except (KeyboardInterrupt, SystemExit): - cpg.log("<Ctrl-C> hit: shutting down", "HTTP") + cherrypy.log("<Ctrl-C> hit: shutting down", "HTTP") return 0 except socket.error, e: return 1 @@ -295,14 +296,14 @@ def embedded_server(handler=None): """Selects and instantiates the appropriate server.""" # Set protocol_version - proto = cpg.config.get('server.protocolVersion') + proto = cherrypy.config.get('server.protocolVersion') if not proto: proto = "HTTP/1.0" CherryHTTPRequestHandler.protocol_version = proto # Select the appropriate server based on config options - sockFile = cpg.config.get('server.socketFile') - threadPool = cpg.config.get('server.threadPool') + sockFile = cherrypy.config.get('server.socketFile') + threadPool = cherrypy.config.get('server.threadPool') if sockFile: # AF_UNIX socket # TODO: Handle threading here @@ -319,10 +320,10 @@ def embedded_server(handler=None): ServerClass = PooledThreadServer else: ServerClass = CherryHTTPServer - server_address = (cpg.config.get('server.socketHost'), - cpg.config.get('server.socketPort')) + server_address = (cherrypy.config.get('server.socketHost'), + cherrypy.config.get('server.socketPort')) - ServerClass.request_queue_size = cpg.config.get('server.socketQueueSize') + ServerClass.request_queue_size = cherrypy.config.get('server.socketQueueSize') if handler is None: handler = CherryHTTPRequestHandler diff --git a/cherrypy/_cphttptools.py b/cherrypy/_cphttptools.py index 384f92ca..8518c92a 100644 --- a/cherrypy/_cphttptools.py +++ b/cherrypy/_cphttptools.py @@ -34,7 +34,8 @@ import urllib, os, sys, time, traceback, types, cgi import mimetypes, Cookie, urlparse from lib.filter import basefilter -import cpg, _cputil, cperror, _cpcgifs +import cherrypy +from cherrypy import _cputil, _cpcgifs # Can't use cStringIO; doesn't support unicode strings # See http://www.python.org/sf/216388 @@ -105,7 +106,7 @@ class Request(object): """ def __init__(self, clientAddress, remoteHost, requestLine, headers, rfile): - # When __init__ is finished, cpg.response should have three attributes: + # When __init__ is finished, cherrypy.response should have three attributes: # status, e.g. "200 OK" # headers, a list of (name, value) tuples # body, an iterable yielding strings @@ -115,38 +116,38 @@ class Request(object): self.requestLine = requestLine self.requestHeaders = headers - # Prepare cpg.request variables - cpg.request.remoteAddr = clientAddress - cpg.request.remoteHost = remoteHost - cpg.request.paramList = [] # Only used for Xml-Rpc - cpg.request.headerMap = {} - cpg.request.requestLine = requestLine - cpg.request.simpleCookie = Cookie.SimpleCookie() - cpg.request.rfile = rfile + # Prepare cherrypy.request variables + cherrypy.request.remoteAddr = clientAddress + cherrypy.request.remoteHost = remoteHost + cherrypy.request.paramList = [] # Only used for Xml-Rpc + cherrypy.request.headerMap = {} + cherrypy.request.requestLine = requestLine + cherrypy.request.simpleCookie = Cookie.SimpleCookie() + cherrypy.request.rfile = rfile - # Prepare cpg.response variables - cpg.response.status = None - cpg.response.headers = None - cpg.response.body = None + # Prepare cherrypy.response variables + cherrypy.response.status = None + cherrypy.response.headers = None + cherrypy.response.body = None year, month, day, hh, mm, ss, wd, y, z = time.gmtime() date = ("%s, %02d %3s %4d %02d:%02d:%02d GMT" % (weekdayname[wd], day, monthname[month], year, hh, mm, ss)) - cpg.response.headerMap = KeyTitlingDict() - cpg.response.headerMap.update({ + cherrypy.response.headerMap = KeyTitlingDict() + cherrypy.response.headerMap.update({ "Content-Type": "text/html", - "Server": "CherryPy/" + cpg.__version__, + "Server": "CherryPy/" + cherrypy.__version__, "Date": date, "Set-Cookie": [], "Content-Length": 0 }) - cpg.response.simpleCookie = Cookie.SimpleCookie() + cherrypy.response.simpleCookie = Cookie.SimpleCookie() self.run() - if cpg.request.method == "HEAD": + if cherrypy.request.method == "HEAD": # HEAD requests MUST NOT return a message-body in the response. - cpg.response.body = [] + cherrypy.response.body = [] def run(self): try: @@ -157,18 +158,18 @@ class Request(object): self.processRequestHeaders() applyFilters('beforeRequestBody') - if cpg.request.processRequestBody: + if cherrypy.request.processRequestBody: self.processRequestBody() applyFilters('beforeMain') - if cpg.response.body is None: + if cherrypy.response.body is None: main() applyFilters('beforeFinalize') finalize() - except cperror.RequestHandled: + except cherrypy.RequestHandled: pass - except cperror.HTTPRedirect, inst: + except cherrypy.HTTPRedirect, inst: # For an HTTPRedirect, we don't go through the regular # mechanism: we return the redirect immediately inst.set_response() @@ -180,21 +181,21 @@ class Request(object): def processRequestHeaders(self): # Parse first line - cpg.request.method, path, cpg.request.protocol = self.requestLine.split() - cpg.request.processRequestBody = cpg.request.method in ("POST",) + cherrypy.request.method, path, cherrypy.request.protocol = self.requestLine.split() + cherrypy.request.processRequestBody = cherrypy.request.method in ("POST",) # find the queryString, or set it to "" if not found if "?" in path: - cpg.request.path, cpg.request.queryString = path.split("?", 1) + cherrypy.request.path, cherrypy.request.queryString = path.split("?", 1) else: - cpg.request.path, cpg.request.queryString = path, "" + cherrypy.request.path, cherrypy.request.queryString = path, "" # build a paramMap dictionary from queryString - pm = cgi.parse_qs(cpg.request.queryString, keep_blank_values=True) + pm = cgi.parse_qs(cherrypy.request.queryString, keep_blank_values=True) for key, val in pm.items(): if len(val) == 1: pm[key] = val[0] - cpg.request.paramMap = pm + cherrypy.request.paramMap = pm # Process the headers into request.headerMap for name, value in self.requestHeaders: @@ -203,54 +204,54 @@ class Request(object): # Warning: if there is more than one header entry for cookies (AFAIK, # only Konqueror does that), only the last one will remain in headerMap # (but they will be correctly stored in request.simpleCookie). - cpg.request.headerMap[name] = value + cherrypy.request.headerMap[name] = value # Handle cookies differently because on Konqueror, multiple cookies # come on different lines with the same key if name == 'Cookie': - cpg.request.simpleCookie.load(value) + cherrypy.request.simpleCookie.load(value) - msg = "%s - %s" % (cpg.request.remoteAddr, self.requestLine[:-2]) - cpg.log(msg, "HTTP") + msg = "%s - %s" % (cherrypy.request.remoteAddr, self.requestLine[:-2]) + cherrypy.log(msg, "HTTP") - cpg.request.base = "http://" + cpg.request.headerMap.get('Host', '') - cpg.request.browserUrl = cpg.request.base + path + cherrypy.request.base = "http://" + cherrypy.request.headerMap.get('Host', '') + cherrypy.request.browserUrl = cherrypy.request.base + path # Change objectPath in filters to change # the object that will get rendered - cpg.request.objectPath = None + cherrypy.request.objectPath = None # Save original values (in case they get modified by filters) - cpg.request.originalPath = cpg.request.path - cpg.request.originalParamMap = cpg.request.paramMap - cpg.request.originalParamList = cpg.request.paramList + cherrypy.request.originalPath = cherrypy.request.path + cherrypy.request.originalParamMap = cherrypy.request.paramMap + cherrypy.request.originalParamList = cherrypy.request.paramList def processRequestBody(self): # Create a copy of headerMap with lowercase keys because # FieldStorage doesn't work otherwise lowerHeaderMap = {} - for key, value in cpg.request.headerMap.items(): + for key, value in cherrypy.request.headerMap.items(): lowerHeaderMap[key.lower()] = value - forms = _cpcgifs.FieldStorage(fp=cpg.request.rfile, headers=lowerHeaderMap, + forms = _cpcgifs.FieldStorage(fp=cherrypy.request.rfile, headers=lowerHeaderMap, environ = {'REQUEST_METHOD': 'POST'}, keep_blank_values = 1) for key in forms.keys(): valueList = forms[key] if isinstance(valueList, list): - cpg.request.paramMap[key] = [] + cherrypy.request.paramMap[key] = [] for item in valueList: if item.file is not None: value = item # It's a file upload else: value = item.value # It's a regular field - cpg.request.paramMap[key].append(value) + cherrypy.request.paramMap[key].append(value) else: if valueList.file is not None: value = valueList # It's a file upload else: value = valueList.value # It's a regular field - cpg.request.paramMap[key] = value + cherrypy.request.paramMap[key] = value # Error handling @@ -271,7 +272,7 @@ def handleError(exc): try: applyFilters('beforeErrorResponse') - # _cpOnError will probably change cpg.response.body. + # _cpOnError will probably change cherrypy.response.body. # It may also change the headerMap, etc. _cputil.getSpecialAttribute('_cpOnError')() @@ -282,8 +283,8 @@ def handleError(exc): # Failure in _cpOnError, error filter, or finalize. # Bypass them all. body = dbltrace % (formatExc(exc), formatExc()) - cpg.response.status, cpg.response.headers, body = bareError(body) - cpg.response.body = body + cherrypy.response.status, cherrypy.response.headers, body = bareError(body) + cherrypy.response.body = body def formatExc(exc=None): """formatExc(exc=None) -> exc (or sys.exc_info), formatted.""" @@ -316,21 +317,21 @@ def bareError(extrabody=None): # Response functions def main(path=None): - """Obtain and set cpg.response.body.""" + """Obtain and set cherrypy.response.body.""" if path is None: - path = cpg.request.objectPath or cpg.request.path + path = cherrypy.request.objectPath or cherrypy.request.path while True: try: func, objectPathList, virtualPathList = mapPathToObject(path) # Remove "root" from objectPathList and join it to get objectPath - cpg.request.objectPath = '/' + '/'.join(objectPathList[1:]) - body = func(*(virtualPathList + cpg.request.paramList), - **(cpg.request.paramMap)) - cpg.response.body = iterable(body) + cherrypy.request.objectPath = '/' + '/'.join(objectPathList[1:]) + body = func(*(virtualPathList + cherrypy.request.paramList), + **(cherrypy.request.paramMap)) + cherrypy.response.body = iterable(body) return - except cperror.InternalRedirect, x: + except cherrypy.InternalRedirect, x: # Try again with the new path path = x.path @@ -347,11 +348,11 @@ def iterable(body): return body def checkStatus(): - """Test/set cpg.response.status. Provide Reason-phrase if missing.""" - if not cpg.response.status: - cpg.response.status = "200 OK" + """Test/set cherrypy.response.status. Provide Reason-phrase if missing.""" + if not cherrypy.response.status: + cherrypy.response.status = "200 OK" else: - status = str(cpg.response.status) + status = str(cherrypy.response.status) parts = status.split(" ", 1) if len(parts) == 1: # No reason supplied. @@ -374,8 +375,8 @@ def checkStatus(): except (KeyError, IndexError): reason = "" - cpg.response.status = "%s %s" % (code, reason) - return cpg.response.status + cherrypy.response.status = "%s %s" % (code, reason) + return cherrypy.response.status general_header_fields = ["Cache-Control", "Connection", "Date", "Pragma", @@ -399,19 +400,19 @@ for _ in entity_header_fields: def finalize(): - """Transform headerMap + cookies into cpg.response.headers.""" + """Transform headerMap + cookies into cherrypy.response.headers.""" checkStatus() - if (cpg.config.get("server.protocolVersion") != "HTTP/1.1" - and cpg.response.headerMap.get('Content-Length') == 0): - content = ''.join(cpg.response.body) - cpg.response.body = [content] - cpg.response.headerMap['Content-Length'] = len(content) + if (cherrypy.config.get("server.protocolVersion") != "HTTP/1.1" + and cherrypy.response.headerMap.get('Content-Length') == 0): + content = ''.join(cherrypy.response.body) + cherrypy.response.body = [content] + cherrypy.response.headerMap['Content-Length'] = len(content) # Headers headers = [] - for key, valueList in cpg.response.headerMap.iteritems(): + for key, valueList in cherrypy.response.headerMap.iteritems(): order = _header_order_map.get(key, 3) if not isinstance(valueList, list): valueList = [valueList] @@ -421,13 +422,13 @@ def finalize(): # first, followed by request-header or response-header fields, and # ending with the entity-header fields.' headers.sort() - cpg.response.headers = [item[1] for item in headers] + cherrypy.response.headers = [item[1] for item in headers] - cookie = cpg.response.simpleCookie.output() + cookie = cherrypy.response.simpleCookie.output() if cookie: name, value = cookie.split(": ", 1) - cpg.response.headers.append((name, value)) - return cpg.response.headers + cherrypy.response.headers.append((name, value)) + return cherrypy.response.headers def applyFilters(methodName): if methodName in ('beforeRequestBody', 'beforeMain'): @@ -465,32 +466,32 @@ def flattener(input): def serve_file(filename): - # If filename is relative, make absolute using cpg.root's module. + # If filename is relative, make absolute using cherrypy.root's module. if not os.path.isabs(filename): - root = os.path.dirname(sys.modules[cpg.root.__module__].__file__) + root = os.path.dirname(sys.modules[cherrypy.root.__module__].__file__) filename = os.path.join(root, filename) # Serve filename try: stat = os.stat(filename) except OSError: - raise cperror.NotFound(cpg.request.path) + raise cherrypy.NotFound(cherrypy.request.path) modifTime = stat.st_mtime strModifTime = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(modifTime)) - if cpg.request.headerMap.has_key('If-Modified-Since'): + if cherrypy.request.headerMap.has_key('If-Modified-Since'): # Check if if-modified-since date is the same as strModifTime - if cpg.request.headerMap['If-Modified-Since'] == strModifTime: - cpg.response.status = "304 Not Modified" - cpg.response.body = [] + if cherrypy.request.headerMap['If-Modified-Since'] == strModifTime: + cherrypy.response.status = "304 Not Modified" + cherrypy.response.body = [] return - cpg.response.headerMap['Last-Modified'] = strModifTime + cherrypy.response.headerMap['Last-Modified'] = strModifTime # Set Content-Length and use an iterable (file object) # this way CP won't load the whole file in memory - cpg.response.headerMap['Content-Length'] = stat[6] - cpg.response.body = open(filename, 'rb') + cherrypy.response.headerMap['Content-Length'] = stat[6] + cherrypy.response.body = open(filename, 'rb') # Set content-type based on filename extension i = filename.rfind('.') @@ -499,7 +500,7 @@ def serve_file(filename): else: ext = "" contentType = mimetypes.types_map.get(ext, "text/plain") - cpg.response.headerMap['Content-Type'] = contentType + cherrypy.response.headerMap['Content-Type'] = contentType # Object lookup @@ -508,11 +509,11 @@ def getObjFromPath(objPathList): """ For a given objectPathList (like ['root', 'a', 'b', 'index']), return the object (or None if it doesn't exist). """ - root = cpg + root = cherrypy for objname in objPathList: # maps virtual filenames to Python identifiers (substitutes '.' for '_') objname = objname.replace('.', '_') - if getattr(cpg, "debug", None): + if getattr(cherrypy, "debug", None): print "Attempting to call method: %s.%s" % (root, objname) root = getattr(root, objname, None) if root is None: @@ -541,7 +542,7 @@ def mapPathToObject(path): objectPathList = tpath.split('/') objectPathList = ['root'] + objectPathList + ['index'] - if getattr(cpg, "debug", None): + if getattr(cherrypy, "debug", None): print "Attempting to map path: %s" % tpath print " objectPathList: %s" % objectPathList @@ -582,10 +583,10 @@ def mapPathToObject(path): icofile = os.path.join(os.path.dirname(__file__), "favicon.ico") serve_file(icofile) finalize() - raise cperror.RequestHandled + raise cherrypy.RequestHandled else: # We didn't find anything - raise cperror.NotFound(path) + raise cherrypy.NotFound(path) if isFirst: # We found the extra ".index" @@ -593,9 +594,9 @@ def mapPathToObject(path): # a redirect) if path[-1] != '/': newUrl = path + '/' - if cpg.request.queryString: - newUrl += "?" + cpg.request.queryString - raise cperror.HTTPRedirect(newUrl) + if cherrypy.request.queryString: + newUrl += "?" + cherrypy.request.queryString + raise cherrypy.HTTPRedirect(newUrl) return candidate, objectPathList, virtualPathList diff --git a/cherrypy/_cputil.py b/cherrypy/_cputil.py index b265aec0..2d9e757b 100644 --- a/cherrypy/_cputil.py +++ b/cherrypy/_cputil.py @@ -26,12 +26,12 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - """ A module containing a few utility classes/functions used by CherryPy """ -import time, cpg, cperror +import time +import cherrypy class EmptyClass: @@ -40,13 +40,13 @@ class EmptyClass: def getObjectTrail(): - """ Return all objects from the currenct object to cpg """ - root = getattr(cpg, 'root', None) + """ Return all objects from the currenct object to cherrypy """ + root = getattr(cherrypy, 'root', None) if root: objectTrail = [root] # Try object path try: - path = cpg.request.objectPath or cpg.request.path + path = cherrypy.request.objectPath or cherrypy.request.path except AttributeError: path = '/' if path: @@ -64,12 +64,12 @@ def getObjectTrail(): return None def getSpecialAttribute(name): - """ Return the special attribute. A special attribute is
- one that applies to all of the children from where it is
- defined, such as _cpFilterList.""" + """Return the special attribute. A special attribute is one that + applies to all of the children from where it is defined, such as + _cpFilterList.""" # First, we look in the right-most object if this special attribute is implemented. - # If not, then we try the previous object and so on until we reach cpg.root + # If not, then we try the previous object and so on until we reach cherrypy.root # If it's still not there, we use the implementation from this module. objectList = getObjectTrail() @@ -84,19 +84,20 @@ def getSpecialAttribute(name): try: return globals()[name] except KeyError: - raise cperror.InternalError("Special attribute %s could not be found" - % repr(name))
-
-def getSpecialAttributePath(name):
- """ Return the path to the special attribute """
- objectList = getObjectTrail()
- if objectList:
- pathList = (cpg.request.objectPath or cpg.request.path).split("/")[1:]
- for i in xrange(len(objectList) - 1, -1, -1):
- if hasattr(objectList[i], name):
- return "/" + "/".join(pathList[:i] + [name])
- raise cperror.InternalError("Special attribute %s could not be found" - % repr(name)) + raise cherrypy.InternalError("Special attribute %s could not be found" + % repr(name)) + +def getSpecialAttributePath(name): + """ Return the path to the special attribute """ + objectList = getObjectTrail() + if objectList: + pathList = cherrypy.request.objectPath or cherrypy.request.path + pathList = pathList.split("/")[1:] + for i in xrange(len(objectList) - 1, -1, -1): + if hasattr(objectList[i], name): + return "/" + "/".join(pathList[:i] + [name]) + raise cherrypy.InternalError("Special attribute %s could not be found" + % repr(name)) def _cpLogMessage(msg, context = '', severity = 0): """ Default method for logging messages """ @@ -112,14 +113,14 @@ def _cpLogMessage(msg, context = '', severity = 0): else: level = "UNKNOWN" try: - logToScreen = cpg.config.get('server.logToScreen') + logToScreen = cherrypy.config.get('server.logToScreen') except: logToScreen = True s = nowStr + ' ' + context + ' ' + level + ' ' + msg if logToScreen: print s - if cpg.config.get('server.logFile'): - f = open(cpg.config.get('server.logFile'), 'ab') + if cherrypy.config.get('server.logFile'): + f = open(cherrypy.config.get('server.logFile'), 'ab') f.write(s + '\n') f.close() @@ -127,10 +128,10 @@ def _cpOnError(): """ Default _cpOnError method """ import sys, traceback content = "".join(traceback.format_exception(*sys.exc_info())) - cpg.response.body = [content] - cpg.response.headerMap['Content-Type'] = 'text/plain' - if cpg.response.headerMap.has_key('Content-Encoding'): - del cpg.response.headerMap['Content-Encoding'] + cherrypy.response.body = [content] + cherrypy.response.headerMap['Content-Type'] = 'text/plain' + if cherrypy.response.headerMap.has_key('Content-Encoding'): + del cherrypy.response.headerMap['Content-Encoding'] _cpFilterList = [] @@ -140,7 +141,7 @@ from cherrypy.lib.filter import baseurlfilter, cachefilter, \ staticfilter, nsgmlsfilter, tidyfilter, \ virtualhostfilter, xmlrpcfilter, sessionauthenticatefilter -from cherrypy.lib.filter.sessionfilter import sessionfilter +from cherrypy.lib.filter import sessionfilter _cachefilter = cachefilter.CacheFilter() _logdebuginfofilter = logdebuginfofilter.LogDebugInfoFilter() @@ -235,4 +236,4 @@ def unrepr(s): try: return Builder().build(getObj(s)) except: - raise cperror.WrongUnreprValue, repr(s) + raise cherrypy.WrongUnreprValue, repr(s) diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py index 6cb95000..6d9c5f67 100644 --- a/cherrypy/_cpwsgi.py +++ b/cherrypy/_cpwsgi.py @@ -33,7 +33,8 @@ A WSGI application and server (see PEP 333). import threading import os, socket, sys, traceback, urllib import SocketServer, BaseHTTPServer -import cpg, _cpserver, _cphttptools, _cpwsgiserver +import cherrypy +from cherrypy import _cphttptools, _cpwsgiserver def requestLine(environ): @@ -77,25 +78,25 @@ class NullWriter(object): def wsgiApp(environ, start_response): # Trap screen output from BaseHTTPRequestHandler.log_message() - if not cpg.config.get('server.logToScreen'): + if not cherrypy.config.get('server.logToScreen'): sys.stderr = NullWriter() try: # LOGON_USER is served by IIS, and is the name of the # user after having been mapped to a local account. # Both IIS and Apache set REMOTE_USER, when possible. - cpg.request.login = (environ.get('LOGON_USER') + cherrypy.request.login = (environ.get('LOGON_USER') or environ.get('REMOTE_USER') or None) - cpg.request.multithread = environ['wsgi.multithread'] - cpg.request.multiprocess = environ['wsgi.multiprocess'] - _cpserver.request(environ.get('REMOTE_ADDR', ''), - environ.get('REMOTE_ADDR', ''), - requestLine(environ), - translate_headers(environ), - environ['wsgi.input'], - ) - start_response(cpg.response.status, cpg.response.headers) - for chunk in cpg.response.body: + cherrypy.request.multithread = environ['wsgi.multithread'] + cherrypy.request.multiprocess = environ['wsgi.multiprocess'] + cherrypy.server.request(environ.get('REMOTE_ADDR', ''), + environ.get('REMOTE_ADDR', ''), + requestLine(environ), + translate_headers(environ), + environ['wsgi.input'], + ) + start_response(cherrypy.response.status, cherrypy.response.headers) + for chunk in cherrypy.response.body: # WSGI requires all data to be of type "str". This coercion should # not take any time at all if chunk is already of type "str". # If it's unicode, it could be a big performance hit (x ~500). @@ -103,7 +104,7 @@ def wsgiApp(environ, start_response): yield chunk except: tb = _cphttptools.formatExc() - cpg.log(tb) + cherrypy.log(tb) s, h, b = _cphttptools.bareError(tb) # CherryPy test suite expects bareError body to be output, # so don't call start_response (which, according to PEP 333, @@ -114,13 +115,16 @@ def wsgiApp(environ, start_response): -# Server components +# Server components. +# _cpwsgiserver should not reference CherryPy in any way, so that it can +# be used in other frameworks and applications. Therefore, we wrap it here. class WSGIServer(_cpwsgiserver.CherryPyWSGIServer): def __init__(self): + conf = cherrypy.config.get _cpwsgiserver.CherryPyWSGIServer.__init__(self, - (cpg.config.get("server.socketHost"), - cpg.config.get("server.socketPort")), + (conf("server.socketHost"), + conf("server.socketPort")), wsgiApp, - cpg.config.get("server.threadPool"), - cpg.config.get("server.socketHost")) + conf("server.threadPool"), + conf("server.socketHost")) diff --git a/cherrypy/_cpwsgiserver.py b/cherrypy/_cpwsgiserver.py index efb5bfb7..e2055938 100644 --- a/cherrypy/_cpwsgiserver.py +++ b/cherrypy/_cpwsgiserver.py @@ -184,7 +184,7 @@ class CherryPyWSGIServer(object): run the server forever ''' # We don't have to trap KeyboardInterrupt or SystemExit here, - # because _cpserver already does so, calling self.stop() for us. + # because cherrpy.server already does so, calling self.stop() for us. # If you're using this server with another framework, you should # trap those exceptions in whatever code block calls start(). self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) diff --git a/cherrypy/_cpconfig.py b/cherrypy/config.py index 45439e80..da154033 100644 --- a/cherrypy/_cpconfig.py +++ b/cherrypy/config.py @@ -1,22 +1,44 @@ +""" +Copyright (c) 2004, CherryPy Team (team@cherrypy.org) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the CherryPy Team nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +""" +Configuration system for CherryPy. +""" +import os.path import ConfigParser -import _cputil, cperror -from lib import autoreload - -cpg = None # delayed import -def init(): - global cpg - if not cpg: - import cpg - reset() +import cherrypy +from cherrypy import _cputil, _cperror +from cherrypy.lib import autoreload -def reset(useDefaults=True): - configMap.clear() - if useDefaults: - configMap["global"] = defaultGlobal.copy() -# This configMap dict holds the settings metadata for all cpg objects. +# This configMap dict holds the settings metadata for all cherrypy objects. # Keys are URL paths, and values are dicts. configMap = {} @@ -43,6 +65,12 @@ defaultGlobal = { 'sessionFilter.default.storageFileDir': '.sessionFiles' } +def reset(useDefaults=True): + configMap.clear() + if useDefaults: + configMap["global"] = defaultGlobal.copy() +reset() + def update(updateMap=None, file=None): if updateMap: for section, valueMap in updateMap.items(): @@ -63,12 +91,12 @@ def update(updateMap=None, file=None): def get(key, defaultValue=None, returnSection=False, startPath = None): # Look, ma, no Python function calls! Uber-fast. - # start path lest you overload the starting search path (needed by getAll) + # startPath lets you overload the starting search path (needed by getAll) if startPath: path = startPath else: try: - path = cpg.request.path + path = cherrypy.request.path except AttributeError: path = "/" @@ -98,8 +126,6 @@ def get(key, defaultValue=None, returnSection=False, startPath = None): return path else: return result - -import os.path def getAll(key): """ @@ -123,6 +149,7 @@ def getAll(key): return result + class CaseSensitiveConfigParser(ConfigParser.ConfigParser): """ Sub-class of ConfigParser that keeps the case of options and that raises an exception if the file cannot be read @@ -147,13 +174,13 @@ def _load(configFile = None): # Parse config file configParser = CaseSensitiveConfigParser() if hasattr(configFile, 'read'): - cpg.log("Reading infos from configFile stream", 'CONFIG') + cherrypy.log("Reading infos from configFile stream", 'CONFIG') configParser.readfp(configFile) else: - cpg.log("Reading infos from configFile: %s" % configFile, 'CONFIG') + cherrypy.log("Reading infos from configFile: %s" % configFile, 'CONFIG') configParser.read(configFile) - - # Load INI file into cpg.configMap + + # Load INI file into cherrypy.configMap for section in configParser.sections(): if section not in configMap: configMap[section] = {} @@ -161,28 +188,28 @@ def _load(configFile = None): value = configParser.get(section, option) try: value = _cputil.unrepr(value) - except cperror.WrongUnreprValue, s: + except _cperror.WrongUnreprValue, s: msg = ("section: %s, option: %s, value: %s" % (repr(section), repr(option), repr(value))) - raise cperror.WrongConfigValue, msg + raise _cperror.WrongConfigValue, msg configMap[section][option] = value def outputConfigMap(): - cpg.log("Server parameters:", 'CONFIG') - cpg.log(" server.environment: %s" % get('server.environment'), 'CONFIG') - cpg.log(" server.logToScreen: %s" % get('server.logToScreen'), 'CONFIG') - cpg.log(" server.logFile: %s" % get('server.logFile'), 'CONFIG') - cpg.log(" server.protocolVersion: %s" % get('server.protocolVersion'), 'CONFIG') - cpg.log(" server.socketHost: %s" % get('server.socketHost'), 'CONFIG') - cpg.log(" server.socketPort: %s" % get('server.socketPort'), 'CONFIG') - cpg.log(" server.socketFile: %s" % get('server.socketFile'), 'CONFIG') - cpg.log(" server.reverseDNS: %s" % get('server.reverseDNS'), 'CONFIG') - cpg.log(" server.socketQueueSize: %s" % get('server.socketQueueSize'), 'CONFIG') - cpg.log(" server.threadPool: %s" % get('server.threadPool'), 'CONFIG') - cpg.log(" session.storageType: %s" % get('session.storageType'), 'CONFIG') + cherrypy.log("Server parameters:", 'CONFIG') + cherrypy.log(" server.environment: %s" % get('server.environment'), 'CONFIG') + cherrypy.log(" server.logToScreen: %s" % get('server.logToScreen'), 'CONFIG') + cherrypy.log(" server.logFile: %s" % get('server.logFile'), 'CONFIG') + cherrypy.log(" server.protocolVersion: %s" % get('server.protocolVersion'), 'CONFIG') + cherrypy.log(" server.socketHost: %s" % get('server.socketHost'), 'CONFIG') + cherrypy.log(" server.socketPort: %s" % get('server.socketPort'), 'CONFIG') + cherrypy.log(" server.socketFile: %s" % get('server.socketFile'), 'CONFIG') + cherrypy.log(" server.reverseDNS: %s" % get('server.reverseDNS'), 'CONFIG') + cherrypy.log(" server.socketQueueSize: %s" % get('server.socketQueueSize'), 'CONFIG') + cherrypy.log(" server.threadPool: %s" % get('server.threadPool'), 'CONFIG') + cherrypy.log(" session.storageType: %s" % get('session.storageType'), 'CONFIG') if get('session.storageType'): - cpg.log(" session.timeout: %s min" % get('session.timeout'), 'CONFIG') - cpg.log(" session.cleanUpDelay: %s min" % get('session.cleanUpDelay'), 'CONFIG') - cpg.log(" session.cookieName: %s" % get('session.cookieName'), 'CONFIG') - cpg.log(" session.storageFileDir: %s" % get('session.storageFileDir'), 'CONFIG') - cpg.log(" staticContent: %s" % get('staticContent'), 'CONFIG') + cherrypy.log(" session.timeout: %s min" % get('session.timeout'), 'CONFIG') + cherrypy.log(" session.cleanUpDelay: %s min" % get('session.cleanUpDelay'), 'CONFIG') + cherrypy.log(" session.cookieName: %s" % get('session.cookieName'), 'CONFIG') + cherrypy.log(" session.storageFileDir: %s" % get('session.storageFileDir'), 'CONFIG') + cherrypy.log(" staticContent: %s" % get('staticContent'), 'CONFIG') diff --git a/cherrypy/cpg.py b/cherrypy/cpg.py deleted file mode 100644 index 01cc12eb..00000000 --- a/cherrypy/cpg.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -Copyright (c) 2004, CherryPy Team (team@cherrypy.org) -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the CherryPy Team nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - -""" -Global module that all modules developing with CherryPy should import. -""" - -from __init__ import __version__ - -_httpserver = None - -# import server module -import _cpserver as server -import _cpconfig as config -config.init() - -# decorator function for exposing methods -def expose(func): - func.exposed = True - return func - -def log(msg, context='', severity=0): - """Syntactic sugar for writing to the log.""" - import _cputil - logfunc = _cputil.getSpecialAttribute('_cpLogMessage') - logfunc(msg, context, severity) - diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py index 295a4f7e..99515be2 100644 --- a/cherrypy/lib/cptools.py +++ b/cherrypy/lib/cptools.py @@ -27,35 +27,36 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ """ -Just a few convenient functions and classes. +Just a few convenient functions and classes """ -
-import inspect
-
-def decorate(func, decorator):
- """
- Return the decorated func. This will automatically copy all
- non-standard attributes (like exposed) to the newly decorated function.
- """
- newfunc = decorator(func)
- for (k,v) in inspect.getmembers(func):
- if not hasattr(newfunc, k):
- setattr(newfunc, k, v)
- return newfunc
-
-def decorateAll(obj, decorator):
- """
- Recursively decorate all exposed functions of obj and all of its children,
- grandchildren, etc. If you used to use aspects, you might want to look
- into these. This function modifies obj; there is no return value.
- """
- obj_type = type(obj)
- for (k,v) in inspect.getmembers(obj):
- if hasattr(obj_type, k): # only deal with user-defined attributes
- continue
- if callable(v) and getattr(v, "exposed", False):
- setattr(obj, k, decorate(v, decorator))
- decorateAll(v, decorator)
+ +import inspect + +def decorate(func, decorator): + """ + Return the decorated func. This will automatically copy all + non-standard attributes (like exposed) to the newly decorated function. + """ + newfunc = decorator(func) + for (k,v) in inspect.getmembers(func): + if not hasattr(newfunc, k): + setattr(newfunc, k, v) + return newfunc + +def decorateAll(obj, decorator): + """ + Recursively decorate all exposed functions of obj and all of its children, + grandchildren, etc. If you used to use aspects, you might want to look + into these. This function modifies obj; there is no return value. + """ + obj_type = type(obj) + for (k,v) in inspect.getmembers(obj): + if hasattr(obj_type, k): # only deal with user-defined attributes + continue + if callable(v) and getattr(v, "exposed", False): + setattr(obj, k, decorate(v, decorator)) + decorateAll(v, decorator) + class ExposeItems: """ @@ -68,8 +69,8 @@ class ExposeItems: from cherrypy.lib.cptools import ExposeItems ... - cpg.root.foo = ExposeItems(mylist) - cpg.root.bar = ExposeItems(mydict) + cherrypy.root.foo = ExposeItems(mylist) + cherrypy.root.bar = ExposeItems(mydict) """ exposed = True def __init__(self, items): @@ -85,13 +86,13 @@ class PositionalParametersAware(object): Use case: from cherrypy.lib import cptools - from cherrypy import cpg + import cherrypy class Root(cptools.PositionalParametersAware): def something(self, name): return "hello, " + name something.exposed - cpg.root = Root() - cpg.server.start() + cherrypy.root = Root() + cherrypy.server.start() Now, fetch http://localhost:8080/something/name_is_here """ diff --git a/cherrypy/lib/csauthenticate.py b/cherrypy/lib/csauthenticate.py index 42b30056..63a7b569 100644 --- a/cherrypy/lib/csauthenticate.py +++ b/cherrypy/lib/csauthenticate.py @@ -27,7 +27,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import time, random -from cherrypy import cpg +import cherrypy from aspect import Aspect, STOP, CONTINUE @@ -44,14 +44,14 @@ class CSAuthenticate(Aspect): timeout = 60 # in minutes def notLoggedIn(self, message): - return STOP, self.loginScreen(message, cpg.request.browserUrl) + return STOP, self.loginScreen(message, cherrypy.request.browserUrl) def _before(self, methodName, method): # If the method is not exposed, don't do anything if not getattr(method, 'exposed', None): return CONTINUE, None - cpg.request.login = '' + cherrypy.request.login = '' # If the method is one of these 4, do not try to find out who is logged in if methodName in ["loginScreen", "logoutScreen", "doLogin", "doLogout", "notLoggedIn"]: return CONTINUE, None @@ -59,29 +59,29 @@ class CSAuthenticate(Aspect): # Check if a user is logged in: # - If they are, set request.login with the right value # - If not, return the login screen - if not cpg.request.simpleCookie.has_key(self.sessionIdCookieName): - # return STOP, self.loginScreen(self.noCookieMessage, cpg.request.browserUrl) + if not cherrypy.request.simpleCookie.has_key(self.sessionIdCookieName): + # return STOP, self.loginScreen(self.noCookieMessage, cherrypy.request.browserUrl) return self.notLoggedIn(self.noCookieMessage) - sessionId = cpg.request.simpleCookie[self.sessionIdCookieName].value + sessionId = cherrypy.request.simpleCookie[self.sessionIdCookieName].value now=time.time() # Check that session exists and hasn't timed out timeout=0 - if not cpg.request.sessionMap.has_key(sessionId): - # return STOP, self.loginScreen(self.noCookieMessage, cpg.request.browserUrl) + if not cherrypy.request.sessionMap.has_key(sessionId): + # return STOP, self.loginScreen(self.noCookieMessage, cherrypy.request.browserUrl) return self.notLoggedIn(self.noCookieMessage) else: - login, expire = cpg.request.sessionMap[sessionId] + login, expire = cherrypy.request.sessionMap[sessionId] if expire < now: timeout=1 else: expire = now + self.timeout*60 - cpg.request.sessionMap[sessionId] = login, expire + cherrypy.request.sessionMap[sessionId] = login, expire if timeout: - # return STOP, self.loginScreen(self.timeoutMessage, cpg.request.browserUrl) + # return STOP, self.loginScreen(self.timeoutMessage, cherrypy.request.browserUrl) return self.notLoggedIn(self.timeoutMessage) - cpg.request.login = login + cherrypy.request.login = login return CONTINUE, None def checkLoginAndPassword(self, login, password): @@ -99,19 +99,19 @@ class CSAuthenticate(Aspect): # Check that login/password match errorMsg = self.checkLoginAndPassword(login, password) if errorMsg: - cpg.request.login = '' + cherrypy.request.login = '' return self.loginScreen(errorMsg, fromPage, login) - cpg.request.login = login + cherrypy.request.login = login # Set session - newSessionId = self.generateSessionId(cpg.request.sessionMap.keys()) - cpg.request.sessionMap[newSessionId] = login, time.time()+self.timeout*60 + newSessionId = self.generateSessionId(cherrypy.request.sessionMap.keys()) + cherrypy.request.sessionMap[newSessionId] = login, time.time()+self.timeout*60 - cpg.response.simpleCookie[self.sessionIdCookieName] = newSessionId - cpg.response.simpleCookie[self.sessionIdCookieName]['path'] = '/' - cpg.response.simpleCookie[self.sessionIdCookieName]['max-age'] = 31536000 - cpg.response.simpleCookie[self.sessionIdCookieName]['version'] = 1 - cpg.response.status = "302 Found" - cpg.response.headerMap['Location'] = fromPage + cherrypy.response.simpleCookie[self.sessionIdCookieName] = newSessionId + cherrypy.response.simpleCookie[self.sessionIdCookieName]['path'] = '/' + cherrypy.response.simpleCookie[self.sessionIdCookieName]['max-age'] = 31536000 + cherrypy.response.simpleCookie[self.sessionIdCookieName]['version'] = 1 + cherrypy.response.status = "302 Found" + cherrypy.response.headerMap['Location'] = fromPage return "" doLogin.exposed = True @@ -121,13 +121,13 @@ class CSAuthenticate(Aspect): del request.sessionMap[sessionId] except: pass - cpg.response.simpleCookie[self.sessionIdCookieName] = "" - cpg.response.simpleCookie[self.sessionIdCookieName]['path'] = '/' - cpg.response.simpleCookie[self.sessionIdCookieName]['max-age'] = 0 - cpg.response.simpleCookie[self.sessionIdCookieName]['version'] = 1 - cpg.request.login = '' - cpg.response.status = "302 Found" - cpg.response.headerMap['Location'] = 'logoutScreen' + cherrypy.response.simpleCookie[self.sessionIdCookieName] = "" + cherrypy.response.simpleCookie[self.sessionIdCookieName]['path'] = '/' + cherrypy.response.simpleCookie[self.sessionIdCookieName]['max-age'] = 0 + cherrypy.response.simpleCookie[self.sessionIdCookieName]['version'] = 1 + cherrypy.request.login = '' + cherrypy.response.status = "302 Found" + cherrypy.response.headerMap['Location'] = 'logoutScreen' return "" doLogout.exposed = True diff --git a/cherrypy/lib/filter/baseurlfilter.py b/cherrypy/lib/filter/baseurlfilter.py index 06cac663..05410b80 100644 --- a/cherrypy/lib/filter/baseurlfilter.py +++ b/cherrypy/lib/filter/baseurlfilter.py @@ -28,6 +28,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from basefilter import BaseFilter + class BaseUrlFilter(BaseFilter): """Filter that changes the base URL. @@ -35,22 +36,19 @@ class BaseUrlFilter(BaseFilter): """ def beforeRequestBody(self): - # We have to dynamically import cpg because Python can't handle - # circular module imports :-( - global cpg - from cherrypy import cpg + import cherrypy - if not cpg.config.get('baseUrlFilter.on', False): + if not cherrypy.config.get('baseUrlFilter.on', False): return - newBaseUrl = cpg.config.get('baseUrlFilter.baseUrl', 'http://localhost') - if cpg.config.get('baseUrlFilter.useXForwardedHost', True): - newBaseUrl = cpg.request.headerMap.get("X-Forwarded-Host", newBaseUrl) + req = cherrypy.request + newBaseUrl = cherrypy.config.get('baseUrlFilter.baseUrl', 'http://localhost') + if cherrypy.config.get('baseUrlFilter.useXForwardedHost', True): + newBaseUrl = req.headerMap.get("X-Forwarded-Host", newBaseUrl) if newBaseUrl.find("://") == -1: - # add http:// or https:// if needed - newBaseUrl = cpg.request.base[:cpg.request.base.find("://") + 3] + newBaseUrl + # add http:// or https:// if needed + newBaseUrl = req.base[:req.base.find("://") + 3] + newBaseUrl - cpg.request.browserUrl = cpg.request.browserUrl.replace( - cpg.request.base, newBaseUrl) - cpg.request.base = newBaseUrl + req.browserUrl = req.browserUrl.replace(req.base, newBaseUrl) + req.base = newBaseUrl diff --git a/cherrypy/lib/filter/cachefilter.py b/cherrypy/lib/filter/cachefilter.py index 9ba2bc19..084ccdbb 100644 --- a/cherrypy/lib/filter/cachefilter.py +++ b/cherrypy/lib/filter/cachefilter.py @@ -33,7 +33,7 @@ import time import basefilter def defaultCacheKey(): - return cpg.request.browserUrl + return cherrypy.request.browserUrl class MemoryCache: @@ -130,54 +130,54 @@ class CacheFilter(basefilter.BaseFilter): self.maxobjects = maxobjects def onStartResource(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg, cperror - from cherrypy import cpg, cperror - cpg.threadData.cacheable = True + global cherrypy + import cherrypy + cherrypy.threadData.cacheable = True def beforeMain(self): - if not cpg.config.get('cacheFilter.on', False): + if not cherrypy.config.get('cacheFilter.on', False): return - if not hasattr(cpg, '_cache'): - cpg._cache = self.CacheClass(self.key, self.delay, + if not hasattr(cherrypy, '_cache'): + cherrypy._cache = self.CacheClass(self.key, self.delay, self.maxobjsize, self.maxsize, self.maxobjects) - cacheData = cpg._cache.get() - cpg.threadData.cacheable = not cacheData + cacheData = cherrypy._cache.get() + cherrypy.threadData.cacheable = not cacheData if cacheData: expirationTime, lastModified, obj = cacheData # found a hit! check the if-modified-since request header - modifiedSince = cpg.request.headerMap.get('If-Modified-Since', None) + modifiedSince = cherrypy.request.headerMap.get('If-Modified-Since', None) # print ("Cache hit: If-Modified-Since=%s, lastModified=%s" % # (modifiedSince, lastModified)) if modifiedSince is not None and modifiedSince == lastModified: - cpg._cache.totNonModified += 1 - cpg.response.status = "304 Not Modified" - cpg.response.body = [] + cherrypy._cache.totNonModified += 1 + cherrypy.response.status = "304 Not Modified" + cherrypy.response.body = [] else: # serve it & get out from the request - cpg.response.status, cpg.response.headers, body = obj - cpg.response.body = body - raise cperror.RequestHandled + cherrypy.response.status, cherrypy.response.headers, body = obj + cherrypy.response.body = body + raise cherrypy.RequestHandled def onEndResource(self): """Close & fix the cache entry after content was fully written""" - if not cpg.config.get('cacheFilter.on', False): + if not cherrypy.config.get('cacheFilter.on', False): return - if cpg.threadData.cacheable: - status = cpg.response.status - headers = cpg.response.headers + if cherrypy.threadData.cacheable: + status = cherrypy.response.status + headers = cherrypy.response.headers # Consume the body iterable. Only do this once! - body = cpg.response.body = [chunk for chunk in cpg.response.body] + body = cherrypy.response.body = [chunk for chunk in cherrypy.response.body] - if cpg.response.headerMap.get('Pragma', None) != 'no-cache': - lastModified = cpg.response.headerMap.get('Last-Modified', None) + if cherrypy.response.headerMap.get('Pragma', None) != 'no-cache': + lastModified = cherrypy.response.headerMap.get('Last-Modified', None) # saves the cache data - cpg._cache.put(lastModified, (status, headers, body)) + cherrypy._cache.put(lastModified, (status, headers, body)) def percentual(n,d): @@ -202,9 +202,9 @@ def formatSize(n): class CacheStats: def index(self): - cpg.response.headerMap['Content-Type'] = 'text/plain' - cpg.response.headerMap['Pragma'] = 'no-cache' - cache = cpg._cache + cherrypy.response.headerMap['Content-Type'] = 'text/plain' + cherrypy.response.headerMap['Pragma'] = 'no-cache' + cache = cherrypy._cache yield "Cache statistics\n" yield "Maximum object size: %s\n" % formatSize(cache.maxobjsize) yield "Maximum cache size: %s\n" % formatSize(cache.maxsize) diff --git a/cherrypy/lib/filter/decodingfilter.py b/cherrypy/lib/filter/decodingfilter.py index 4b2e5506..373b3522 100644 --- a/cherrypy/lib/filter/decodingfilter.py +++ b/cherrypy/lib/filter/decodingfilter.py @@ -32,16 +32,16 @@ class DecodingFilter(BaseFilter): """Automatically decodes request parameters (except uploads).""" def beforeMain(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg - from cherrypy import cpg - - if not cpg.config.get('decodingFilter.on', False): + global cherrypy + import cherrypy + + if not cherrypy.config.get('decodingFilter.on', False): return - enc = cpg.config.get('decodingFilter.encoding', 'utf-8') - for key, value in cpg.request.paramMap.items(): + enc = cherrypy.config.get('decodingFilter.encoding', 'utf-8') + for key, value in cherrypy.request.paramMap.items(): if hasattr(value, 'file'): # This is a file being uploaded: skip it continue @@ -51,5 +51,5 @@ class DecodingFilter(BaseFilter): else: # value is a regular string: decode it newValue = value.decode(enc) - cpg.request.paramMap[key] = newValue + cherrypy.request.paramMap[key] = newValue diff --git a/cherrypy/lib/filter/encodingfilter.py b/cherrypy/lib/filter/encodingfilter.py index 6badc7f2..c7469c8e 100644 --- a/cherrypy/lib/filter/encodingfilter.py +++ b/cherrypy/lib/filter/encodingfilter.py @@ -32,26 +32,27 @@ class EncodingFilter(BaseFilter): """Filter that automatically encodes the response.""" def beforeFinalize(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg - from cherrypy import cpg + global cherrypy + import cherrypy - if not cpg.config.get('encodingFilter.on', False): + conf = cherrypy.config.get + if not conf('encodingFilter.on', False): return - contentType = cpg.response.headerMap.get("Content-Type") + contentType = cherrypy.response.headerMap.get("Content-Type") if contentType: ctlist = contentType.split(';')[0] - if (ctlist in cpg.config.get('encodingFilter.mimeTypeList', ['text/html'])): - enc = cpg.config.get('encodingFilter.encoding', 'utf-8') + if (ctlist in conf('encodingFilter.mimeTypeList', ['text/html'])): + enc = conf('encodingFilter.encoding', 'utf-8') # Add "charset=..." to response Content-Type header if contentType and 'charset' not in contentType: - cpg.response.headerMap["Content-Type"] += ";charset=%s" % enc + cherrypy.response.headerMap["Content-Type"] += ";charset=%s" % enc # Return a generator that encodes the sequence def encode_body(body): for line in body: yield line.encode(enc) - cpg.response.body = encode_body(cpg.response.body) + cherrypy.response.body = encode_body(cherrypy.response.body) diff --git a/cherrypy/lib/filter/gzipfilter.py b/cherrypy/lib/filter/gzipfilter.py index ada7ca4b..ae2cc17a 100644 --- a/cherrypy/lib/filter/gzipfilter.py +++ b/cherrypy/lib/filter/gzipfilter.py @@ -35,25 +35,26 @@ class GzipFilter(BaseFilter): """Filter that gzips the response.""" def beforeFinalize(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg - from cherrypy import cpg - if not cpg.config.get('gzipFilter.on', False): + global cherrypy + import cherrypy + + if not cherrypy.config.get('gzipFilter.on', False): return - if not cpg.response.body: + if not cherrypy.response.body: # Response body is empty (might be a 304 for instance) return - ct = cpg.response.headerMap.get('Content-Type').split(';')[0] - ae = cpg.request.headerMap.get('Accept-Encoding', '') - if (ct in cpg.config.get('gzipFilter.mimeTypeList', ['text/html']) + ct = cherrypy.response.headerMap.get('Content-Type').split(';')[0] + ae = cherrypy.request.headerMap.get('Accept-Encoding', '') + if (ct in cherrypy.config.get('gzipFilter.mimeTypeList', ['text/html']) and ('gzip' in ae)): - cpg.response.headerMap['Content-Encoding'] = 'gzip' + cherrypy.response.headerMap['Content-Encoding'] = 'gzip' # Return a generator that compresses the page - level = cpg.config.get('gzipFilter.compresslevel', 9) - cpg.response.body = self.zip_body(cpg.response.body, level) + level = cherrypy.config.get('gzipFilter.compresslevel', 9) + cherrypy.response.body = self.zip_body(cherrypy.response.body, level) def write_gzip_header(self): """Adapted from the gzip.py standard module code""" diff --git a/cherrypy/lib/filter/logdebuginfofilter.py b/cherrypy/lib/filter/logdebuginfofilter.py index ccdb3324..ed6890de 100644 --- a/cherrypy/lib/filter/logdebuginfofilter.py +++ b/cherrypy/lib/filter/logdebuginfofilter.py @@ -35,55 +35,56 @@ except ImportError: from basefilter import BaseFilter + class LogDebugInfoFilter(BaseFilter): """Filter that adds debug information to the page""" def onStartResource(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg - from cherrypy import cpg + global cherrypy + import cherrypy def beforeMain(self): - cpg.request.startBuilTime = time.time() + cherrypy.request.startBuilTime = time.time() def beforeFinalize(self): - if cpg.config.get('server.environment') == 'development': + if cherrypy.config.get('server.environment') == 'development': # In "dev" environment, log everything by default defaultOn = True else: defaultOn = False - if not cpg.config.get('logDebugInfoFilter.on', defaultOn): + if not cherrypy.config.get('logDebugInfoFilter.on', defaultOn): return - mimelist = cpg.config.get('logDebugInfoFilter.mimeTypeList', ['text/html']) - ct = cpg.response.headerMap.get('Content-Type').split(';')[0] + mimelist = cherrypy.config.get('logDebugInfoFilter.mimeTypeList', ['text/html']) + ct = cherrypy.response.headerMap.get('Content-Type').split(';')[0] if ct in mimelist: - body = ''.join(cpg.response.body) + body = ''.join(cherrypy.response.body) debuginfo = '\n' - logAsComment = cpg.config.get('logDebugInfoFilter.logAsComment', False) + logAsComment = cherrypy.config.get('logDebugInfoFilter.logAsComment', False) if logAsComment: debuginfo += '<!-- ' else: debuginfo += "<br/><br/>" logList = [] - if cpg.config.get('logDebugInfoFilter.logBuildTime', True): + if cherrypy.config.get('logDebugInfoFilter.logBuildTime', True): logList.append("Build time: %.03fs" % ( - time.time() - cpg.request.startBuilTime)) + time.time() - cherrypy.request.startBuilTime)) - if cpg.config.get('logDebugInfoFilter.logPageSize', True): + if cherrypy.config.get('logDebugInfoFilter.logPageSize', True): logList.append("Page size: %.02fKB" % ( len(body)/float(1024))) ''' # this is not compatible with the session filter - if (cpg.config.get('logDebugInfoFilter.logSessionSize', True) - and cpg.config.get('session.storageType')): + if (cherrypy.config.get('logDebugInfoFilter.logSessionSize', True) + and cherrypy.config.get('session.storageType')): # Pickle session data to get its size try: - dumpStr = pickle.dumps(cpg.request.sessionMap, 1) + dumpStr = pickle.dumps(cherrypy.request.sessionMap, 1) logList.append("Session data size: %.02fKB" % (len(dumpStr) / float(1024))) except: @@ -94,4 +95,4 @@ class LogDebugInfoFilter(BaseFilter): if logAsComment: debuginfo += '-->' - cpg.response.body = [body, debuginfo] + cherrypy.response.body = [body, debuginfo] diff --git a/cherrypy/lib/filter/nsgmlsfilter.py b/cherrypy/lib/filter/nsgmlsfilter.py index 5f847ad2..72765c7b 100644 --- a/cherrypy/lib/filter/nsgmlsfilter.py +++ b/cherrypy/lib/filter/nsgmlsfilter.py @@ -29,40 +29,41 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os, cgi from basefilter import BaseFilter + class NsgmlsFilter(BaseFilter): """Filter that runs the response through Nsgmls. """ def beforeFinalize(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg - from cherrypy import cpg + global cherrypy + import cherrypy - if not cpg.config.get('nsgmlsFilter.on', False): + if not cherrypy.config.get('nsgmlsFilter.on', False): return # the tidy filter, by its very nature it's not generator friendly, # so we just collect the body and work with it. - originalBody = ''.join(cpg.response.body) - cpg.response.body = [originalBody] + originalBody = ''.join(cherrypy.response.body) + cherrypy.response.body = [originalBody] - fct = cpg.response.headerMap.get('Content-Type', '') + fct = cherrypy.response.headerMap.get('Content-Type', '') ct = fct.split(';')[0] encoding = '' i = fct.find('charset=') if i != -1: encoding = fct[i+8:] if ct == 'text/html': - tmpdir = cpg.config.get('nsgmlsFilter.tmpDir') + tmpdir = cherrypy.config.get('nsgmlsFilter.tmpDir') pageFile = os.path.join(tmpdir, 'page.html') errFile = os.path.join(tmpdir, 'nsgmls.err') f = open(pageFile, 'wb') f.write(originalBody) f.close() nsgmlsEncoding = encoding.replace('-', '') - nsgmlsPath = cpg.config.get('nsgmlsFilter.nsgmlsPath') - catalogPath = cpg.config.get('nsgmlsFilter.catalogPath') + nsgmlsPath = cherrypy.config.get('nsgmlsFilter.nsgmlsPath') + catalogPath = cherrypy.config.get('nsgmlsFilter.catalogPath') command = '%s -c%s -f%s -s -E10 %s' % ( nsgmlsPath, catalogPath, errFile, pageFile) command = command.replace('\\', '/') @@ -74,7 +75,7 @@ class NsgmlsFilter(BaseFilter): newErrList = [] for err in errList: ignore = False - for errIgn in cpg.config.get('nsgmlsFilter.errorsToIgnore', []): + for errIgn in cherrypy.config.get('nsgmlsFilter.errorsToIgnore', []): if err.find(errIgn) != -1: ignore = True break @@ -88,6 +89,6 @@ class NsgmlsFilter(BaseFilter): i += 1 newBody += "%03d - "%i + cgi.escape(line).replace('\t',' ').replace(' ',' ') + '<br />' - cpg.response.body = [newBody] + cherrypy.response.body = [newBody] diff --git a/cherrypy/lib/filter/sessionauthenticatefilter.py b/cherrypy/lib/filter/sessionauthenticatefilter.py index 3a10791b..cbc22856 100644 --- a/cherrypy/lib/filter/sessionauthenticatefilter.py +++ b/cherrypy/lib/filter/sessionauthenticatefilter.py @@ -28,6 +28,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from basefilter import BaseFilter + def defaultLoginScreen(fromPage, login = '', errorMsg = ''): return """ <html><body> @@ -52,40 +53,40 @@ class SessionAuthenticateFilter(BaseFilter): """ def beforeMain(self): - global cpg - from cherrypy import cpg + import cherrypy from cherrypy.lib import httptools - if not cpg.config.get('sessionAuthenticateFilter.on', False): + + if not cherrypy.config.get('sessionAuthenticateFilter.on', False): return - checkLoginAndPassword = cpg.config.get('sessionAuthenticateFilter.checkLoginAndPassword', defaultCheckLoginAndPassword) - loginScreen = cpg.config.get('sessionAuthenticateFilter.loginScreen', defaultLoginScreen) - notLoggedIn = cpg.config.get('sessionAuthenticateFilter.notLoggedIn') - loadUserByUsername = cpg.config.get('sessionAuthenticateFilter.loadUserByUsername') - sessionName = cpg.config.get('sessionAuthenticateFilter.sessionName', 'sessionMap') - sessionKey = cpg.config.get('sessionAuthenticateFilter.sessionKey', 'username') - sessionMap = getattr(cpg.sessions, sessionName) + checkLoginAndPassword = cherrypy.config.get('sessionAuthenticateFilter.checkLoginAndPassword', defaultCheckLoginAndPassword) + loginScreen = cherrypy.config.get('sessionAuthenticateFilter.loginScreen', defaultLoginScreen) + notLoggedIn = cherrypy.config.get('sessionAuthenticateFilter.notLoggedIn') + loadUserByUsername = cherrypy.config.get('sessionAuthenticateFilter.loadUserByUsername') + sessionName = cherrypy.config.get('sessionAuthenticateFilter.sessionName', 'sessionMap') + sessionKey = cherrypy.config.get('sessionAuthenticateFilter.sessionKey', 'username') + sessionMap = getattr(cherrypy.sessions, sessionName) - if cpg.request.path.endswith('loginScreen'): + if cherrypy.request.path.endswith('loginScreen'): return - elif cpg.request.path.endswith('doLogout'): + elif cherrypy.request.path.endswith('doLogout'): sessionMap[sessionKey] = None - cpg.threadData.user = None - fromPage = cpg.request.paramMap.get('fromPage') + cherrypy.threadData.user = None + fromPage = cherrypy.request.paramMap.get('fromPage') if fromPage is None: fromPage = '/' - cpg.response.body = httptools.redirect(fromPage) - elif cpg.request.path.endswith('doLogin'): - fromPage = cpg.request.paramMap['fromPage'] - login = cpg.request.paramMap['login'] - password = cpg.request.paramMap['password'] + cherrypy.response.body = httptools.redirect(fromPage) + elif cherrypy.request.path.endswith('doLogin'): + fromPage = cherrypy.request.paramMap['fromPage'] + login = cherrypy.request.paramMap['login'] + password = cherrypy.request.paramMap['password'] errorMsg = checkLoginAndPassword(login, password) if errorMsg: - cpg.response.body = loginScreen(fromPage, login = login, errorMsg = errorMsg) + cherrypy.response.body = loginScreen(fromPage, login = login, errorMsg = errorMsg) else: sessionMap[sessionKey] = login if not fromPage: fromPage = '/' - cpg.response.body = httptools.redirect(fromPage) + cherrypy.response.body = httptools.redirect(fromPage) return # Check if user is logged in @@ -94,11 +95,10 @@ class SessionAuthenticateFilter(BaseFilter): # is OK can handle it notLoggedIn() if not sessionMap.get(sessionKey): - cpg.response.body = loginScreen(cpg.request.browserUrl) + cherrypy.response.body = loginScreen(cherrypy.request.browserUrl) return # Everything is OK: user is logged in if loadUserByUsername: username = sessionMap[sessionKey] - cpg.threadData.user = loadUserByUsername(username) - + cherrypy.threadData.user = loadUserByUsername(username) diff --git a/cherrypy/lib/filter/sessionfilter/__init__.py b/cherrypy/lib/filter/sessionfilter/__init__.py index 8b137891..9a20650b 100644 --- a/cherrypy/lib/filter/sessionfilter/__init__.py +++ b/cherrypy/lib/filter/sessionfilter/__init__.py @@ -1 +1,154 @@ +import time +import cherrypy + +import sessionconfig +from sessionerrors import SessionNotFoundError, SessionIncompatibleError +from ramsession import RamSession +from filesession import FileSession +from dbmsession import DBMSession + +_sessionTypes = { + 'ram' : RamSession, + 'file' : FileSession, + 'anydb' : DBMSession + } + +try: + # the user might not have sqlobject instaled + from sqlobjectsession import SQLObjectSession + _sessionTypes['sqlobject'] = SQLObjectSession +except ImportError: + pass + + +def _getSessions3(): + sessions = {} + + sessionLists = cherrypy.config.getAll('sessionFilter.sessionList') + + for sessionPath, sessionList in sessionLists.iteritems(): + if not isinstance(sessionList,list): + sessionList=[sessionList] + + for index in xrange(len(sessionList)): + session = sessionList[index] + + if isinstance(session, str): + sessionName = session + # check if the session is on or off + if not cherrypy.config.get('sessionFilter.%s.on' % sessionName, True): + continue + + storageType = sessionconfig.retrieve('storageType', sessionName) + + sessionManager = _sessionTypes[storageType](sessionName) + sessionManager.path = sessionPath + sessionManager.lastCleanUp = time.time() + + sessionList[index] = sessionManager + + cherrypy.config.update({sessionPath: {'sessionFilter.sessionList' : sessionList} }) + else: + sessionManager = session + + sessions[sessionManager.sessionName] = sessionManager + + return sessions + +_getSessions2 = _getSessions3 + + +class SessionFilter: + """ + Input filter - get the sessionId (or generate a new one) and load up the session data + """ + + def __initSessions(self): + sessions = _getSessions2() +# sessions = _getSessions() + sessionKeys = self.getSessionKeys() + + for sessionName in sessions: + sessionManager = sessions[sessionName] + sessionKey = sessionKeys.get(sessionName, None) + + try: + sessionManager.loadSession(sessionKey) + except SessionNotFoundError: + newKey = sessionManager.createSession() + sessionManager.loadSession(newKey) + + self.setSessionKey(newKey, sessionManager) + + def getSessionKeys(self): + """ + Returns the all current sessionkeys as a dict + """ + sessionKeys = {} + sessions = _getSessions2() + for sessionName in sessions: + sessionManager = sessions[sessionName] + + cookiePrefix = sessionconfig.retrieve('cookiePrefix', sessionName, None) + cookieName = '%s_%s_%i' % (cookiePrefix, sessionName, hash(sessionManager)) + + try: + sessionKeys[sessionName] = cherrypy.request.simpleCookie[cookieName].value + except: + sessionKeys[sessionName] = None + return sessionKeys + + def setSessionKey(self, sessionKey, sessionManager): + """ + Sets the session key in a cookie. Aplications should not call this function, + but it might be usefull to redefine it. + """ + + sessionName = sessionManager.sessionName + + cookiePrefix = sessionconfig.retrieve('cookiePrefix', sessionName, None) + cookieName = '%s_%s_%i' % (cookiePrefix, sessionName, hash(sessionManager)) + + cherrypy.response.simpleCookie[cookieName] = sessionKey + cherrypy.response.simpleCookie[cookieName]['version'] = 1 + + cookiePath = sessionconfig.retrieve('cookiePath', sessionManager.sessionName, sessionManager.path) + + cherrypy.response.simpleCookie[cookieName]['path'] = cookiePath + + def __saveSessions(self): + #sessions = _getSessions() + sessions = _getSessions2() + + for sessionName in sessions: + sessionManager = sessions[sessionName] + sessionData = getattr(cherrypy.sessions, sessionName) + sessionManager.commitCache(sessionData.key) + sessionManager.cleanUpCache() + + sessionManager.lastCleanUp = time.time() + + cleanUpDelay = sessionconfig.retrieve('cleanUpDelay', sessionManager.sessionName) + now = time.time() + lastCleanUp = sessionManager.lastCleanUp + if lastCleanUp + cleanUpDelay * 60 <= now: + sessionManager.cleanUpOldSessions() + + def beforeMain(self): + if (not cherrypy.config.get('staticFilter.on', False) + and cherrypy.config.get('sessionFilter.on')): + self.__initSessions() + + def beforeFinalize(self): + if (not cherrypy.config.get('staticFilter.on', False) + and cherrypy.config.get('sessionFilter.on')): + self.__saveSessions() + + ''' + #this breaks a test case + def beforeErrorResponse(self): + # Still save session data + if not cherrypy.config.get('staticFilter.on', False) and \ + cherrypy.config.get('sessionFilter.on'): + ''' diff --git a/cherrypy/lib/filter/sessionfilter/basesession.py b/cherrypy/lib/filter/sessionfilter/basesession.py index 8b7f25d1..2538c6b2 100644 --- a/cherrypy/lib/filter/sessionfilter/basesession.py +++ b/cherrypy/lib/filter/sessionfilter/basesession.py @@ -26,52 +26,56 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -import cherrypy.cpg - -import cherrypy._cputil, cherrypy.cperror import random, time, sha, string -from simplesessiondict import SimpleSessionDict +import cherrypy +from cherrypy.lib.filter.sessionfilter.simplesessiondict import SimpleSessionDict +from cherrypy.lib.filter.sessionfilter import sessionconfig -import sessionconfig class BaseSession(object): """ This is the class from which all session storage types are derived. The functions which need to be redefined are at the end of the file """ - + # by default don't use session caching noCache = True - + # these are the functions that need to rewritten def delSession(self, sessionKey): """ delete a session from storage """ - + pass + def getSession(self, sessionKey): """ function to lookup the session """ + pass def setSession(self, sessionData): """ function to save sesion data """ - + pass + def cleanUpOldSessions(self): """This function cleans up expired sessions""" - + pass + def newSession(self): """ Return a new sessiondict instance """ - + pass + # it might be usefull to redefine this function def generateSessionKey(self): """ Function to return a new sessioId """ sessionKeyFunc = sessionconfig.retrieve('keyGenerator', self.sessionName, None) if sessionKeyFunc: - newKey = cherrypy._cputil.getSpecialAttribute(sessionKeyFunc)() + from cherrypy import _cputil + newKey = _cputil.getSpecialAttribute(sessionKeyFunc)() else: newKey = sha.new('%s%s' % (time.time(), random.random())).hexdigest() return newKey - + def __init__(self, sessionName): """ Create the session caceh and set the session name. Make if you write @@ -81,8 +85,8 @@ class BaseSession(object): self.__sessionCache = {} self.sessionName = sessionName - - + + # there should never be a reason to modify the remaining functions, they used # internally by the sessionFilter @@ -95,8 +99,6 @@ class BaseSession(object): } def loadSession(self, sessionKey, autoCreate = True): - cpg = cherrypy.cpg - try: # look for the session in the cache session = self.__sessionCache[sessionKey] @@ -107,14 +109,14 @@ class BaseSession(object): session.threadCount += 1 self.__sessionCache[sessionKey] = session - setattr(cpg.sessions, self.sessionName, session) - + setattr(cherrypy.sessions, self.sessionName, session) + def createSession(self): """ returns a session key """ session = self.newSession() self.setSession(session) return session.key - + def commitCache(self, sessionKey): """ commit a session to persistand storage """ diff --git a/cherrypy/lib/filter/sessionfilter/basesessiondict.py b/cherrypy/lib/filter/sessionfilter/basesessiondict.py index 47dcd995..5154ed89 100644 --- a/cherrypy/lib/filter/sessionfilter/basesessiondict.py +++ b/cherrypy/lib/filter/sessionfilter/basesessiondict.py @@ -26,10 +26,9 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -import cherrypy.cpg import time +from cherrypy.lib.filter.sessionfilter.sessionerrors import SessionImmutableError -from sessionerrors import SessionImmutableError def locker(function): def _inner(self, *args, **kwds): @@ -43,7 +42,7 @@ def locker(function): # this class is used by class BaseSessionDict(object): """ - cpg.request.sessionMap is a SessionDict instance. + cherrypy.request.sessionMap is a SessionDict instance. SessionDict isntances alwasy contain the following attributes. diff --git a/cherrypy/lib/filter/sessionfilter/dbmsession.py b/cherrypy/lib/filter/sessionfilter/dbmsession.py index cfcc6610..f8109fff 100644 --- a/cherrypy/lib/filter/sessionfilter/dbmsession.py +++ b/cherrypy/lib/filter/sessionfilter/dbmsession.py @@ -26,32 +26,30 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from basesession import BaseSession -import cherrypy.cpg - import shelve +import cherrypy +from basesession import BaseSession from sessionerrors import * from simplesessiondict import SimpleSessionDict import os.path + class DBMSession(BaseSession): - # it is ok to cache the sessoin data + # it is ok to cache the session data noCache = False def __init__(self, sessionName): - cpg = cherrypy.cpg - BaseSession.__init__(self, sessionName) - # we must make sure the db file is unique - defaultFile = '%s-%i.db' % (sessionName, hash(self)) - dbFilePrefix=cpg.config.get('sessionFilter.%s.dbFilePrefix' % sessionName, '') - - sessionFile = os.path.join(dbFilePrefix, defaultFile) - + # we must make sure the db file is unique + defaultFile = '%s-%i.db' % (sessionName, hash(self)) + dbFilePrefix = cherrypy.config.get('sessionFilter.%s.dbFilePrefix' + % sessionName, '') + + sessionFile = os.path.join(dbFilePrefix, defaultFile) self.__data = shelve.open(sessionFile, 'c') def newSession(self): diff --git a/cherrypy/lib/filter/sessionfilter/filesession.py b/cherrypy/lib/filter/sessionfilter/filesession.py index d1d2e608..b160753b 100644 --- a/cherrypy/lib/filter/sessionfilter/filesession.py +++ b/cherrypy/lib/filter/sessionfilter/filesession.py @@ -26,18 +26,16 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from basesession import BaseSession -import cherrypy.cpg import cPickle as pickle - +import threading import os.path -from sessionerrors import * import sessionconfig - -import threading +from basesession import BaseSession +from sessionerrors import * from simplesessiondict import SimpleSessionDict + class FileSession(BaseSession): # is ok to cache filesession data @@ -56,7 +54,7 @@ class FileSession(BaseSession): def getSession(self, sessionKey): if not sessionKey: raise SessionNotFoundError - + storageDir = sessionconfig.retrieve('storageFileDir', self.sessionName) fileName = '%s_%i-%s' % (self.sessionName, hash(self), sessionKey) filePath = os.path.join(storageDir, fileName) diff --git a/cherrypy/lib/filter/sessionfilter/ramsession.py b/cherrypy/lib/filter/sessionfilter/ramsession.py index 438b4dd5..8fd89103 100644 --- a/cherrypy/lib/filter/sessionfilter/ramsession.py +++ b/cherrypy/lib/filter/sessionfilter/ramsession.py @@ -27,11 +27,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from basesession import BaseSession -import cherrypy.cpg - from sessionerrors import * from simplesessiondict import SimpleSessionDict + class RamSession(BaseSession): def __init__(self, sessionName): diff --git a/cherrypy/lib/filter/sessionfilter/sessionconfig.py b/cherrypy/lib/filter/sessionfilter/sessionconfig.py index 0ee1d500..af3704c6 100644 --- a/cherrypy/lib/filter/sessionfilter/sessionconfig.py +++ b/cherrypy/lib/filter/sessionfilter/sessionconfig.py @@ -26,30 +26,14 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from ramsession import RamSession -from filesession import FileSession -from dbmsession import DBMSession - -_sessionTypes = { - 'ram' : RamSession, - 'file' : FileSession, - 'anydb' : DBMSession - } +import cherrypy -try: - # the user might not have sqlobject instaled - from sqlobjectsession import SQLObjectSession - _sessionTypes['sqlobject'] = SQLObjectSession -except ImportError: - pass - - -import cherrypy.cpg def retrieve(keyName, sessionName, default = None): - cpg = cherrypy.cpg missing = object() - value = cpg.config.get('sessionFilter.%s.%s' % (sessionName, keyName), missing) + value = cherrypy.config.get('sessionFilter.%s.%s' + % (sessionName, keyName), missing) if value is missing: - value = cpg.config.get('sessionFilter.default.%s' % keyName, default) + value = cherrypy.config.get('sessionFilter.default.%s' + % keyName, default) return value diff --git a/cherrypy/lib/filter/sessionfilter/sessionfilter.py b/cherrypy/lib/filter/sessionfilter/sessionfilter.py deleted file mode 100644 index 16c3b11f..00000000 --- a/cherrypy/lib/filter/sessionfilter/sessionfilter.py +++ /dev/null @@ -1,151 +0,0 @@ - -import cherrypy.cpg - -import time - -from sessionerrors import SessionNotFoundError, SessionIncompatibleError - -import sessionconfig -from cherrypy._cputil import getObjectTrail -def _getSessions3(): - cpg = cherrypy.cpg - sessions = {} - - sessionLists = cpg.config.getAll('sessionFilter.sessionList') - - for sessionPath, sessionList in sessionLists.iteritems(): - if not isinstance(sessionList,list): - sessionList=[sessionList] - for index in xrange(len(sessionList)): - session = sessionList[index] - - if isinstance(session, str): - sessionName = session - # check if the session is on or off - if not cpg.config.get('sessionFilter.%s.on' % sessionName, True): - continue - - storageType = sessionconfig.retrieve('storageType', sessionName) - - sessionManager = sessionconfig._sessionTypes[storageType](sessionName) - sessionManager.path = sessionPath - sessionManager.lastCleanUp = time.time() - - sessionList[index] = sessionManager - - cpg.config.update({sessionPath: {'sessionFilter.sessionList' : sessionList} }) - else: - sessionManager = session - - sessions[sessionManager.sessionName] = sessionManager - - return sessions - -_getSessions2 = _getSessions3 - -class SessionFilter: - """ - Input filter - get the sessionId (or generate a new one) and load up the session data - """ - - def __initSessions(self): - cpg = cherrypy.cpg - sessions = _getSessions2() -# sessions = _getSessions() - sessionKeys = self.getSessionKeys() - - for sessionName in sessions: - sessionManager = sessions[sessionName] - sessionKey = sessionKeys.get(sessionName, None) - try: - sessionManager.loadSession(sessionKey) - except SessionNotFoundError: - newKey = sessionManager.createSession() - sessionManager.loadSession(newKey) - - self.setSessionKey(newKey, sessionManager) - - def getSessionKeys(self): - """ - Returns the all current sessionkeys as a dict - """ - cpg = cherrypy.cpg - - sessionKeys= {} - sessions = _getSessions2() - for sessionName in sessions: - sessionManager = sessions[sessionName] - - cookiePrefix = sessionconfig.retrieve('cookiePrefix', sessionName, None) - - cookieName = '%s_%s_%i' % (cookiePrefix, sessionName, hash(sessionManager)) - - try: - sessionKeys[sessionName] = cpg.request.simpleCookie[cookieName].value - except: - sessionKeys[sessionName] = None - return sessionKeys - - - def setSessionKey(self, sessionKey, sessionManager): - """ - Sets the session key in a cookie. Aplications should not call this function, - but it might be usefull to redefine it. - """ - - cpg = cherrypy.cpg - - sessionName = sessionManager.sessionName - - cookiePrefix = sessionconfig.retrieve('cookiePrefix', sessionName, None) - - cookieName = '%s_%s_%i' % (cookiePrefix, sessionName, hash(sessionManager)) - - cpg.response.simpleCookie[cookieName] = sessionKey - cpg.response.simpleCookie[cookieName]['version'] = 1 - - cookiePath = sessionconfig.retrieve('cookiePath', sessionManager.sessionName, sessionManager.path) - - cpg.response.simpleCookie[cookieName]['path'] = cookiePath - - - def __saveSessions(self): - cpg = cherrypy.cpg - #sessions = _getSessions() - sessions = _getSessions2() - - for sessionName in sessions: - sessionManager = sessions[sessionName] - sessionData = getattr(cpg.sessions, sessionName) - sessionManager.commitCache(sessionData.key) - sessionManager.cleanUpCache() - - sessionManager.lastCleanUp = time.time() - - cleanUpDelay = sessionconfig.retrieve('cleanUpDelay', sessionManager.sessionName) - now = time.time() - lastCleanUp = sessionManager.lastCleanUp - if lastCleanUp + cleanUpDelay * 60 <= now: - sessionManager.cleanUpOldSessions() - - - def beforeMain(self): - cpg = cherrypy.cpg - if not cpg.config.get('staticFilter.on', False) and \ - cpg.config.get('sessionFilter.on'): - self.__initSessions() - - def beforeFinalize(self): - cpg = cherrypy.cpg - if not cpg.config.get('staticFilter.on', False) and \ - cpg.config.get('sessionFilter.on'): - self.__saveSessions() - - ''' - #this breaks a test case - def beforeErrorResponse(self): - cpg = cherrypy.cpg - # Still save session data - if not cpg.config.get('staticFilter.on', False) and \ - cpg.config.get('sessionFilter.on'): - ''' diff --git a/cherrypy/lib/filter/sessionfilter/sqlobjectsession.py b/cherrypy/lib/filter/sessionfilter/sqlobjectsession.py index eccc47f8..1245d33d 100644 --- a/cherrypy/lib/filter/sessionfilter/sqlobjectsession.py +++ b/cherrypy/lib/filter/sessionfilter/sqlobjectsession.py @@ -25,14 +25,16 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from basesession import BaseSession -import cherrypy.cpg +import cherrypy +from cherrypy import _cputil +from basesession import BaseSession from sessionerrors import * from sqlobject import * from basesessiondict import BaseSessionDict + class SQLObjectSessionDict(BaseSessionDict): # it is ok to cache the session data @@ -69,7 +71,7 @@ class SQLObjectSessionDict(BaseSessionDict): return getattr(self.__sqlObject, key) except AttributeError: raise KeyError - + def __setitem__(self, key, value): # make shure it is not an attribute if key in ['timestamp', 'timeout', 'lastAccess', 'key']: @@ -78,25 +80,24 @@ class SQLObjectSessionDict(BaseSessionDict): return setattr(self.__sqlObject, key, value) except AttributeError: return KeyError - + def __str__(self): return str(self.__sqlObject) - + + class SQLObjectSession(BaseSession): def __init__(self, sessionName): BaseSession.__init__(self, sessionName) - dbClassName = cherrypy.cpg.config.get('%s.dbClassName' % sessionName) - self.Session = cherrypy._cputil.getSpecialAttribute(dbClassName) + dbClassName = cherrypy.config.get('%s.dbClassName' % sessionName) + self.Session = _cputil.getSpecialAttribute(dbClassName) def newSession(self): """ Return a new sessionMap instance """ - newSession = self.Session(session_key = self.generateSessionKey()) return SQLObjectSessionDict(newSession) - def getSession(self, sessionKey): resultList = list(self.Session.select(self.Session.q.session_key == sessionKey)) diff --git a/cherrypy/lib/filter/staticfilter.py b/cherrypy/lib/filter/staticfilter.py index 2e193cae..838f95f3 100644 --- a/cherrypy/lib/filter/staticfilter.py +++ b/cherrypy/lib/filter/staticfilter.py @@ -34,16 +34,17 @@ class StaticFilter(BaseFilter): """Filter that handles static content.""" def beforeMain(self): - from cherrypy import cpg, _cphttptools + import cherrypy + from cherrypy import _cphttptools - if not cpg.config.get('staticFilter.on', False): + if not cherrypy.config.get('staticFilter.on', False): return - filename = cpg.config.get('staticFilter.file') + filename = cherrypy.config.get('staticFilter.file') if not filename: - staticDir = cpg.config.get('staticFilter.dir') - section = cpg.config.get('staticFilter.dir', returnSection=True) - extraPath = cpg.request.path[len(section) + 1:] + staticDir = cherrypy.config.get('staticFilter.dir') + section = cherrypy.config.get('staticFilter.dir', returnSection=True) + extraPath = cherrypy.request.path[len(section) + 1:] filename = os.path.join(staticDir, extraPath) _cphttptools.serve_file(filename) diff --git a/cherrypy/lib/filter/tidyfilter.py b/cherrypy/lib/filter/tidyfilter.py index bdbe2fa2..0cea0381 100644 --- a/cherrypy/lib/filter/tidyfilter.py +++ b/cherrypy/lib/filter/tidyfilter.py @@ -29,6 +29,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os, cgi, StringIO, traceback from basefilter import BaseFilter + class TidyFilter(BaseFilter): """Filter that runs the response through Tidy. @@ -39,27 +40,24 @@ class TidyFilter(BaseFilter): """ def beforeFinalize(self): - # We have to dynamically import cpg because Python can't handle - # circular module imports :-( - global cpg - from cherrypy import cpg + import cherrypy - if not cpg.config.get('tidyFilter.on', False): + if not cherrypy.config.get('tidyFilter.on', False): return # the tidy filter, by its very nature it's not generator friendly, # so we just collect the body and work with it. - originalBody = ''.join(cpg.response.body) - cpg.response.body = [originalBody] + originalBody = ''.join(cherrypy.response.body) + cherrypy.response.body = [originalBody] - fct = cpg.response.headerMap.get('Content-Type', '') + fct = cherrypy.response.headerMap.get('Content-Type', '') ct = fct.split(';')[0] encoding = '' i = fct.find('charset=') if i != -1: encoding = fct[i+8:] if ct == 'text/html': - tmpdir = cpg.config.get('tidyFilter.tmpDir') + tmpdir = cherrypy.config.get('tidyFilter.tmpDir') pageFile = os.path.join(tmpdir, 'page.html') outFile = os.path.join(tmpdir, 'tidy.out') errFile = os.path.join(tmpdir, 'tidy.err') @@ -71,10 +69,10 @@ class TidyFilter(BaseFilter): tidyEncoding = '-' + tidyEncoding strictXml = "" - if cpg.config.get('tidyFilter.strictXml', False): + if cherrypy.config.get('tidyFilter.strictXml', False): strictXml = ' -xml' os.system('"%s" %s%s -f %s -o %s %s' % - (cpg.config.get('tidyFilter.tidyPath'), tidyEncoding, + (cherrypy.config.get('tidyFilter.tidyPath'), tidyEncoding, strictXml, errFile, outFile, pageFile)) f = open(errFile, 'rb') err = f.read() @@ -85,7 +83,7 @@ class TidyFilter(BaseFilter): for err in errList: if (err.find('Warning') != -1 or err.find('Error') != -1): ignore = 0 - for errIgn in cpg.config.get('encodingFilter.errorsToIgnore', []): + for errIgn in cherrypy.config.get('encodingFilter.errorsToIgnore', []): if err.find(errIgn) != -1: ignore = 1 break @@ -100,7 +98,7 @@ class TidyFilter(BaseFilter): i += 1 newBody += "%03d - "%i + cgi.escape(line).replace('\t',' ').replace(' ',' ') + '<br />' - cpg.response.body = [newBody] + cherrypy.response.body = [newBody] elif strictXml: # The HTML is OK, but is it valid XML @@ -120,7 +118,7 @@ class TidyFilter(BaseFilter): # Wrong XML bodyFile = StringIO.StringIO() traceback.print_exc(file = bodyFile) - cpg.response.body = [bodyFile.getvalue()] + cherrypy.response.body = [bodyFile.getvalue()] newBody = "Wrong XML:<br />" + cgi.escape(bodyFile.getvalue().replace('\n','<br />')) newBody += '<br /><br />' @@ -129,5 +127,5 @@ class TidyFilter(BaseFilter): i += 1 newBody += "%03d - "%i + cgi.escape(line).replace('\t',' ').replace(' ',' ') + '<br />' - cpg.response.body = [newBody] + cherrypy.response.body = [newBody] diff --git a/cherrypy/lib/filter/virtualhostfilter.py b/cherrypy/lib/filter/virtualhostfilter.py index fbd72d7f..e730b15c 100644 --- a/cherrypy/lib/filter/virtualhostfilter.py +++ b/cherrypy/lib/filter/virtualhostfilter.py @@ -36,18 +36,15 @@ class VirtualHostFilter(basefilter.BaseFilter): """ def beforeRequestBody(self): - # We have to dynamically import cpg because Python can't handle - # circular module imports :-( - global cpg, _cphttptools - from cherrypy import cpg, _cphttptools + import cherrypy + from cherrypy import _cphttptools - if not cpg.config.get('virtualHostFilter.on', False): + if not cherrypy.config.get('virtualHostFilter.on', False): return - domain = cpg.request.base.split('//')[1] + domain = cherrypy.request.base.split('//')[1] # Re-use "mapPathToObject" function to find the actual objectPath - prefix = cpg.config.get('virtualHostFilter.prefix', '/') - virtualPath = prefix + cpg.request.path + prefix = cherrypy.config.get('virtualHostFilter.prefix', '/') + virtualPath = prefix + cherrypy.request.path c, objectPathList, v = _cphttptools.mapPathToObject(virtualPath) - cpg.request.objectPath = '/' + '/'.join(objectPathList[1:]) - #raise basefilter.InternalRedirect + cherrypy.request.objectPath = '/' + '/'.join(objectPathList[1:]) diff --git a/cherrypy/lib/filter/xmlrpcfilter.py b/cherrypy/lib/filter/xmlrpcfilter.py index da0c2848..5ce61c50 100644 --- a/cherrypy/lib/filter/xmlrpcfilter.py +++ b/cherrypy/lib/filter/xmlrpcfilter.py @@ -44,7 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## NOTE: __don't try to return a Generator object to the caller__ ## You could of course handle the generator usage internally, before sending ## the result. This breaks from the general cherrypy way of handling generators... -## 0.0.8 : 2004-12-23 cpg.request.paramList should now be a filter. +## 0.0.8 : 2004-12-23 cherrypy.request.paramList should now be a filter. ## 0.0.7 : 2004-12-07 inserted in the experimental branch (all remco boerma till here) ## 0.0.6 : 2004-12-02 Converted basefilter to baseinputfileter,baseoutputfilter ## 0.0.5 : 2004-11-22 "RPC2/" now changed to "/RPC2/" with the new mapping function @@ -81,7 +81,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## EXAMPLE CODE FOR THE SERVER: ## from cherrypy.lib.filter.xmlrpcfilter import XmlRpcFilter -## from cherrypy import cpg +## from cherrypy import cherrypy ## ## class Root: ## _cpFilterList = [XmlRpcFilter()] @@ -90,9 +90,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## return s*times ## longString.exposed = True ## -## cpg.root = Root() +## cherrypy.root = Root() ## if __name__=='__main__': -## cpg.server.start(configMap = {'socketPort': 9001, +## cherrypy.server.start(configMap = {'socketPort': 9001, ## 'threadPool':0, ## 'socketQueueSize':10 }) ## EXAMPLE CODE FOR THE CLIENT: @@ -105,6 +105,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from basefilter import BaseFilter import xmlrpclib + class XmlRpcFilter(BaseFilter): """Converts XMLRPC to CherryPy2 object system and vice-versa. @@ -112,12 +113,12 @@ class XmlRpcFilter(BaseFilter): beforeRequestBody: Unmarshalls the posted data to a methodname and parameters. - - These are stored in cpg.request.rpcMethod and .rpcParams - - The method is also stored in cpg.request.path, so CP2 will find + - These are stored in cherrypy.request.rpcMethod and .rpcParams + - The method is also stored in cherrypy.request.path, so CP2 will find the right method to call for you, based on the root's position. beforeFinalize: - Marshalls cpg.response.body to xmlrpc. - - Until resolved: cpg.response.body must be a python source string; + Marshalls cherrypy.response.body to xmlrpc. + - Until resolved: cherrypy.response.body must be a python source string; this string is 'eval'ed to return the results. This will be resolved in the future. - Content-Type and Content-Length are set according to the new @@ -126,66 +127,67 @@ class XmlRpcFilter(BaseFilter): def testValidityOfRequest(self): # test if the content-length was sent - result = int(cpg.request.headerMap.get('Content-Length',0)) > 0 - ct = cpg.request.headerMap.get('Content-Type', 'text/xml').lower() + result = int(cherrypy.request.headerMap.get('Content-Length',0)) > 0 + ct = cherrypy.request.headerMap.get('Content-Type', 'text/xml').lower() result = result and ct in ['text/xml'] return result def onStartResource(self): - # We have to dynamically import cpg because Python can't handle + # We have to dynamically import cherrypy because Python can't handle # circular module imports :-( - global cpg - from cherrypy import cpg + global cherrypy + import cherrypy def beforeRequestBody(self): """ Called after the request header has been read/parsed""" - cpg.threadData.xmlRpcFilterOn = cpg.config.get('xmlRpcFilter.on', False) - if not cpg.threadData.xmlRpcFilterOn: + cherrypy.threadData.xmlRpcFilterOn = cherrypy.config.get('xmlRpcFilter.on', False) + if not cherrypy.threadData.xmlRpcFilterOn: return True - cpg.request.isRPC = self.testValidityOfRequest() - if not cpg.request.isRPC: + cherrypy.request.isRPC = self.testValidityOfRequest() + if not cherrypy.request.isRPC: # used for debugging or more info # print 'not a valid xmlrpc call' return # break this if it's not for this filter!! # used for debugging, or more info: # print "xmlrpcmethod...", - cpg.request.processRequestBody = False - dataLength = int(cpg.request.headerMap.get('Content-Length', 0)) - data = cpg.request.rfile.read(dataLength) + cherrypy.request.processRequestBody = False + dataLength = int(cherrypy.request.headerMap.get('Content-Length', 0)) + data = cherrypy.request.rfile.read(dataLength) try: params, method = xmlrpclib.loads(data) except Exception: params, method = ('ERROR PARAMS', ), 'ERRORMETHOD' - cpg.request.rpcMethod, cpg.request.rpcParams = method, params + cherrypy.request.rpcMethod, cherrypy.request.rpcParams = method, params # patch the path. there are only a few options: # - 'RPC2' + method >> method # - 'someurl' + method >> someurl.method # - 'someurl/someother' + method >> someurl.someother.method - if not cpg.request.path.endswith('/'): - cpg.request.path += '/' - if cpg.request.path.startswith('/RPC2/'): - cpg.request.path=cpg.request.path[5:] ## strip the first /rpc2 - cpg.request.path += str(method).replace('.', '/') - cpg.request.paramList = list(params) + if not cherrypy.request.path.endswith('/'): + cherrypy.request.path += '/' + if cherrypy.request.path.startswith('/RPC2/'): + cherrypy.request.path=cherrypy.request.path[5:] ## strip the first /rpc2 + cherrypy.request.path += str(method).replace('.', '/') + cherrypy.request.paramList = list(params) # used for debugging and more info - # print "XMLRPC Filter: calling '%s' with args: '%s' " % (cpg.request.path,params) + # print "XMLRPC Filter: calling '%s' with args: '%s' " % (cherrypy.request.path,params) def beforeFinalize(self): """ Called before finalizing output """ - if (not cpg.threadData.xmlRpcFilterOn) or (not cpg.request.isRPC): + if (not cherrypy.threadData.xmlRpcFilterOn + or not cherrypy.request.isRPC): return - cpg.response.body = [xmlrpclib.dumps( - (cpg.response.body[0],), methodresponse=1, allow_none=1)] - cpg.response.headerMap['Content-Type'] = 'text/xml' - cpg.response.headerMap['Content-Length'] = `len(cpg.response.body[0])` + cherrypy.response.body = [xmlrpclib.dumps( + (cherrypy.response.body[0],), methodresponse=1, allow_none=1)] + cherrypy.response.headerMap['Content-Type'] = 'text/xml' + cherrypy.response.headerMap['Content-Length'] = `len(cherrypy.response.body[0])` def beforeErrorResponse(self): try: - if not cpg.threadData.xmlRpcFilterOn: + if not cherrypy.threadData.xmlRpcFilterOn: return - cpg.response.body = [xmlrpclib.dumps( - xmlrpclib.Fault(1, ''.join(cpg.response.body)))] + cherrypy.response.body = [xmlrpclib.dumps( + xmlrpclib.Fault(1, ''.join(cherrypy.response.body)))] except: pass diff --git a/cherrypy/lib/form.py b/cherrypy/lib/form.py index 080cdd4c..5d9ba90c 100644 --- a/cherrypy/lib/form.py +++ b/cherrypy/lib/form.py @@ -30,95 +30,127 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Simple form handling module. """ -from cherrypy import cpg +import cherrypy import defaultformmask + class FormField: - def __init__(self, label, name, typ, mask=None, mandatory=0, size=15, optionList=[], defaultValue='', defaultMessage='', validate=None): - self.isField=1 - self.label=label - self.name=name - self.typ=typ - if not mask: self.mask=defaultformmask.defaultMask - else: self.mask=mask - self.mandatory=mandatory - self.size=size - self.optionList=optionList - self.defaultValue=defaultValue - self.defaultMessage=defaultMessage - self.validate=validate - self.errorMessage="" + + def __init__(self, label, name, typ, mask=None, mandatory=0, size=15, + optionList=[], defaultValue='', defaultMessage='', validate=None): + self.isField = 1 + self.label = label + self.name = name + self.typ = typ + if mask is None: + self.mask = defaultformmask.defaultMask + else: + self.mask = mask + self.mandatory = mandatory + self.size = size + self.optionList = optionList + self.defaultValue = defaultValue + self.defaultMessage = defaultMessage + self.validate = validate + self.errorMessage = "" + def render(self, leaveValues): if leaveValues: - if self.typ!='submit': - if cpg.request.paramMap.has_key(self.name): self.currentValue=cpg.request.paramMap[self.name] - else: self.currentValue="" - else: self.currentValue=self.defaultValue + if self.typ !='submit': + self.currentValue = cherrypy.request.paramMap.get(self.name, "") + else: + self.currentValue = self.defaultValue else: - self.currentValue=self.defaultValue - self.errorMessage=self.defaultMessage + self.currentValue = self.defaultValue + self.errorMessage = self.defaultMessage return self.mask(self) + class FormSeparator: + def __init__(self, label, mask): - self.isField=0 - self.label=label - self.mask=mask + self.isField = 0 + self.label = label + self.mask = mask + def render(self, dummy): return self.mask(self.label) + class Form: - method="post" - enctype="" + + method = "post" + enctype = "" + def formView(self, leaveValues=0): - if self.enctype: enctypeTag='enctype="%s"'%self.enctype - else: enctypeTag="" - res='<form method="%s" %s action="postForm">'%(self.method, enctypeTag) + if self.enctype: + enctypeTag = 'enctype="%s"' % self.enctype + else: + enctypeTag = "" + + res = ['<form method="%s" %s action="postForm">' + % (self.method, enctypeTag)] for field in self.fieldList: - res+=field.render(leaveValues) - return res+"</form>" + res.append(field.render(leaveValues)) + res.append["</form>"] + + return "".join(res) + def validateFields(self): # Should be subclassed # Update field's errorMessage value to set an error pass + def validateForm(self): # Reset errorMesage for each field for field in self.fieldList: - if field.isField: field.errorMessage="" - + if field.isField: + field.errorMessage = "" + # Validate mandatory fields for field in self.fieldList: - if field.isField and field.mandatory and (not cpg.request.paramMap.has_key(field.name) or not cpg.request.paramMap[field.name]): field.errorMessage="Missing" - + if (field.isField and field.mandatory + and not cherrypy.request.paramMap.get(field.name)): + field.errorMessage = "Missing" + # Validate fields one by one for field in self.fieldList: if field.isField and field.validate and not field.errorMessage: - if cpg.request.paramMap.has_key(field.name): value=cpg.request.paramMap[field.name] - else: value="" - field.errorMessage=field.validate(value) + value = cherrypy.request.paramMap.get(field.name, "") + field.errorMessage = field.validate(value) # Validate all fields together (ie: check that passwords match) self.validateFields() for field in self.fieldList: - if field.isField and field.errorMessage: return 0 + if field.isField and field.errorMessage: + return 0 return 1 + def setFieldErrorMessage(self, fieldName, errorMessage): for field in self.fieldList: - if field.isField and field.name==fieldName: field.errorMessage=errorMessage + if field.isField and field.name == fieldName: + field.errorMessage = errorMessage + def getFieldOptionList(self, fieldName): for field in self.fieldList: - if field.isField and field.name==fieldName: return field.optionList + if field.isField and field.name == fieldName: + return field.optionList + def getFieldDefaultValue(self, fieldName): for field in self.fieldList: - if field.isField and field.name==fieldName: return field.defaultValue + if field.isField and field.name == fieldName: + return field.defaultValue + def setFieldDefaultValue(self, fieldName, defaultValue): for field in self.fieldList: - if field.isField and field.name==fieldName: field.defaultValue=defaultValue - + if field.isField and field.name == fieldName: + field.defaultValue = defaultValue + def getFieldNameList(self, exceptList=[]): - fieldNameList=[] + fieldNameList = [] for field in self.fieldList: - if field.isField and field.name and field.name not in exceptList: fieldNameList.append(field.name) + if field.isField and field.name and field.name not in exceptList: + fieldNameList.append(field.name) return fieldNameList diff --git a/cherrypy/lib/httptools.py b/cherrypy/lib/httptools.py index afa7f1c7..936981b2 100644 --- a/cherrypy/lib/httptools.py +++ b/cherrypy/lib/httptools.py @@ -30,15 +30,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Just a few convenient functions """ -from cherrypy import cpg +import cherrypy import urlparse def canonicalizeUrl(url): """ Canonicalize a URL. The URL might be relative, absolute or canonical """ - return urlparse.urljoin(cpg.request.browserUrl, url) + return urlparse.urljoin(cherrypy.request.browserUrl, url) def redirect(url): """ Sends a redirect to the browser (after canonicalizing the URL) """ - cpg.response.status = "302 Found" - cpg.response.headerMap['Location'] = canonicalizeUrl(url) + cherrypy.response.status = "302 Found" + cherrypy.response.headerMap['Location'] = canonicalizeUrl(url) return "" diff --git a/cherrypy/lib/profiler.py b/cherrypy/lib/profiler.py index 0274fa18..0f56395f 100644 --- a/cherrypy/lib/profiler.py +++ b/cherrypy/lib/profiler.py @@ -45,7 +45,7 @@ You can profile any of your pages as follows: def _index(self): return "Hello, world!" - cpg.root = Root() + cherrypy.root = Root() CherryPy developers @@ -130,22 +130,22 @@ class Profiler(object): menu.exposed = True def report(self, filename): - from cherrypy import cpg - cpg.response.headerMap['Content-Type'] = 'text/plain' + import cherrypy + cherrypy.response.headerMap['Content-Type'] = 'text/plain' return self.stats(filename) report.exposed = True def serve(path=None, port=8080): - from cherrypy import cpg - cpg.root = Profiler(path) - cpg.config.update({'global': {'server.serverPort': port, - 'server.threadPool': 10, - 'server.environment': "production", - 'session.storageType': "ram", - } - }) - cpg.server.start() + import cherrypy + cherrypy.root = Profiler(path) + cherrypy.config.update({'global': {'server.serverPort': port, + 'server.threadPool': 10, + 'server.environment': "production", + 'session.storageType': "ram", + } + }) + cherrypy.server.start() if __name__ == "__main__": diff --git a/cherrypy/_cpserver.py b/cherrypy/server.py index ab433a57..d820c1e4 100644 --- a/cherrypy/_cpserver.py +++ b/cherrypy/server.py @@ -34,15 +34,15 @@ Main CherryPy module: import threading import time import sys -import cpg, _cphttptools + +import cherrypy +from cherrypy import _cphttptools +from cherrypy.lib import autoreload, profiler try: from threading import local except ImportError: - from _cpthreadinglocal import local - - -from lib import autoreload, profiler + from cherrypy._cpthreadinglocal import local # Set some special attributes for adding hooks @@ -52,7 +52,7 @@ onStopServerList = [] onStopThreadList = [] def start(initOnly=False, serverClass=None): - if cpg.config.get("server.environment") == "development": + if cherrypy.config.get("server.environment") == "development": # Check initOnly. If True, we're probably not starting # our own webserver, and therefore could do Very Bad Things # when autoreload calls sys.exit. @@ -72,44 +72,44 @@ def _start(initOnly=False, serverClass=None): # Create request and response object (the same objects will be used # throughout the entire life of the webserver) - cpg.request = local() - cpg.response = local() + cherrypy.request = local() + cherrypy.response = local() # Create as sessions object for accessing session data - cpg.sessions = local() + cherrypy.sessions = local() # Create threadData object as a thread-specific all-purpose storage - cpg.threadData = local() + cherrypy.threadData = local() # Output config options to log - if cpg.config.get("server.logConfigOptions", True): - cpg.config.outputConfigMap() + if cherrypy.config.get("server.logConfigOptions", True): + cherrypy.config.outputConfigMap() # Check the config options # TODO - # _cpconfig.checkConfigOptions() + # config.checkConfigOptions() # Initialize a few global variables - cpg._lastCacheFlushTime = time.time() - cpg._lastSessionCleanUpTime = time.time() - cpg._sessionMap = {} # Map of "cookie" -> ("session object", "expiration time") + cherrypy._lastCacheFlushTime = time.time() + cherrypy._lastSessionCleanUpTime = time.time() + cherrypy._sessionMap = {} # Map of "cookie" -> ("session object", "expiration time") # If sessions are stored in files and we # use threading, we need a lock on the file - if (cpg.config.get('server.threadPool') > 1 - and cpg.config.get('session.storageType') == 'file'): - cpg._sessionFileLock = threading.RLock() + if (cherrypy.config.get('server.threadPool') > 1 + and cherrypy.config.get('session.storageType') == 'file'): + cherrypy._sessionFileLock = threading.RLock() - # Call the functions from cpg.server.onStartServerList - for func in cpg.server.onStartServerList: + # Call the functions from cherrypy.server.onStartServerList + for func in cherrypy.server.onStartServerList: func() # Set up the profiler if requested. - if cpg.config.get("profiling.on", False): - ppath = cpg.config.get("profiling.path", "") - cpg.profiler = profiler.Profiler(ppath) + if cherrypy.config.get("profiling.on", False): + ppath = cherrypy.config.get("profiling.path", "") + cherrypy.profiler = profiler.Profiler(ppath) else: - cpg.profiler = None + cherrypy.profiler = None if not initOnly: run_server(serverClass) @@ -119,27 +119,27 @@ def run_server(serverClass=None): # Instantiate the server. if serverClass is None: - serverClass = cpg.config.get("server.class", None) + serverClass = cherrypy.config.get("server.class", None) if serverClass and isinstance(serverClass, basestring): serverClass = attributes(serverClass) if serverClass is None: import _cpwsgi serverClass = _cpwsgi.WSGIServer - cpg._httpserver = serverClass() + cherrypy._httpserver = serverClass() - if cpg.config.get('server', 'socketPort'): - onWhat = "socket: ('%s', %s)" % (cpg.config.get('server.socketHost'), - cpg.config.get('server.socketPort')) + if cherrypy.config.get('server', 'socketPort'): + onWhat = "socket: ('%s', %s)" % (cherrypy.config.get('server.socketHost'), + cherrypy.config.get('server.socketPort')) else: - onWhat = "socket file: %s" % cpg.config.get('server.socketFile') - cpg.log("Serving HTTP on %s" % onWhat, 'HTTP') + onWhat = "socket file: %s" % cherrypy.config.get('server.socketFile') + cherrypy.log("Serving HTTP on %s" % onWhat, 'HTTP') # Start the http server. try: - cpg._httpserver.start() + cherrypy._httpserver.start() except (KeyboardInterrupt, SystemExit): - cpg.log("<Ctrl-C> hit: shutting down", "HTTP") + cherrypy.log("<Ctrl-C> hit: shutting down", "HTTP") stop() def modules(modulePath): @@ -180,12 +180,12 @@ def request(clientAddress, remoteHost, requestLine, headers, rfile): if threadID not in seen_threads: i = len(seen_threads) + 1 seen_threads[threadID] = i - # Call the functions from cpg.server.onStartThreadList - for func in cpg.server.onStartThreadList: + # Call the functions from cherrypy.server.onStartThreadList + for func in cherrypy.server.onStartThreadList: func(i) - if cpg.profiler: - cpg.profiler.run(_cphttptools.Request, clientAddress, remoteHost, + if cherrypy.profiler: + cherrypy.profiler.run(_cphttptools.Request, clientAddress, remoteHost, requestLine, headers, rfile) else: _cphttptools.Request(clientAddress, remoteHost, @@ -194,18 +194,18 @@ def request(clientAddress, remoteHost, requestLine, headers, rfile): def stop(): """Shutdown CherryPy (and any HTTP servers it started).""" try: - httpstop = cpg._httpserver.stop + httpstop = cherrypy._httpserver.stop except AttributeError: pass else: httpstop() - # Call the functions from cpg.server.onStopThreadList + # Call the functions from cherrypy.server.onStopThreadList for thread_ident, i in seen_threads.iteritems(): - for func in cpg.server.onStopThreadList: + for func in cherrypy.server.onStopThreadList: func(i) seen_threads.clear() - # Call the functions from cpg.server.onStopServerList - for func in cpg.server.onStopServerList: + # Call the functions from cherrypy.server.onStopServerList + for func in cherrypy.server.onStopServerList: func() diff --git a/cherrypy/test/helper.py b/cherrypy/test/helper.py index 0ddeeb31..3bb05177 100644 --- a/cherrypy/test/helper.py +++ b/cherrypy/test/helper.py @@ -33,7 +33,8 @@ import socket import StringIO import httplib import threading -from cherrypy import cpg + +import cherrypy HOST = "127.0.0.1" @@ -51,19 +52,19 @@ def port_is_free(): def startServer(serverClass=None): if serverClass is None: - cpg.server.start(initOnly=True) + cherrypy.server.start(initOnly=True) else: if not port_is_free(): raise IOError("Port %s is in use; perhaps the previous server " "did not shut down properly." % PORT) - t = threading.Thread(target=cpg.server.start, args=(False, serverClass)) + t = threading.Thread(target=cherrypy.server.start, args=(False, serverClass)) t.start() time.sleep(1) def stopServer(): - cpg.server.stop() - if cpg.config.get('server.threadPool') > 1: + cherrypy.server.stop() + if cherrypy.config.get('server.threadPool') > 1: # With thread-pools, it can take up to 1 sec for the server to stop time.sleep(1.1) @@ -92,9 +93,9 @@ def getPage(url, headers=None, method="GET", body=None): # Improper response from server. print print "Server did not return a response." - print "status>", repr(cpg.response.status) - print "headers>", repr(cpg.response.headers) - print "body>", repr(cpg.response.body) + print "status>", repr(cherrypy.response.status) + print "headers>", repr(cherrypy.response.headers) + print "body>", repr(cherrypy.response.body) raise status = "%s %s" % (response.status, response.reason) @@ -131,7 +132,8 @@ def request(url, headers=None, method="GET", body=None): headers.append(("Content-type", "application/x-www-form-urlencoded")) headers.append(("Content-Length", str(len(body or "")))) - if cpg._httpserver is None: + resp = cherrypy.response + if cherrypy._httpserver is None: requestLine = "%s %s HTTP/1.0" % (method.upper(), url) found = False for k, v in headers: @@ -142,12 +144,10 @@ def request(url, headers=None, method="GET", body=None): headers.append(("Host", "%s:%s" % (HOST, PORT))) if body is not None: body = StringIO.StringIO(body) - cpg.server.request(HOST, HOST, requestLine, headers, body) - cpg.response.body = "".join(cpg.response.body) + cherrypy.server.request(HOST, HOST, requestLine, headers, body) + resp.body = "".join(resp.body) else: result = getPage(url, headers, method, body) - cpg.response.status, cpg.response.headerMap, cpg.response.body = result - cpg.response.headers = [(k, v) for k, v in - cpg.response.headerMap.iteritems()] - + resp.status, resp.headerMap, resp.body = result + resp.headers = [(k, v) for k, v in resp.headerMap.iteritems()] diff --git a/cherrypy/test/test.py b/cherrypy/test/test.py index 3835337f..f25df608 100644 --- a/cherrypy/test/test.py +++ b/cherrypy/test/test.py @@ -135,7 +135,7 @@ def main(): try: import cherrypy except ImportError: - print "Error: couln't find CherryPy !" + print "Error: couldn't find CherryPy !" os._exit(-1) print "CherryPy version", cherrypy.__version__ print @@ -154,8 +154,8 @@ def main(): 'test_virtualhost_filter', ] - from cherrypy import cpg - import helper + import cherrypy + from cherrypy.test import helper server_conf = {'server.socketHost': helper.HOST, 'server.socketPort': helper.PORT, @@ -172,13 +172,13 @@ def main(): print print "Running tests:", name - cpg.config.update({'global': server_conf.copy()}) + cherrypy.config.update({'global': server_conf.copy()}) helper.startServer(server) for testmod in testList: # Must run each module in a separate suite, - # because each module uses/overwrites cpg globals. - cpg.config.reset() - cpg.config.update({'global': server_conf.copy()}) + # because each module uses/overwrites cherrypy globals. + cherrypy.config.reset() + cherrypy.config.update({'global': server_conf.copy()}) suite = CPTestLoader.loadTestsFromName(testmod) CPTestRunner(verbosity=2).run(suite) helper.stopServer() diff --git a/cherrypy/test/test_baseurl_filter.py b/cherrypy/test/test_baseurl_filter.py index 47f66b76..1746d395 100644 --- a/cherrypy/test/test_baseurl_filter.py +++ b/cherrypy/test/test_baseurl_filter.py @@ -26,16 +26,17 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy from cherrypy.lib import httptools + class Root: def index(self): return httptools.redirect('dummy') index.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'server.environment': 'production', 'baseUrlFilter.on': True, @@ -50,11 +51,11 @@ class BaseUrlFilterTest(unittest.TestCase): def testBaseUrlFilter(self): helper.request("/") - self.assertEqual(cpg.response.headerMap['Location'], + self.assertEqual(cherrypy.response.headerMap['Location'], "http://www.mydomain.com/dummy") if __name__ == '__main__': - cpg.server.start(initOnly=True) + cherrypy.server.start(initOnly=True) unittest.main() diff --git a/cherrypy/test/test_cache_filter.py b/cherrypy/test/test_cache_filter.py index 6f2f13ef..d8a8b649 100644 --- a/cherrypy/test/test_cache_filter.py +++ b/cherrypy/test/test_cache_filter.py @@ -26,21 +26,22 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy import time + class Root: def __init__(self): - cpg.counter = 0 + cherrypy.counter = 0 def index(self): - counter = cpg.counter + 1 - cpg.counter = counter + counter = cherrypy.counter + 1 + cherrypy.counter = counter return "visit #%s" % counter index.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': 'production', @@ -57,8 +58,8 @@ class CacheFilterTest(unittest.TestCase): def testCaching(self): for trial in xrange(2): helper.request("/") - self.assertEqual(cpg.response.body, 'visit #1') + self.assertEqual(cherrypy.response.body, 'visit #1') if __name__ == '__main__': - cpg.server.start(initOnly=True) + cherrypy.server.start(initOnly=True) unittest.main() diff --git a/cherrypy/test/test_combinedfilters.py b/cherrypy/test/test_combinedfilters.py index 0ccf8f92..5863a13b 100644 --- a/cherrypy/test/test_combinedfilters.py +++ b/cherrypy/test/test_combinedfilters.py @@ -27,7 +27,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import gzip, StringIO -from cherrypy import cpg +import cherrypy europoundUnicode = u'\x80\xa3' @@ -38,8 +38,8 @@ class Root: yield europoundUnicode index.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': 'production', @@ -47,7 +47,7 @@ cpg.config.update({ 'encodingFilter.on': True, } }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest import helper @@ -62,7 +62,7 @@ class CombinedFiltersTest(unittest.TestCase): zfile.close() helper.request("/", headers=[("Accept-Encoding", "gzip")]) - self.assert_(zbuf.getvalue()[:3] in cpg.response.body) + self.assert_(zbuf.getvalue()[:3] in cherrypy.response.body) if __name__ == '__main__': diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index fd8a334f..84f67af9 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -28,7 +28,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Basic tests for the CherryPy core: request handling.""" -from cherrypy import cpg, cperror +import cherrypy import types class Root: @@ -36,7 +36,7 @@ class Root: return "hello" index.exposed = True -cpg.root = Root() +cherrypy.root = Root() class TestType(type): @@ -45,7 +45,7 @@ class TestType(type): for value in dct.itervalues(): if isinstance(value, types.FunctionType): value.exposed = True - setattr(cpg.root, name.lower(), cls()) + setattr(cherrypy.root, name.lower(), cls()) class Test(object): __metaclass__ = TestType @@ -56,24 +56,24 @@ class Status(Test): return "normal" def blank(self): - cpg.response.status = "" + cherrypy.response.status = "" # According to RFC 2616, new status codes are OK as long as they # are between 100 and 599. # Here is an illegal code... def illegal(self): - cpg.response.status = 781 + cherrypy.response.status = 781 return "oops" # ...and here is an unknown but legal code. def unknown(self): - cpg.response.status = "431 My custom error" + cherrypy.response.status = "431 My custom error" return "funky" # Non-numeric code def bad(self): - cpg.response.status = "error" + cherrypy.response.status = "error" return "hello" @@ -83,24 +83,24 @@ class Redirect(Test): return "child" def by_code(self, code): - raise cperror.HTTPRedirect("somewhere else", code) + raise cherrypy.HTTPRedirect("somewhere else", code) def nomodify(self): - raise cperror.HTTPRedirect("", 304) + raise cherrypy.HTTPRedirect("", 304) def proxy(self): - raise cperror.HTTPRedirect("proxy", 305) + raise cherrypy.HTTPRedirect("proxy", 305) def internal(self): - raise cperror.InternalRedirect("/") + raise cherrypy.InternalRedirect("/") def internal2(self, user_id): if user_id == "parrot": # Trade it for a slug when redirecting - raise cperror.InternalRedirect('/image/getImagesByUser', + raise cherrypy.InternalRedirect('/image/getImagesByUser', "user_id=slug") else: - raise cperror.InternalRedirect('/image/getImagesByUser') + raise cherrypy.InternalRedirect('/image/getImagesByUser') class Image(Test): @@ -138,7 +138,7 @@ class Error(Test): raise ValueError def page_http_1_1(self): - cpg.response.headerMap["Content-Length"] = 39 + cherrypy.response.headerMap["Content-Length"] = 39 def inner(): yield "hello" raise ValueError @@ -155,13 +155,13 @@ class Headers(Test): # header fields, one in lowercase, the other in mixed-case." # Set the most common headers - cpg.response.headerMap['content-type'] = "text/html" - cpg.response.headerMap['content-length'] = 18 - cpg.response.headerMap['server'] = 'CherryPy headertest' - cpg.response.headerMap['location'] = 'http://127.0.0.1:8000/headers/' + cherrypy.response.headerMap['content-type'] = "text/html" + cherrypy.response.headerMap['content-length'] = 18 + cherrypy.response.headerMap['server'] = 'CherryPy headertest' + cherrypy.response.headerMap['location'] = 'http://127.0.0.1:8000/headers/' # Set a rare header for fun - cpg.response.headerMap['Expires'] = 'Thu, 01 Dec 2194 16:00:00 GMT' + cherrypy.response.headerMap['Expires'] = 'Thu, 01 Dec 2194 16:00:00 GMT' return "double header test" @@ -171,17 +171,17 @@ defined_http_methods = ("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", class Method(Test): def index(self): - m = cpg.request.method + m = cherrypy.request.method if m in defined_http_methods: return m if m == "LINK": - cpg.response.status = 405 + cherrypy.response.status = 405 else: - cpg.response.status = 501 + cherrypy.response.status = 501 -cpg.config.update({ +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': 'production', @@ -197,7 +197,7 @@ cpg.config.update({ 'bax': 'this4', }, }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest import helper @@ -206,7 +206,7 @@ import os class CoreRequestHandlingTest(unittest.TestCase): def testConfig(self): - from cherrypy import _cpconfig + import cherrypy tests = [ ('/', 'nex', None ), ('/', 'foo', 'this' ), @@ -219,112 +219,113 @@ class CoreRequestHandlingTest(unittest.TestCase): ('/foo/nex', 'baz', 'that2'), ] for path, key, expected in tests: - cpg.request.path = path - result = _cpconfig.get(key, None) + cherrypy.request.path = path + result = cherrypy.config.get(key, None) self.assertEqual(result, expected) def testStatus(self): helper.request("/status/") - self.assertEqual(cpg.response.body, 'normal') - self.assertEqual(cpg.response.status, '200 OK') + self.assertEqual(cherrypy.response.body, 'normal') + self.assertEqual(cherrypy.response.status, '200 OK') helper.request("/status/blank") - self.assertEqual(cpg.response.body, '') - self.assertEqual(cpg.response.status, '200 OK') + self.assertEqual(cherrypy.response.body, '') + self.assertEqual(cherrypy.response.status, '200 OK') helper.request("/status/illegal") - self.assertEqual(cpg.response.body, 'oops') - self.assertEqual(cpg.response.status, '500 Internal error') + self.assertEqual(cherrypy.response.body, 'oops') + self.assertEqual(cherrypy.response.status, '500 Internal error') helper.request("/status/unknown") - self.assertEqual(cpg.response.body, 'funky') - self.assertEqual(cpg.response.status, '431 My custom error') + self.assertEqual(cherrypy.response.body, 'funky') + self.assertEqual(cherrypy.response.status, '431 My custom error') helper.request("/status/bad") - self.assertEqual(cpg.response.body, 'hello') - self.assertEqual(cpg.response.status, '500 Internal error') + self.assertEqual(cherrypy.response.body, 'hello') + self.assertEqual(cherrypy.response.status, '500 Internal error') def testRedirect(self): helper.request("/redirect/") - self.assertEqual(cpg.response.body, 'child') - self.assertEqual(cpg.response.status, '200 OK') + self.assertEqual(cherrypy.response.body, 'child') + self.assertEqual(cherrypy.response.status, '200 OK') helper.request("/redirect?id=3") - self.assert_(cpg.response.status in ('302 Found', '303 See Other')) - self.assert_("<a href='http://127.0.0.1:8000/redirect/?id=3'>http://127.0.0.1:8000/redirect/?id=3</a>" in cpg.response.body) + self.assert_(cherrypy.response.status in ('302 Found', '303 See Other')) + self.assert_("<a href='http://127.0.0.1:8000/redirect/?id=3'>http://127.0.0.1:8000/redirect/?id=3</a>" + in cherrypy.response.body) helper.request("/redirect/by_code?code=300") - self.assert_("<a href='somewhere else'>somewhere else</a>" in cpg.response.body) - self.assertEqual(cpg.response.status, '300 Multiple Choices') + self.assert_("<a href='somewhere else'>somewhere else</a>" in cherrypy.response.body) + self.assertEqual(cherrypy.response.status, '300 Multiple Choices') helper.request("/redirect/by_code?code=301") - self.assert_("<a href='somewhere else'>somewhere else</a>" in cpg.response.body) - self.assertEqual(cpg.response.status, '301 Moved Permanently') + self.assert_("<a href='somewhere else'>somewhere else</a>" in cherrypy.response.body) + self.assertEqual(cherrypy.response.status, '301 Moved Permanently') helper.request("/redirect/by_code?code=302") - self.assert_("<a href='somewhere else'>somewhere else</a>" in cpg.response.body) - self.assertEqual(cpg.response.status, '302 Found') + self.assert_("<a href='somewhere else'>somewhere else</a>" in cherrypy.response.body) + self.assertEqual(cherrypy.response.status, '302 Found') helper.request("/redirect/by_code?code=303") - self.assert_("<a href='somewhere else'>somewhere else</a>" in cpg.response.body) - self.assertEqual(cpg.response.status, '303 See Other') + self.assert_("<a href='somewhere else'>somewhere else</a>" in cherrypy.response.body) + self.assertEqual(cherrypy.response.status, '303 See Other') helper.request("/redirect/by_code?code=307") - self.assert_("<a href='somewhere else'>somewhere else</a>" in cpg.response.body) - self.assertEqual(cpg.response.status, '307 Temporary Redirect') + self.assert_("<a href='somewhere else'>somewhere else</a>" in cherrypy.response.body) + self.assertEqual(cherrypy.response.status, '307 Temporary Redirect') helper.request("/redirect/nomodify") - self.assertEqual(cpg.response.body, '') - self.assertEqual(cpg.response.status, '304 Not modified') + self.assertEqual(cherrypy.response.body, '') + self.assertEqual(cherrypy.response.status, '304 Not modified') helper.request("/redirect/proxy") - self.assertEqual(cpg.response.body, '') - self.assertEqual(cpg.response.status, '305 Use Proxy') + self.assertEqual(cherrypy.response.body, '') + self.assertEqual(cherrypy.response.status, '305 Use Proxy') # InternalRedirect helper.request("/redirect/internal") - self.assertEqual(cpg.response.body, 'hello') - self.assertEqual(cpg.response.status, '200 OK') + self.assertEqual(cherrypy.response.body, 'hello') + self.assertEqual(cherrypy.response.status, '200 OK') helper.request("/redirect/internal2?user_id=Sir-not-appearing-in-this-film") - self.assertEqual(cpg.response.body, '0 images for Sir-not-appearing-in-this-film') - self.assertEqual(cpg.response.status, '200 OK') + self.assertEqual(cherrypy.response.body, '0 images for Sir-not-appearing-in-this-film') + self.assertEqual(cherrypy.response.status, '200 OK') helper.request("/redirect/internal2?user_id=parrot") - self.assertEqual(cpg.response.body, '0 images for slug') - self.assertEqual(cpg.response.status, '200 OK') + self.assertEqual(cherrypy.response.body, '0 images for slug') + self.assertEqual(cherrypy.response.status, '200 OK') def testFlatten(self): for url in ["/flatten/as_string", "/flatten/as_list", "/flatten/as_yield", "/flatten/as_dblyield", "/flatten/as_refyield"]: helper.request(url) - self.assertEqual(cpg.response.body, 'content') + self.assertEqual(cherrypy.response.body, 'content') def testErrorHandling(self): valerr = '\n raise ValueError\nValueError\n' helper.request("/error/page_method") - self.assert_(cpg.response.body.endswith(valerr)) + self.assert_(cherrypy.response.body.endswith(valerr)) helper.request("/error/page_yield") - self.assert_(cpg.response.body.endswith(valerr)) + self.assert_(cherrypy.response.body.endswith(valerr)) - if cpg._httpserver is None: + if cherrypy._httpserver is None: self.assertRaises(ValueError, helper.request, "/error/page_http_1_1") else: helper.request("/error/page_http_1_1") # Because this error is raised after the response body has # started, the status should not change to an error status. - self.assertEqual(cpg.response.status, "200 OK") - self.assertEqual(cpg.response.body, "helloUnrecoverable error in the server.") + self.assertEqual(cherrypy.response.status, "200 OK") + self.assertEqual(cherrypy.response.body, "helloUnrecoverable error in the server.") def testHeaderCaseSensitivity(self): helper.request("/headers/") - hnames = [name.title() for name, val in cpg.response.headers] + hnames = [name.title() for name, val in cherrypy.response.headers] hnames.sort() self.assertEqual(hnames, ['Content-Length', 'Content-Type', 'Date', 'Expires', 'Location', 'Server']) - self.assertEqual(cpg.response.body, "double header test") + self.assertEqual(cherrypy.response.body, "double header test") def testMethods(self): # Test that all defined HTTP methods work. @@ -336,15 +337,15 @@ class CoreRequestHandlingTest(unittest.TestCase): if m == "HEAD": m = "" - self.assertEqual(cpg.response.body, m) + self.assertEqual(cherrypy.response.body, m) # Request a disallowed method helper.request("/method/", method="LINK") - self.assertEqual(cpg.response.status, "405 Method Not Allowed") + self.assertEqual(cherrypy.response.status, "405 Method Not Allowed") # Request an unknown method helper.request("/method/", method="SEARCH") - self.assertEqual(cpg.response.status, "501 Not Implemented") + self.assertEqual(cherrypy.response.status, "501 Not Implemented") def testFavicon(self): # Calls to favicon.ico are special-cased in _cphttptools. @@ -355,10 +356,10 @@ class CoreRequestHandlingTest(unittest.TestCase): icofile.close() helper.request("/favicon.ico") - self.assertEqual(cpg.response.body, data) + self.assertEqual(cherrypy.response.body, data) helper.request("/redirect/favicon.ico") - self.assertEqual(cpg.response.body, data) + self.assertEqual(cherrypy.response.body, data) if __name__ == '__main__': diff --git a/cherrypy/test/test_decodingencoding_filter.py b/cherrypy/test/test_decodingencoding_filter.py index c777f688..2665b994 100644 --- a/cherrypy/test/test_decodingencoding_filter.py +++ b/cherrypy/test/test_decodingencoding_filter.py @@ -26,7 +26,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy europoundUnicode = u'\x80\xa3' class Root: @@ -35,8 +35,8 @@ class Root: yield europoundUnicode index.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': 'production', @@ -44,7 +44,7 @@ cpg.config.update({ 'decodingFilter.on': True } }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest @@ -56,7 +56,7 @@ class DecodingEncodingFilterTest(unittest.TestCase): def testDecodingEncodingFilter(self): helper.request('/?param=%s' % europoundUtf8) - self.assertEqual(cpg.response.body, europoundUtf8) + self.assertEqual(cherrypy.response.body, europoundUtf8) if __name__ == "__main__": diff --git a/cherrypy/test/test_gzip_filter.py b/cherrypy/test/test_gzip_filter.py index 27469030..15fd4fdb 100644 --- a/cherrypy/test/test_gzip_filter.py +++ b/cherrypy/test/test_gzip_filter.py @@ -27,7 +27,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import gzip, StringIO -from cherrypy import cpg +import cherrypy class Root: def index(self): @@ -41,8 +41,8 @@ class Root: yield "Here be dragons" noshow.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': 'production', @@ -50,7 +50,7 @@ cpg.config.update({ } }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest @@ -67,12 +67,12 @@ class GzipFilterTest(unittest.TestCase): zfile.close() helper.request('/', headers=[("Accept-Encoding", "gzip")]) - self.assert_(zbuf.getvalue()[:3] in cpg.response.body) + self.assert_(zbuf.getvalue()[:3] in cherrypy.response.body) # Test for ticket #147 helper.request('/noshow', headers=[("Accept-Encoding", "gzip")]) - self.assert_('Content-Encoding' not in cpg.response.headerMap) - self.assert_(cpg.response.body.endswith("IndexError\n")) + self.assert_('Content-Encoding' not in cherrypy.response.headerMap) + self.assert_(cherrypy.response.body.endswith("IndexError\n")) if __name__ == "__main__": diff --git a/cherrypy/test/test_logdebuginfo_filter.py b/cherrypy/test/test_logdebuginfo_filter.py index c911f1dc..f63c6c26 100644 --- a/cherrypy/test/test_logdebuginfo_filter.py +++ b/cherrypy/test/test_logdebuginfo_filter.py @@ -26,15 +26,15 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy class Root: def index(self): yield "Hello, world" index.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'session.storageType': 'ram', 'session.timeout': 60, @@ -47,7 +47,7 @@ cpg.config.update({ 'logDebugInfoFilter.on': True, } }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest @@ -57,10 +57,10 @@ class LogDebugInfoFilterTest(unittest.TestCase): def testLogDebugInfoFilter(self): helper.request('/') - self.assert_('Build time' in cpg.response.body) - self.assert_('Page size' in cpg.response.body) + self.assert_('Build time' in cherrypy.response.body) + self.assert_('Page size' in cherrypy.response.body) # not compatible with the sessionFilter - #self.assert_('Session data size' in cpg.response.body) + #self.assert_('Session data size' in cherrypy.response.body) if __name__ == "__main__": diff --git a/cherrypy/test/test_noserver.py b/cherrypy/test/test_noserver.py index 32b05381..ff4c9cb7 100644 --- a/cherrypy/test/test_noserver.py +++ b/cherrypy/test/test_noserver.py @@ -1,4 +1,4 @@ -from cherrypy import cpg +import cherrypy class HelloWorld: def index(self): @@ -6,10 +6,10 @@ class HelloWorld: index.exposed = True wsgi_asp = index -cpg.root = HelloWorld() -cpg.root.test = HelloWorld() +cherrypy.root = HelloWorld() +cherrypy.root.test = HelloWorld() -cpg.config.update({"global": {"server.environment": "production", +cherrypy.config.update({"global": {"server.environment": "production", "session.storageType": "ram"}}) -cpg.server.start(initOnly = True) +cherrypy.server.start(initOnly = True) diff --git a/cherrypy/test/test_objectmapping.py b/cherrypy/test/test_objectmapping.py index 55657b83..925bb90f 100644 --- a/cherrypy/test/test_objectmapping.py +++ b/cherrypy/test/test_objectmapping.py @@ -26,7 +26,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy from cherrypy.lib import httptools class Root: @@ -60,7 +60,7 @@ class Dir1: index.exposed = True def myMethod(self): - return "myMethod from dir1, object Path is:" + repr(cpg.request.objectPath) + return "myMethod from dir1, object Path is:" + repr(cherrypy.request.objectPath) myMethod.exposed = True def default(self, *params): @@ -70,7 +70,7 @@ class Dir1: class Dir2: def index(self): - return "index for dir2, path is:" + cpg.request.path + return "index for dir2, path is:" + cherrypy.request.path index.exposed = True def method(self): @@ -87,18 +87,18 @@ class Dir4: def index(self): return "index for dir4, not exposed" -cpg.root = Root() -cpg.root.dir1 = Dir1() -cpg.root.dir1.dir2 = Dir2() -cpg.root.dir1.dir2.dir3 = Dir3() -cpg.root.dir1.dir2.dir3.dir4 = Dir4() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.root.dir1 = Dir1() +cherrypy.root.dir1.dir2 = Dir2() +cherrypy.root.dir1.dir2.dir3 = Dir3() +cherrypy.root.dir1.dir2.dir3.dir4 = Dir4() +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': "production", } }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest import helper @@ -107,38 +107,38 @@ class ObjectMappingTest(unittest.TestCase): def testObjectMapping(self): helper.request('/') - self.assertEqual(cpg.response.body, 'world') + self.assertEqual(cherrypy.response.body, 'world') helper.request("/dir1/myMethod") - self.assertEqual(cpg.response.body, "myMethod from dir1, object Path is:'/dir1/myMethod'") + self.assertEqual(cherrypy.response.body, "myMethod from dir1, object Path is:'/dir1/myMethod'") helper.request("/this/method/does/not/exist") - self.assertEqual(cpg.response.body, "default:('this', 'method', 'does', 'not', 'exist')") + self.assertEqual(cherrypy.response.body, "default:('this', 'method', 'does', 'not', 'exist')") helper.request("/extra/too/much") - self.assertEqual(cpg.response.body, "default:('extra', 'too', 'much')") + self.assertEqual(cherrypy.response.body, "default:('extra', 'too', 'much')") helper.request("/other") - self.assertEqual(cpg.response.body, 'other') + self.assertEqual(cherrypy.response.body, 'other') helper.request("/notExposed") - self.assertEqual(cpg.response.body, "default:('notExposed',)") + self.assertEqual(cherrypy.response.body, "default:('notExposed',)") helper.request("/dir1/dir2/") - self.assertEqual(cpg.response.body, 'index for dir2, path is:/dir1/dir2/') + self.assertEqual(cherrypy.response.body, 'index for dir2, path is:/dir1/dir2/') helper.request("/dir1/dir2") - self.assert_(cpg.response.status in ('302 Found', '303 See Other')) - self.assertEqual(cpg.response.headerMap['Location'], + self.assert_(cherrypy.response.status in ('302 Found', '303 See Other')) + self.assertEqual(cherrypy.response.headerMap['Location'], 'http://%s:%s/dir1/dir2/' % (helper.HOST, helper.PORT)) helper.request("/dir1/dir2/dir3/dir4/index") - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, "default for dir1, param is:('dir2', 'dir3', 'dir4', 'index')") helper.request("/redirect") - self.assertEqual(cpg.response.status, '302 Found') - self.assertEqual(cpg.response.headerMap['Location'], + self.assertEqual(cherrypy.response.status, '302 Found') + self.assertEqual(cherrypy.response.headerMap['Location'], 'http://%s:%s/dir1/' % (helper.HOST, helper.PORT)) diff --git a/cherrypy/test/test_static_filter.py b/cherrypy/test/test_static_filter.py index 933dbbac..27c0b4df 100644 --- a/cherrypy/test/test_static_filter.py +++ b/cherrypy/test/test_static_filter.py @@ -26,13 +26,13 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy class Root: pass -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'staticFilter.on': False, 'server.logToScreen': False, @@ -47,7 +47,7 @@ cpg.config.update({ 'staticFilter.file': 'style.css', } }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest @@ -57,12 +57,12 @@ class StaticFilterTest(unittest.TestCase): def testStaticFilter(self): helper.request("/static/index.html") - self.assertEqual(cpg.response.headerMap['Content-Type'], 'text/html') - self.assertEqual(cpg.response.body, 'Hello, world\r\n') + self.assertEqual(cherrypy.response.headerMap['Content-Type'], 'text/html') + self.assertEqual(cherrypy.response.body, 'Hello, world\r\n') helper.request("/style.css") - self.assertEqual(cpg.response.headerMap['Content-Type'], 'text/css') - self.assertEqual(cpg.response.body, 'Dummy stylesheet\n') + self.assertEqual(cherrypy.response.headerMap['Content-Type'], 'text/css') + self.assertEqual(cherrypy.response.body, 'Dummy stylesheet\n') if __name__ == "__main__": diff --git a/cherrypy/test/test_tutorials.py b/cherrypy/test/test_tutorials.py index 6ed490f7..dab967f0 100644 --- a/cherrypy/test/test_tutorials.py +++ b/cherrypy/test/test_tutorials.py @@ -28,7 +28,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import sys -from cherrypy import cpg + +import cherrypy from cherrypy.test import helper server_conf = {'server.socketHost': helper.HOST, @@ -41,8 +42,8 @@ server_conf = {'server.socketHost': helper.HOST, def load_tut_module(tutorialName): """Import or reload tutorial module as needed.""" - cpg.config.reset() - cpg.config.update({'global': server_conf.copy()}) + cherrypy.config.reset() + cherrypy.config.update({'global': server_conf.copy()}) target = "cherrypy.tutorial." + tutorialName if target in sys.modules: @@ -50,7 +51,7 @@ def load_tut_module(tutorialName): else: module = __import__(target) - cpg.server.start(initOnly=True) + cherrypy.server.start(initOnly=True) class TutorialTest(unittest.TestCase): @@ -58,34 +59,34 @@ class TutorialTest(unittest.TestCase): def test01HelloWorld(self): load_tut_module("tut01_helloworld") helper.request("/") - self.assertEqual(cpg.response.body, 'Hello world!') + self.assertEqual(cherrypy.response.body, 'Hello world!') def test02ExposeMethods(self): load_tut_module("tut02_expose_methods") helper.request("/showMessage") - self.assertEqual(cpg.response.body, 'Hello world!') + self.assertEqual(cherrypy.response.body, 'Hello world!') def test03GetAndPost(self): load_tut_module("tut03_get_and_post") # Try different GET queries helper.request("/greetUser?name=Bob") - self.assertEqual(cpg.response.body, "Hey Bob, what's up?") + self.assertEqual(cherrypy.response.body, "Hey Bob, what's up?") helper.request("/greetUser") - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, 'Please enter your name <a href="./">here</a>.') helper.request("/greetUser?name=") - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, 'No, really, enter your name <a href="./">here</a>.') # Try the same with POST helper.request("/greetUser", method="POST", body="name=Bob") - self.assertEqual(cpg.response.body, "Hey Bob, what's up?") + self.assertEqual(cherrypy.response.body, "Hey Bob, what's up?") helper.request("/greetUser", method="POST", body="name=") - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, 'No, really, enter your name <a href="./">here</a>.') def test04ComplexSite(self): @@ -100,7 +101,7 @@ class TutorialTest(unittest.TestCase): <p>[<a href="../">Return to links page</a>]</p>''' helper.request("/links/extra/") - self.assertEqual(cpg.response.body, msg) + self.assertEqual(cherrypy.response.body, msg) def test05DerivedObjects(self): load_tut_module("tut05_derived_objects") @@ -120,26 +121,26 @@ class TutorialTest(unittest.TestCase): </html> ''' helper.request("/another/") - self.assertEqual(cpg.response.body, msg) + self.assertEqual(cherrypy.response.body, msg) def test06DefaultMethod(self): load_tut_module("tut06_default_method") helper.request('/hendrik') - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, 'Hendrik Mans, CherryPy co-developer & crazy German ' '(<a href="./">back</a>)') def test07Sessions(self): load_tut_module("tut07_sessions") - cpg.config.update({"global": {"sessionFilter.on": True}}) + cherrypy.config.update({"global": {"sessionFilter.on": True}}) helper.request('/') - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, "\n During your current session, you've viewed this" "\n page 1 times! Your life is a patio of fun!" "\n ") - helper.request('/', [('Cookie', dict(cpg.response.headers)['Set-Cookie'])]) - self.assertEqual(cpg.response.body, + helper.request('/', [('Cookie', dict(cherrypy.response.headers)['Set-Cookie'])]) + self.assertEqual(cherrypy.response.body, "\n During your current session, you've viewed this" "\n page 2 times! Your life is a patio of fun!" "\n ") @@ -147,20 +148,20 @@ class TutorialTest(unittest.TestCase): def test08GeneratorsAndYield(self): load_tut_module("tut08_generators_and_yield") helper.request('/') - self.assertEqual(cpg.response.body, + self.assertEqual(cherrypy.response.body, '<html><body><h2>Generators rule!</h2>' '<h3>List of users:</h3>' 'Remi<br/>Carlos<br/>Hendrik<br/>Lorenzo Lamas<br/>' '</body></html>') def test09SessionFilter(self): load_tut_module("tut09_sessionfilter") - cpg.config.update({"global": {"sessionFilter.on": True}}) + cherrypy.config.update({"global": {"sessionFilter.on": True}}) helper.request('/') - self.assert_("viewed this page 1 times" in cpg.response.body) + self.assert_("viewed this page 1 times" in cherrypy.response.body) - helper.request('/', [('Cookie', dict(cpg.response.headers)['Set-Cookie'])]) - self.assert_("viewed this page 2 times" in cpg.response.body) + helper.request('/', [('Cookie', dict(cherrypy.response.headers)['Set-Cookie'])]) + self.assert_("viewed this page 2 times" in cherrypy.response.body) def test10FileUpload(self): load_tut_module("tut10_file_upload") @@ -175,7 +176,7 @@ hello --x-- """ helper.request('/upload', h, "POST", b) - self.assertEqual(cpg.response.body, ''' + self.assertEqual(cherrypy.response.body, ''' <html><body> myFile length: 5<br /> myFile filename: hello.txt<br /> diff --git a/cherrypy/test/test_virtualhost_filter.py b/cherrypy/test/test_virtualhost_filter.py index 2ba66ffe..745465b6 100644 --- a/cherrypy/test/test_virtualhost_filter.py +++ b/cherrypy/test/test_virtualhost_filter.py @@ -26,15 +26,15 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from cherrypy import cpg +import cherrypy class Root: def index2(self): yield "Hello, world" index2.exposed = True -cpg.root = Root() -cpg.config.update({ +cherrypy.root = Root() +cherrypy.config.update({ 'global': { 'server.logToScreen': False, 'server.environment': 'production', @@ -42,7 +42,7 @@ cpg.config.update({ 'virtualHostFilter.prefix': '/index2', }, }) -cpg.server.start(initOnly=True) +cherrypy.server.start(initOnly=True) import unittest @@ -52,7 +52,7 @@ class VirtualHostFilterTest(unittest.TestCase): def testVirtualHostFilter(self): helper.request("/") - self.assertEqual(cpg.response.body, 'Hello, world') + self.assertEqual(cherrypy.response.body, 'Hello, world') if __name__ == "__main__": diff --git a/cherrypy/tutorial/bonus-sqlobject.py b/cherrypy/tutorial/bonus-sqlobject.py index 1a226ca3..3a384b61 100644 --- a/cherrypy/tutorial/bonus-sqlobject.py +++ b/cherrypy/tutorial/bonus-sqlobject.py @@ -30,7 +30,7 @@ to be very GOOD. Play around with it some, browse the source code, smile. -- Hendrik Mans <hendrik@mans.de> ''' -from cherrypy import cpg +import cherrypy from Cheetah.Template import Template from sqlobject import * @@ -165,5 +165,5 @@ class ContactManager: print "If you're running this application for the first time, please go to http://localhost:8080/reset once in order to create the database!" -cpg.root = ContactManager() -cpg.server.start() +cherrypy.root = ContactManager() +cherrypy.server.start() diff --git a/cherrypy/tutorial/tut01_helloworld.py b/cherrypy/tutorial/tut01_helloworld.py index 340c5af6..75dd4039 100644 --- a/cherrypy/tutorial/tut01_helloworld.py +++ b/cherrypy/tutorial/tut01_helloworld.py @@ -5,7 +5,7 @@ The most basic (working) CherryPy application possible. """ # Import CherryPy global namespace -from cherrypy import cpg +import cherrypy class HelloWorld: """ Sample request handler class. """ @@ -21,14 +21,14 @@ class HelloWorld: # publish methods that don't have the exposed attribute set to True. index.exposed = True -# CherryPy always starts with cpg.root when trying to map request URIs +# CherryPy always starts with cherrypy.root when trying to map request URIs # to objects, so we need to mount a request handler object here. A request -# to '/' will be mapped to cpg.root.index(). -cpg.root = HelloWorld() +# to '/' will be mapped to cherrypy.root.index(). +cherrypy.root = HelloWorld() if __name__ == '__main__': # Use the configuration file tutorial.conf. - cpg.config.update(file = 'tutorial.conf') + cherrypy.config.update(file = 'tutorial.conf') # Start the CherryPy server. - cpg.server.start() + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut02_expose_methods.py b/cherrypy/tutorial/tut02_expose_methods.py index 856bae84..777dd11f 100644 --- a/cherrypy/tutorial/tut02_expose_methods.py +++ b/cherrypy/tutorial/tut02_expose_methods.py @@ -5,7 +5,7 @@ This tutorial shows you how to link to other methods of your request handler. """ -from cherrypy import cpg +import cherrypy class HelloWorld: @@ -19,9 +19,9 @@ class HelloWorld: return "Hello world!" showMessage.exposed = True -cpg.root = HelloWorld() +cherrypy.root = HelloWorld() if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut03_get_and_post.py b/cherrypy/tutorial/tut03_get_and_post.py index aa81aff7..ca9bd184 100644 --- a/cherrypy/tutorial/tut03_get_and_post.py +++ b/cherrypy/tutorial/tut03_get_and_post.py @@ -4,7 +4,8 @@ Tutorial 03 - Passing variables This tutorial shows you how to pass GET/POST variables to methods. """ -from cherrypy import cpg +import cherrypy + class WelcomePage: @@ -39,9 +40,9 @@ class WelcomePage: greetUser.exposed = True -cpg.root = WelcomePage() +cherrypy.root = WelcomePage() if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut04_complex_site.py b/cherrypy/tutorial/tut04_complex_site.py index 38248d2c..1ae7a57d 100644 --- a/cherrypy/tutorial/tut04_complex_site.py +++ b/cherrypy/tutorial/tut04_complex_site.py @@ -5,7 +5,8 @@ This tutorial shows you how to create a site structure through multiple possibly nested request handler objects. """ -from cherrypy import cpg +import cherrypy + class HomePage: def index(self): @@ -73,9 +74,9 @@ class ExtraLinksPage: # Of course we can also mount request handler objects right here! -cpg.root = HomePage() -cpg.root.joke = JokePage() -cpg.root.links = LinksPage() +cherrypy.root = HomePage() +cherrypy.root.joke = JokePage() +cherrypy.root.links = LinksPage() # Remember, we don't need to mount ExtraLinksPage here, because # LinksPage does that itself on initialization. In fact, there is @@ -84,6 +85,6 @@ cpg.root.links = LinksPage() if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut05_derived_objects.py b/cherrypy/tutorial/tut05_derived_objects.py index 60204e79..786a47c4 100644 --- a/cherrypy/tutorial/tut05_derived_objects.py +++ b/cherrypy/tutorial/tut05_derived_objects.py @@ -7,7 +7,8 @@ want to create a central base class used for all your pages, which takes care of things like printing a common page header and footer. """ -from cherrypy import cpg +import cherrypy + class Page: # Store the page title in a class attribute @@ -68,10 +69,10 @@ class AnotherPage(Page): index.exposed = True -cpg.root = HomePage() +cherrypy.root = HomePage() if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut06_default_method.py b/cherrypy/tutorial/tut06_default_method.py index 1ba4a810..e1349575 100644 --- a/cherrypy/tutorial/tut06_default_method.py +++ b/cherrypy/tutorial/tut06_default_method.py @@ -9,14 +9,15 @@ located deepest on the URI path. Using this mechanism you can easily simulate virtual URI structures by parsing the extra URI string, which you can access through -cpg.request.virtualPath. +cherrypy.request.virtualPath. The application in this tutorial simulates an URI structure looking like /users/<username>. Since the <username> bit will not be found (as there are no matching methods), it is handled by the default method. """ -from cherrypy import cpg +import cherrypy + class UsersPage: @@ -49,10 +50,10 @@ class UsersPage: default.exposed = True -cpg.root = UsersPage() +cherrypy.root = UsersPage() if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut07_sessions.py b/cherrypy/tutorial/tut07_sessions.py index f5d721ce..de21022c 100644 --- a/cherrypy/tutorial/tut07_sessions.py +++ b/cherrypy/tutorial/tut07_sessions.py @@ -1,23 +1,23 @@ """ Tutorial 08 - Sessions -Storing session data in CherryPy applications is very easy: cpg.request +Storing session data in CherryPy applications is very easy: cherrypy.request provides a dictionary called sessionMap that represents the session data for the current user. If you use RAM based sessions, you can store any kind of object into that dictionary; otherwise, you are limited to objects that can be pickled. """ -from cherrypy import cpg +import cherrypy class HitCounter: def index(self): # Increase the silly hit counter - count = cpg.sessions.default.get('count', 0) + 1 + count = cherrypy.sessions.default.get('count', 0) + 1 # Store the new value in the session dictionary - cpg.sessions.default['count'] = count + cherrypy.sessions.default['count'] = count # And display a silly hit count message! return ''' @@ -27,10 +27,10 @@ class HitCounter: index.exposed = True -cpg.root = HitCounter() -cpg.config.update({'global': {'sessionFilter.on': True}}) +cherrypy.root = HitCounter() +cherrypy.config.update({'global': {'sessionFilter.on': True}}) if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut08_generators_and_yield.py b/cherrypy/tutorial/tut08_generators_and_yield.py index f2bbbc31..3f4443d5 100644 --- a/cherrypy/tutorial/tut08_generators_and_yield.py +++ b/cherrypy/tutorial/tut08_generators_and_yield.py @@ -7,7 +7,8 @@ in situations where using a template package like CherryPy or Cheetah would be overkill, and messy string concatenation too uncool. ;-) """ -from cherrypy import cpg +import cherrypy + class GeneratorDemo: @@ -31,10 +32,10 @@ class GeneratorDemo: yield self.footer() index.exposed = True -cpg.root = GeneratorDemo() +cherrypy.root = GeneratorDemo() if __name__ == '__main__': - cpg.config.update(file = 'tutorial.conf') - cpg.server.start() + cherrypy.config.update(file = 'tutorial.conf') + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut09_sessionfilter.py b/cherrypy/tutorial/tut09_sessionfilter.py index 2e6dcbd0..0abeb441 100644 --- a/cherrypy/tutorial/tut09_sessionfilter.py +++ b/cherrypy/tutorial/tut09_sessionfilter.py @@ -2,7 +2,7 @@ Tutorial 10 - Advanced sessionFilter usage see tut10_sessionfilter.conf """ -from cherrypy import cpg +import cherrypy # you will never need to import the RamSession # we only import it to demostrate how to manually use @@ -14,7 +14,7 @@ class HitCounter: def __init__(self): # turn on the sessionfilter and create sessions for the admin # and forum sections of the site - cpg.config.update( + cherrypy.config.update( { 'global' : {'sessionFilter.on': True}, '/admin' : {'sessionFilter.sessionList' : ['admin'] }, @@ -23,7 +23,7 @@ class HitCounter: # this is just a primative template function def __examplePage(self, poweredBy, count, links, sessionKey): - yield '<html><head><title>sessionFilter exampe</title><body>\n' + yield '<html><head><title>sessionFilter example</title><body>\n' yield 'This page uses %s based session storage.<br/>\n' % poweredBy yield 'You have viewed this page %i times. <br/><br/>\n' % count for link in links: @@ -42,14 +42,14 @@ class HitCounter: # it may not be the defualt in future versions # Increase the silly hit counter - count = cpg.sessions.default.get('count', 0) + 1 + count = cherrypy.sessions.default.get('count', 0) + 1 # Store the new value in the session dictionary - # cpg.sessions.default is available by default - cpg.sessions.default['count'] = count + # cherrypy.sessions.default is available by default + cherrypy.sessions.default['count'] = count # And display a silly hit count message! - key = cpg.sessions.default.key + key = cherrypy.sessions.default.key return self.__examplePage('ram', count, self.samplePages, key) index.exposed = True @@ -59,10 +59,10 @@ class HitCounter: # the config file "tut10_sessionFilter.conf", otherwise # it mirrors the session function - adminCount = cpg.sessions.admin.get('adminCount', 0) + 1 - cpg.sessions.admin['adminCount'] = adminCount + adminCount = cherrypy.sessions.admin.get('adminCount', 0) + 1 + cherrypy.sessions.admin['adminCount'] = adminCount - key = cpg.sessions.admin.key + key = cherrypy.sessions.admin.key return self.__examplePage('ram', adminCount, self.samplePages, key) admin.exposed = True @@ -73,17 +73,17 @@ class HitCounter: # the config file "tut10_sessionFilter.conf", otherwise # it mirrors the session function - forumCount = cpg.sessions.forum.get('forumCount', 0) + 1 - cpg.sessions.forum['forumCount'] = forumCount + forumCount = cherrypy.sessions.forum.get('forumCount', 0) + 1 + cherrypy.sessions.forum['forumCount'] = forumCount - key = cpg.sessions.forum.key + key = cherrypy.sessions.forum.key return self.__examplePage('ram', forumCount, self.samplePages, key) forum.exposed=True -cpg.root = HitCounter() +cherrypy.root = HitCounter() if __name__ == '__main__': - cpg.config.update(file = "tutorial.conf") - cpg.server.start() + cherrypy.config.update(file = "tutorial.conf") + cherrypy.server.start() diff --git a/cherrypy/tutorial/tut10_file_upload.py b/cherrypy/tutorial/tut10_file_upload.py index 6fd151e4..6108eaf8 100644 --- a/cherrypy/tutorial/tut10_file_upload.py +++ b/cherrypy/tutorial/tut10_file_upload.py @@ -1,6 +1,7 @@ """Tutorial: File upload""" -from cherrypy import cpg +import cherrypy + class FileUploadDemo(object): @@ -28,10 +29,10 @@ class FileUploadDemo(object): upload.exposed = True -cpg.root = FileUploadDemo() +cherrypy.root = FileUploadDemo() if __name__ == '__main__': # Use the configuration file tutorial.conf. - cpg.config.update(file = 'tutorial.conf') + cherrypy.config.update(file = 'tutorial.conf') # Start the CherryPy server. - cpg.server.start() + cherrypy.server.start() |