1. cherrypy
  2. CherryPy

Commits

Remi Delon  committed b3cf533

Big change: camelCase to lower_with_underscore names (still need to update the book)

  • Participants
  • Parent commits 462502d
  • Branches cherrypy

Comments (0)

Files changed (46)

File __init__.py

View file
 request = _ThreadLocalProxy('request')
 response = _ThreadLocalProxy('response')
 
-# Create threadData object as a thread-specific all-purpose storage
-threadData = local()
+# Create thread_data object as a thread-specific all-purpose storage
+thread_data = local()
+threadData = thread_data # Backward compatibility
 
 # Create variables needed for session (see lib/sessionfilter.py for more info)
 from filters import sessionfilter
 session = sessionfilter.SessionWrapper()
-_sessionDataHolder = {} # Needed for RAM sessions only
-_sessionLockDict = {} # Needed for RAM sessions only
-_sessionLastCleanUpTime = datetime.datetime.now()
+_session_data_holder = {} # Needed for RAM sessions only
+_session_lock_dict = {} # Needed for RAM sessions only
+_session_last_clean_up_time = datetime.datetime.now()
 
 def expose(func=None, alias=None):
     """Expose the function, optionally providing an alias or set of aliases."""
         func.exposed = True
         if alias is not None:
             if isinstance(alias, basestring):
-                parentDict[alias] = func
+                parents[alias] = func
             else:
                 for a in alias:
-                    parentDict[a] = func
+                    parents[a] = func
         return func
     
-    parentDict = sys._getframe(1).f_locals
+    parents = sys._getframe(1).f_locals
     if isinstance(func, (types.FunctionType, types.MethodType)):
         # expose is being called directly, before the method has been bound
         return expose_(func)
     # Load _cputil lazily to avoid circular references, and
     # to allow profiler and coverage tools to work on it.
     import _cputil
-    logfunc = _cputil.getSpecialAttribute('_cpLogMessage')
+    logfunc = _cputil.get_special_attribute('_cp_log_message', '_cpLogMessage')
     logfunc(msg, context, severity)
 

File _cperror.py

View file
 class InternalRedirect(Exception):
     """Exception raised when processing should be handled by a different path.
     
-    If you supply 'params', it will be used to re-populate paramMap.
+    If you supply 'params', it will be used to re-populate params.
     If 'params' is a dict, it will be used directly.
     If 'params' is a string, it will be converted to a dict using cgi.parse_qs.
     
-    If you omit 'params', the paramMap from the original request will
+    If you omit 'params', the params from the original request will
     remain in effect, including any POST parameters.
     """
     
                 for key, val in pm.items():
                     if len(val) == 1:
                         pm[key] = val[0]
-                request.paramMap = pm
+                request.params = pm
             else:
                 request.queryString = urllib.urlencode(params)
-                request.paramMap = params.copy()
+                request.params = params.copy()
         
         Exception.__init__(self, path, params)
 
         import cherrypy
         response = cherrypy.response
         response.status = status = self.status
-        response.headerMap['Content-Type'] = "text/html"
+        response.headers['Content-Type'] = "text/html"
         
         if status in (300, 301, 302, 303, 307):
             # "The ... URI SHOULD be given by the Location field
             # in the response."
-            response.headerMap['Location'] = self.urls[0]
+            response.headers['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
         elif status == 305:
             # Use Proxy.
             # self.urls[0] should be the URI of the proxy.
-            response.headerMap['Location'] = self.urls[0]
+            response.headers['Location'] = self.urls[0]
             response.body = None
         else:
             raise ValueError("The %s status code is unknown." % status)
     
     def set_response(self):
         import cherrypy
-        handler = cherrypy._cputil.getSpecialAttribute("_cpOnHTTPError")
+        handler = cherrypy._cputil.get_special_attribute("_cp_on_http_error", "_cpOnHTTPError")
         handler(self.status, self.message)
 
 

File _cphttpserver.py

View file
     """CherryPy HTTP request handler"""
     
     def address_string(self):
-        """ Try to do a reverse DNS based on server.reverseDNS in the config file """
-        if cherrypy.config.get('server.reverseDNS'):
+        """ Try to do a reverse DNS based on server.reverse_dns in the config file """
+        if cherrypy.config.get('server.reverse_dns'):
             return BaseHTTPRequestHandler.address_string(self)
         else:
             return self.client_address[0]
     
     def parse_request(self):
         # Extended to provide header and body length limits.
-        mhs = int(cherrypy.config.get('server.maxRequestHeaderSize',
+        mhs = int(cherrypy.config.get('server.max_request_header_size',
                                       500 * 1024))
         self.rfile = httptools.SizeCheckWrapper(self.rfile, mhs)
         try:
                 path = self.path
                 if path == "*":
                     path = "global"
-                mbs = int(cherrypy.config.get('server.maxRequestBodySize',
+                mbs = int(cherrypy.config.get('server.max_request_body_size',
                                               100 * 1024 * 1024, path=path))
                 self.rfile.maxlen = mbs
         return presult
         try:
             request = cherrypy.server.request(self.client_address,
                                               self.address_string(), "http")
-            request.multithread = cherrypy.config.get("server.threadPool") > 1
+            request.multithread = cherrypy.config.get("server.thread_pool") > 1
             request.multiprocess = False
             response = request.run(self.raw_requestline, self._headerlist(),
                                    self.rfile)
         except:
             tb = _cputil.formatExc()
             cherrypy.log(tb)
-            if not cherrypy.config.get("server.showTracebacks", False):
+            if not cherrypy.config.get("server.show_tracebacks", False):
                 tb = ""
             s, h, b = _cputil.bareError(tb)
         
         # but we have to in order to implement SSL and IPv6 support!
         
         # Set protocol_version
-        httpproto = cherrypy.config.get('server.protocolVersion') or "HTTP/1.0"
+        httpproto = cherrypy.config.get('server.protocol_version') or "HTTP/1.0"
         self.RequestHandlerClass.protocol_version = httpproto
         
-        self.request_queue_size = cherrypy.config.get('server.socketQueueSize')
+        self.request_queue_size = cherrypy.config.get('server.socket_queue_size')
         
         # Select the appropriate server based on config options
-        sockFile = cherrypy.config.get('server.socketFile')
+        sockFile = cherrypy.config.get('server.socket_file')
         if sockFile:
             # AF_UNIX socket
             self.address_family = socket.AF_UNIX
             self.server_bind()
         else:
             # AF_INET or AF_INET6 socket
-            host = cherrypy.config.get('server.socketHost')
-            port = cherrypy.config.get('server.socketPort')
+            host = cherrypy.config.get('server.socket_host')
+            port = cherrypy.config.get('server.socket_port')
             self.server_address = (host, port)
             
             try:
        requests (i.e. you don't have to bother with Deferreds)."""
     
     def __init__(self):
-        self.numThreads = cherrypy.config.get('server.threadPool')
+        self.numThreads = cherrypy.config.get('server.thread_pool')
         self.ThreadClass = ServerThread
         self.requestQueue = Queue.Queue()
         self.workerThreads = []
     """Selects and instantiates the appropriate server."""
     
     # Select the appropriate server based on config options
-    if cherrypy.config.get('server.threadPool', 1) > 1:
+    if cherrypy.config.get('server.thread_pool', 1) > 1:
         ServerClass = PooledThreadServer
     else:
         ServerClass = CherryHTTPServer

File _cphttptools.py

View file
         if not self.closed:
             self.closed = True
             try:
-                applyFilters('onEndRequest')
+                applyFilters('on_end_request', 'onEndRequest')
             except (KeyboardInterrupt, SystemExit):
                 raise
             except:
         
         """
         self.requestLine = requestLine.strip()
-        self.headers = list(headers)
+        self.header_list = list(headers)
         self.rfile = rfile
         
         if cherrypy.profiler:
     def _run(self):
         
         try:
-            self.headerMap = httptools.HeaderMap()
+            self.headers = httptools.HeaderMap()
+            self.headerMap = self.headers # Backward compatibility
             self.simpleCookie = Cookie.SimpleCookie()
             
             # This has to be done very early in the request process,
             self.processRequestLine()
             
             try:
-                applyFilters('onStartResource')
+                applyFilters('on_start_resource', 'onStartResource')
                 
                 try:
                     self.processHeaders()
                     
-                    applyFilters('beforeRequestBody')
+                    applyFilters('before_request_body', 'beforeRequestBody')
                     if self.processRequestBody:
                         self.processBody()
                     
-                    applyFilters('beforeMain')
+                    applyFilters('before_main', 'beforeMain')
                     if self.executeMain:
                         self.main()
                     
-                    applyFilters('beforeFinalize')
+                    applyFilters('before_finalize', 'beforeFinalize')
                     cherrypy.response.finalize()
                 except cherrypy.RequestHandled:
                     pass
                     # we don't go through the regular mechanism:
                     # we return the redirect or error page immediately
                     inst.set_response()
-                    applyFilters('beforeFinalize')
+                    applyFilters('before_finalize', 'before_finalize')
                     cherrypy.response.finalize()
             finally:
-                applyFilters('onEndResource')
+                applyFilters('on_end_resource', 'onEndResource')
         except (KeyboardInterrupt, SystemExit):
             raise
         except:
             # HEAD requests MUST NOT return a message-body in the response.
             cherrypy.response.body = []
         
-        _cputil.getSpecialAttribute("_cpLogAccess")()
+        _cputil.get_special_attribute("_cp_log_access", "_cpLogAccess")()
     
     def processRequestLine(self):
         rl = self.requestLine
         
         # cherrypy.request.version == request.protocol in a Version instance.
         self.version = httptools.Version.from_http(self.protocol)
-        server_v = cherrypy.config.get("server.protocolVersion", "HTTP/1.0")
+        server_v = cherrypy.config.get("server.protocol_version", "HTTP/1.0")
         server_v = httptools.Version.from_http(server_v)
         
         # cherrypy.response.version should be used to determine whether or
     
     def processHeaders(self):
         
-        self.paramMap = httptools.parseQueryString(self.queryString)
+        self.params = httptools.parseQueryString(self.queryString)
+        self.paramMap = self.params # Backward compatibility
         
-        # Process the headers into self.headerMap
-        for name, value in self.headers:
+        # Process the headers into self.headers
+        for name, value in self.header_list:
             value = value.strip()
             # Warning: if there is more than one header entry for cookies (AFAIK,
-            # only Konqueror does that), only the last one will remain in headerMap
+            # only Konqueror does that), only the last one will remain in headers
             # (but they will be correctly stored in request.simpleCookie).
-            self.headerMap[name] = value
+            self.headers[name] = value
             
             # Handle cookies differently because on Konqueror, multiple
             # cookies come on different lines with the same key
         
         # Save original values (in case they get modified by filters)
         # This feature is deprecated in 2.2 and will be removed in 2.3.
-        self._originalParamMap = self.paramMap.copy()
+        self._original_params = self.params.copy()
         
         if self.version >= "1.1":
             # All Internet-based HTTP/1.1 servers MUST respond with a 400
             # (Bad Request) status code to any HTTP/1.1 request message
             # which lacks a Host header field.
-            if not self.headerMap.has_key("Host"):
+            if not self.headers.has_key("Host"):
                 msg = "HTTP/1.1 requires a 'Host' request header."
                 raise cherrypy.HTTPError(400, msg)
-        self.base = "%s://%s" % (self.scheme, self.headerMap.get('Host', ''))
+        self.base = "%s://%s" % (self.scheme, self.headers.get('Host', ''))
     
-    def _get_original_param_map(self):
+    def _get_original_params(self):
         # This feature is deprecated in 2.2 and will be removed in 2.3.
-        return self._originalParamMap
-    originalParamMap = property(_get_original_param_map,
-                        doc="Deprecated. A copy of the original paramMap.")
+        return self._original_params
+    original_params = property(_get_original_params,
+                        doc="Deprecated. A copy of the original params.")
     
     def _get_browserUrl(self):
         url = self.base + self.path
                           doc="The URL as entered in a browser (read-only).")
     
     def processBody(self):
-        # Create a copy of headerMap with lowercase keys because
+        # Create a copy of headers with lowercase keys because
         # FieldStorage doesn't work otherwise
         lowerHeaderMap = {}
-        for key, value in self.headerMap.items():
+        for key, value in self.headers.items():
             lowerHeaderMap[key.lower()] = value
         
         # FieldStorage only recognizes POST, so fake it.
             # request body was a content-type other than form params.
             self.body = forms.file
         else:
-            self.paramMap.update(httptools.paramsFromCGIForm(forms))
+            self.params.update(httptools.paramsFromCGIForm(forms))
     
     def main(self, path=None):
         """Obtain and set cherrypy.response.body from a page handler."""
                 # Remove "root" from object_path and join it to get objectPath
                 self.objectPath = '/' + '/'.join(object_path[1:])
                 try:
-                    body = page_handler(*virtual_path, **self.paramMap)
+                    body = page_handler(*virtual_path, **self.params)
                 except Exception, x:
                     x.args = x.args + (page_handler,)
                     raise
             # that raises NotFound.
             icofile = os.path.join(os.path.dirname(__file__), "favicon.ico")
             cptools.serveFile(icofile)
-            applyFilters('beforeFinalize')
+            applyFilters('before_finalize', 'beforeFinalize')
             cherrypy.response.finalize()
             raise cherrypy.RequestHandled()
         else:
     
     def __init__(self):
         self.status = None
-        self.headers = None
+        self.header_list = None
         self.body = None
         
-        self.headerMap = httptools.HeaderMap()
-        self.headerMap.update({
+        self.headers = httptools.HeaderMap()
+        self.headerMap = self.headers # Backward compatibility
+        self.headers.update({
             "Content-Type": "text/html",
             "Server": "CherryPy/" + cherrypy.__version__,
             "Date": httptools.HTTPDate(),
         return newbody
     
     def finalize(self):
-        """Transform headerMap (and cookies) into cherrypy.response.headers."""
+        """Transform headers (and cookies) into cherrypy.response.header_list."""
         
         try:
             code, reason, _ = httptools.validStatus(self.status)
         
         if stream:
             try:
-                del self.headerMap['Content-Length']
+                del self.headers['Content-Length']
             except KeyError:
                 pass
         else:
             # Responses which are not streamed should have a Content-Length,
             # but allow user code to set Content-Length if desired.
-            if self.headerMap.get('Content-Length') is None:
+            if self.headers.get('Content-Length') is None:
                 content = self.collapse_body()
-                self.headerMap['Content-Length'] = len(content)
+                self.headers['Content-Length'] = len(content)
         
         # Headers
-        headers = []
-        for key, valueList in self.headerMap.iteritems():
+        header_list = []
+        for key, valueList in self.headers.iteritems():
             order = _header_order_map.get(key, 3)
             if not isinstance(valueList, list):
                 valueList = [valueList]
             for value in valueList:
-                headers.append((order, (key, str(value))))
+                header_list.append((order, (key, str(value))))
         # RFC 2616: '... it is "good practice" to send general-header
         # fields first, followed by request-header or response-header
         # fields, and ending with the entity-header fields.'
-        headers.sort()
-        self.headers = [item[1] for item in headers]
+        header_list.sort()
+        self.header_list = [item[1] for item in header_list]
         
         cookie = self.simpleCookie.output()
         if cookie:
             lines = cookie.split("\n")
             for line in lines:
                 name, value = line.split(": ", 1)
-                self.headers.append((name, value))
+                self.header_list.append((name, value))
     
     dbltrace = "\n===First Error===\n\n%s\n\n===Second Error===\n\n%s\n\n"
     
     def handleError(self, exc):
         """Set status, headers, and body when an unanticipated error occurs."""
         try:
-            applyFilters('beforeErrorResponse')
+            applyFilters('before_error_response', 'beforeErrorResponse')
            
-            # _cpOnError will probably change self.body.
-            # It may also change the headerMap, etc.
-            _cputil.getSpecialAttribute('_cpOnError')()
+            # _cp_on_error will probably change self.body.
+            # It may also change the headers, etc.
+            _cputil.get_special_attribute('_cp_on_error', '_cpOnError')()
             
             self.finalize()
             
-            applyFilters('afterErrorResponse')
+            applyFilters('after_error_response', 'afterErrorResponse')
             return
         except cherrypy.HTTPRedirect, inst:
             try:
             # Fall through to the second error handler
             pass
         
-        # Failure in _cpOnError, error filter, or finalize.
+        # Failure in _cp_on_error, error filter, or finalize.
         # Bypass them all.
-        if cherrypy.config.get('server.showTracebacks', False):
+        if cherrypy.config.get('server.show_tracebacks', False):
             body = self.dbltrace % (_cputil.formatExc(exc),
                                     _cputil.formatExc())
         else:
         self.setBareError(body)
     
     def setBareError(self, body=None):
-        self.status, self.headers, self.body = _cputil.bareError(body)
+        self.status, self.header_list, self.body = _cputil.bareError(body)
 

File _cpserver.py

View file
         self.interrupt = None
         
         # Set some special attributes for adding hooks
-        self.onStartServerList = []
-        self.onStartThreadList = []
-        self.onStopServerList = []
-        self.onStopThreadList = []
+        self.on_start_server_list = []
+        self.on_start_thread_list = []
+        self.on_stop_server_list = []
+        self.on_stop_thread_list = []
+
+        # Backward compatibility:
+        self.onStopServerList = self.on_stop_server_list
+        self.onStartThreadList = self.on_start_thread_list
+        self.onStartServerList = self.on_start_server_list
+        self.onStopThreadList = self.on_stop_thread_list
     
     def start(self, initOnly=False, serverClass=_missing):
         """Main function. MUST be called from the main thread.
     
     def _start(self):
         # Output config options to log
-        if cherrypy.config.get("server.logConfigOptions", True):
+        if cherrypy.config.get("server.log_config_options", True):
             cherrypy.config.outputConfigMap()
         
         try:
             configure()
             
-            for func in cherrypy.server.onStartServerList:
+            for func in cherrypy.server.on_start_server_list:
                 func()
             self.start_http_server()
             self.state = STARTED
         if self.httpserverclass is None:
             return
         
-        if cherrypy.config.get('server.socketPort'):
-            host = cherrypy.config.get('server.socketHost')
-            port = cherrypy.config.get('server.socketPort')
+        if cherrypy.config.get('server.socket_port'):
+            host = cherrypy.config.get('server.socket_host')
+            port = cherrypy.config.get('server.socket_port')
             
             wait_for_free_port(host, port)
             
             if not host:
                 host = 'localhost'
-            onWhat = "http://%s:%s/" % (host, port)
+            on_what = "http://%s:%s/" % (host, port)
         else:
-            onWhat = "socket file: %s" % cherrypy.config.get('server.socketFile')
+            on_what = "socket file: %s" % cherrypy.config.get('server.socket_file')
         
         # Instantiate the server.
         self.httpserver = self.httpserverclass()
         if blocking:
             self.wait_for_http_ready()
         
-        cherrypy.log("Serving HTTP on %s" % onWhat, 'HTTP')
+        cherrypy.log("Serving HTTP on %s" % on_what, 'HTTP')
     
     def wait_for_http_ready(self):
         if self.httpserverclass is not None:
                 time.sleep(.1)
             
             # Wait for port to be occupied
-            if cherrypy.config.get('server.socketPort'):
-                host = cherrypy.config.get('server.socketHost')
-                port = cherrypy.config.get('server.socketPort')
+            if cherrypy.config.get('server.socket_port'):
+                host = cherrypy.config.get('server.socket_host')
+                port = cherrypy.config.get('server.socket_port')
                 wait_for_occupied_port(host, port)
     
     def request(self, clientAddress, remoteHost, scheme="http"):
             i = len(seen_threads) + 1
             seen_threads[threadID] = i
             
-            for func in self.onStartThreadList:
+            for func in self.on_start_thread_list:
                 func(i)
         
         r = _cphttptools.Request(clientAddress[0], clientAddress[1],
         self.stop_http_server()
         
         for thread_ident, i in seen_threads.iteritems():
-            for func in self.onStopThreadList:
+            for func in self.on_stop_thread_list:
                 func(i)
         seen_threads.clear()
         
-        for func in self.onStopServerList:
+        for func in self.on_stop_server_list:
             func()
         
         self.state = STOPPED
     def restart(self):
         """Restart, including any HTTP servers."""
         self.stop()
-        for func in self.onStartServerList:
+        for func in self.on_start_server_list:
             func()
         self.start_http_server()
         self.state = STARTED
     
     # If sessions are stored in files and we
     # use threading, we need a lock on the file
-    if (conf('server.threadPool') > 1
-        and conf('session.storageType') == 'file'):
+    if (conf('server.thread_pool') > 1
+        and conf('session.storage_type') == 'file'):
         cherrypy._sessionFileLock = threading.RLock()
     
     # set cgi.maxlen which will limit the size of POST request bodies
-    cgi.maxlen = conf('server.maxRequestSize')
+    cgi.maxlen = conf('server.max_request_size')
     
     # Set up the profiler if requested.
     if conf("profiling.on", False):
 
 def check_port(host, port):
     """Raise an error if the given port is not free on the given host."""
-    sockFile = cherrypy.config.get('server.socketFile')
-    if sockFile:
+    sock_file = cherrypy.config.get('server.socket_file')
+    if sock_file:
         return
     
     if not host:

File _cputil.py

View file
     
     return objectTrail
 
-def getSpecialAttribute(name):
+def get_special_attribute(name, alternate_name = None):
     """Return the special attribute. A special attribute is one that
     applies to all of the children from where it is defined, such as
-    _cpFilterList."""
+    _cp_filters."""
     
     # First, we look in the right-most object to see if this special
     # attribute is implemented. If not, then we try the previous object,
     try:
         return globals()[name]
     except KeyError:
+        if alternate_name:
+            return get_special_attribute(alternate_name)
         msg = "Special attribute %s could not be found" % repr(name)
         raise cherrypy.HTTPError(500, msg)
 
 def _cpGlobalHandler():
     """Default handler for a Request-URI of '*'."""
     response = cherrypy.response
-    response.headerMap['Content-Type'] = 'text/plain'
+    response.headers['Content-Type'] = 'text/plain'
     
     # OPTIONS is defined in HTTP 1.1 and greater
     request = cherrypy.request
     if request.method == 'OPTIONS' and request.version >= 1.1:
-        response.headerMap['Allow'] = 'HEAD, GET, POST, PUT, OPTIONS'
+        response.headers['Allow'] = 'HEAD, GET, POST, PUT, OPTIONS'
     else:
-        response.headerMap['Allow'] = 'HEAD, GET, POST'
+        response.headers['Allow'] = 'HEAD, GET, POST'
     return ""
 _cpGlobalHandler.exposed = True
 
     return '%02d/%s/%04d:%02d:%02d:%02d' % (
         now.day, month, now.year, now.hour, now.minute, now.second)
 
-def _cpLogAccess():
+def _cp_log_access():
     """ Default method for logging access """
     
     tmpl = '%(h)s %(l)s %(u)s [%(t)s] "%(r)s" %(s)s %(b)s'
                 't': logtime(),
                 'r': cherrypy.request.requestLine,
                 's': cherrypy.response.status.split(" ", 1)[0],
-                'b': cherrypy.response.headerMap.get('Content-Length', '') or "-",
+                'b': cherrypy.response.headers.get('Content-Length', '') or "-",
                 }
     
-    if cherrypy.config.get('server.logToScreen', True):
+    if cherrypy.config.get('server.log_to_screen', True):
         print s
     
-    fname = cherrypy.config.get('server.logAccessFile', '')
+    fname = cherrypy.config.get('server.log_access_file', '')
     if fname:
         f = open(fname, 'ab')
         f.write(s + '\n')
 
 _log_severity_levels = {0: "INFO", 1: "WARNING", 2: "ERROR"}
 
-def _cpLogMessage(msg, context = '', severity = 0):
+def _cp_log_message(msg, context = '', severity = 0):
     """Default method for logging messages (error log).
     
     This is not just for errors! Applications may call this at any time to
     
     s = ' '.join((logtime(), context, level, msg))
     
-    if cherrypy.config.get('server.logToScreen', True):
+    if cherrypy.config.get('server.log_to_screen', True):
         print s
     
-    fname = cherrypy.config.get('server.logFile', '')
+    fname = cherrypy.config.get('server.log_file', '')
     #logdir = os.path.dirname(fname)
     #if logdir and not os.path.exists(logdir):
     #    os.makedirs(logdir)
             kwargs[k] = cgi.escape(kwargs[k])
     
     template = _HTTPErrorTemplate
-    errorPageFile = cherrypy.config.get('errorPage.%s' % code, '')
-    if errorPageFile:
+    error_page_file = cherrypy.config.get('error_page.%s' % code, '')
+    if error_page_file:
         try:
-            template = file(errorPageFile, 'rb').read()
+            template = file(error_page_file, 'rb').read()
         except:
             m = kwargs['message']
             if m:
     return template % kwargs
 
 
-def _cpOnHTTPError(status, message):
-    """ Default _cpOnHTTPError method.
+def _cp_on_http_error(status, message):
+    """ Default _cp_on_http_error method.
     
     status should be an int.
     """
     tb = formatExc()
     logmsg = ""
     
-    if cherrypy.config.get('server.logTracebacks', True):
+    if cherrypy.config.get('server.log_tracebacks', True):
         logmsg = tb
-    if cherrypy.config.get('server.logRequestHeaders', True):
-        h = ["  %s: %s" % (k, v) for k, v in cherrypy.request.headers]
+    if cherrypy.config.get('server.log_request_headers', True):
+        h = ["  %s: %s" % (k, v) for k, v in cherrypy.request.header_list]
         logmsg += 'Request Headers:\n' + '\n'.join(h)
     if logmsg:
         cherrypy.log(logmsg, "HTTP")
     
-    if not cherrypy.config.get('server.showTracebacks', False):
+    if not cherrypy.config.get('server.show_tracebacks', False):
         tb = None
     
     response = cherrypy.response
     for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After",
                 "Vary", "Content-Encoding", "Content-Length", "Expires",
                 "Content-Location", "Content-MD5", "Last-Modified"]:
-        if response.headerMap.has_key(key):
-            del response.headerMap[key]
+        if response.headers.has_key(key):
+            del response.headers[key]
     
     if status != 416:
         # A server sending a response with status code 416 (Requested
         # specifies the current length of the selected resource.
         # A response with status code 206 (Partial Content) MUST NOT
         # include a Content-Range field with a byte-range- resp-spec of "*".
-        if response.headerMap.has_key("Content-Range"):
-            del response.headerMap["Content-Range"]
+        if response.headers.has_key("Content-Range"):
+            del response.headers["Content-Range"]
     
     # In all cases, finalize will be called after this method,
     # so don't bother cleaning up response values here.
     response.status = status
     content = getErrorPage(status, traceback=tb, message=message)
     response.body = content
-    response.headerMap['Content-Length'] = len(content)
-    response.headerMap['Content-Type'] = "text/html"
+    response.headers['Content-Length'] = len(content)
+    response.headers['Content-Type'] = "text/html"
     
     be_ie_unfriendly(status)
 
             # in one chunk or it will still get replaced! Bah.
             content = content + (" " * (s - l))
         response.body = content
-        response.headerMap['Content-Length'] = len(content)
+        response.headers['Content-Length'] = len(content)
+
+def lower_to_camel(s):
+    """Turns lowercase_with_underscore into camelCase."""
+    sp = s.split('_')
+    new_sp = []
+    for i, s in enumerate(sp):
+        if i != 0:
+            s = s[0].upper() + s[1:]
+        new_sp.append(s)
+    return ''.join(new_sp)
 
 def formatExc(exc=None):
     """formatExc(exc=None) -> exc (or sys.exc_info if None), formatted."""
              ('Content-Length', str(len(body)))],
             [body])
 
-def _cpOnError():
-    """ Default _cpOnError method """
+def _cp_on_error():
+    """ Default _cp_on_error method """
     # Allow logging of only *unexpected* HTTPError's.
-    if (not cherrypy.config.get('server.logTracebacks', True)
-        and cherrypy.config.get('server.logUnhandledTracebacks', True)):
+    if (not cherrypy.config.get('server.log_tracebacks', True)
+        and cherrypy.config.get('server.log_unhandled_tracebacks', True)):
         cherrypy.log(formatExc())
     
     cherrypy.HTTPError(500).set_response()
 
 
-_cpFilterList = []
+_cp_filters = []
 

File _cpwsgi.py

View file
     """The WSGI 'application object' for CherryPy."""
     
     # Trap screen output from BaseHTTPRequestHandler.log_message()
-    if not cherrypy.config.get('server.logToScreen'):
+    if not cherrypy.config.get('server.log_to_screen'):
         sys.stderr = NullWriter()
     
     request = None
         response = request.run(requestLine(environ),
                                translate_headers(environ),
                                environ['wsgi.input'])
-        s, h, b = response.status, response.headers, response.body
+        s, h, b = response.status, response.header_list, response.body
         exc = None
     except (KeyboardInterrupt, SystemExit):
         raise
     except:
         tb = _cputil.formatExc()
         cherrypy.log(tb)
-        if not cherrypy.config.get("server.showTracebacks", False):
+        if not cherrypy.config.get("server.show_tracebacks", False):
             tb = ""
         s, h, b = _cputil.bareError(tb)
         exc = sys.exc_info()
     
     def __init__(self, socket, addr, server):
         _cpwsgiserver.HTTPRequest.__init__(self, socket, addr, server)
-        mhs = int(cherrypy.config.get('server.maxRequestHeaderSize',
+        mhs = int(cherrypy.config.get('server.max_request_header_size',
                                       500 * 1024))
         self.rfile = httptools.SizeCheckWrapper(self.rfile, mhs)
     
                     path = "global"
                 else:
                     path = "/" + path
-                mbs = int(cherrypy.config.get('server.maxRequestBodySize',
+                mbs = int(cherrypy.config.get('server.max_request_body_size',
                                               100 * 1024 * 1024, path=path))
                 self.rfile.maxlen = mbs
 
     def __init__(self):
         conf = cherrypy.config.get
         
-        sockFile = cherrypy.config.get('server.socketFile')
+        sockFile = cherrypy.config.get('server.socket_file')
         if sockFile:
             bind_addr = sockFile
         else:
-            bind_addr = (conf("server.socketHost"), conf("server.socketPort"))
+            bind_addr = (conf("server.socket_host"), conf("server.socket_port"))
         
         s = _cpwsgiserver.CherryPyWSGIServer
         s.__init__(self, bind_addr, wsgiApp,
-                   conf("server.threadPool"),
-                   conf("server.socketHost"),
-                   request_queue_size = conf('server.socketQueueSize'),
+                   conf("server.thread_pool"),
+                   conf("server.socket_host"),
+                   request_queue_size = conf('server.socket_queue_size'),
                    )
 

File config.py

View file
 from cherrypy.lib import autoreload, cptools
 
 
-# This configMap dict holds the settings metadata for all cherrypy objects.
+# This configs dict holds the settings metadata for all cherrypy objects.
 # Keys are URL paths, and values are dicts.
-configMap = {}
+configs = {}
+configMap = configs # Backward compatibility
 
-defaultGlobal = {
-    'server.socketPort': 8080,
-    'server.socketHost': '',
-    'server.socketFile': '',
-    'server.socketQueueSize': 5,
-    'server.protocolVersion': 'HTTP/1.0',
-    'server.logToScreen': True,
-    'server.logTracebacks': True,
-    'server.logFile': '',
-    'server.reverseDNS': False,
-    'server.threadPool': 0,
+default_global = {
+    'server.socket_port': 8080,
+    'server.socket_host': '',
+    'server.socket_file': '',
+    'server.socket_queue_size': 5,
+    'server.protocol_version': 'HTTP/1.0',
+    'server.log_to_screen': True,
+    'server.log_tracebacks': True,
+    'server.log_file': '',
+    'server.reverse_dns': False,
+    'server.thread_pool': 0,
     'server.environment': "development",
     }
 
 environments = {
     "development": {
         'autoreload.on': True,
-        'logDebugInfoFilter.on': True,
-        'server.logFileNotFound': True,
-        'server.showTracebacks': True,
-        'server.logRequestHeaders': True,
+        'log_debug_info_filter.on': True,
+        'server.log_file_not_found': True,
+        'server.show_tracebacks': True,
+        'server.log_request_headers': True,
         },
     "staging": {
         'autoreload.on': False,
-        'logDebugInfoFilter.on': False,
-        'server.logFileNotFound': False,
-        'server.showTracebacks': False,
-        'server.logRequestHeaders': False,
+        'log_debug_info_filter.on': False,
+        'server.log_file_not_found': False,
+        'server.show_tracebacks': False,
+        'server.log_request_headers': False,
         },
     "production": {
         'autoreload.on': False,
-        'logDebugInfoFilter.on': False,
-        'server.logFileNotFound': False,
-        'server.showTracebacks': False,
-        'server.logRequestHeaders': False,
+        'log_debug_info_filter.on': False,
+        'server.log_file_not_found': False,
+        'server.show_tracebacks': False,
+        'server.log_request_headers': False,
         },
     }
 
 def update(updateMap=None, file=None, overwrite=True):
-    """Update configMap from a dictionary or a config file.
+    """Update configs from a dictionary or a config file.
     
     If overwrite is False then the update will not modify values
-    already defined in the configMap.
+    already defined in the configs.
     """
     if updateMap is None:
         updateMap = {}
         updateMap = updateMap.copy()
         updateMap.update(dict_from_config_file(file))
     
-    # Load new conf into cherrypy.configMap
+    # Load new conf into cherrypy.configs
     for section, valueMap in updateMap.iteritems():
         # Handle shortcut syntax for "global" section
-        #   example: update({'server.socketPort': 80})
+        #   example: update({'server.socket_port': 80})
         if not isinstance(valueMap, dict):
             valueMap = {section: valueMap}
             section = 'global'
         
-        bucket = configMap.setdefault(section, {})
+        bucket = configs.setdefault(section, {})
         if overwrite:
             bucket.update(valueMap)
         else:
 
 def reset(useDefaults=True):
     """Clear configuration and restore defaults"""
-    configMap.clear()
+    configs.clear()
     if useDefaults:
-        update(defaultGlobal)
+        update(default_global)
 reset()
 
-def get(key, defaultValue=None, returnSection=False, path = None):
+def get(key, default_value=None, return_section=False, path = None):
     """Return the configuration value corresponding to key
-    If specified, return defaultValue on lookup failure. If returnSection is
+    If specified, return default_value on lookup failure. If return_section is
     specified, return the path to the value, instead of the value itself.
     """
     # Look, ma, no Python function calls! Uber-fast.
             path = "/"
         
         try:
-            result = configMap[path][key]
+            result = configs[path][_cputil.lower_to_camel(key)]
             break
         except KeyError:
+            try:
+                result = configs[path][key]
+                break
+            except KeyError:
+                pass
             pass
         
         try:
             # Check for a server.environment entry at this node.
-            env = configMap[path]["server.environment"]
-            result = environments[env][key]
+            env = configs[path]["server.environment"]
+            # For backward compatibility, check for camelCase key first
+            result = environments[env][_cputil.lower_to_camel(key)]
             break
         except KeyError:
+            try:
+                env = configs[path]["server.environment"]
+                result = environments[env][key]
+                break
+            except KeyError:
+                pass
             pass
         
         if path == "global":
-            result = defaultValue
+            result = default_value
             break
         
         # Move one node up the tree and try again.
         else:
             path = path[:path.rfind("/")]
     
-    if returnSection:
+    if return_section:
         return path
     else:
         return result
     # Needed by the session filter
     
     try:
-        results = [('global', configMap['global'][key])]
+        results = [('global', configs['global'][key])]
     except KeyError:
         results = []
     
     for n in xrange(1, len(pathList)):
         path = '/' + '/'.join(pathList[0:n+1])
         try:
-            results.append((path, configMap[path][key]))
+            results.append((path, configs[path][key]))
         except KeyError:
             pass
     
     
     serverVars = [
                   'server.environment',
-                  'server.logToScreen',
-                  'server.logFile',
-                  'server.logTracebacks',
-                  'server.logRequestHeaders',
-                  'server.protocolVersion',
-                  'server.socketHost',
-                  'server.socketPort',
-                  'server.socketFile',
-                  'server.reverseDNS',
-                  'server.socketQueueSize',
-                  'server.threadPool',
+                  'server.log_to_screen',
+                  'server.log_file',
+                  'server.log_tracebacks',
+                  'server.log_request_headers',
+                  'server.protocol_version',
+                  'server.socket_host',
+                  'server.socket_port',
+                  'server.socket_file',
+                  'server.reverse_dns',
+                  'server.socket_queue_size',
+                  'server.thread_pool',
                  ]
 
     for var in serverVars:

File filters/__init__.py

View file
     'CacheFilter',
 ]
 
-_input_methods = ['onStartResource', 'beforeRequestBody', 'beforeMain']
-_output_methods = ['beforeFinalize', 'onEndResource', 'onEndRequest',
-                   'beforeErrorResponse', 'afterErrorResponse']
+_input_methods = ['on_start_resource', 'onStartResource',
+        'before_request_body', 'beforeRequestBody',
+        'before_main', 'beforeMain']
+_output_methods = ['before_finalize', 'beforeFinalize',
+        'on_end_resource', 'onEndResource',
+        'on_end_request', 'onEndRequest',
+        'before_error_response', 'beforeErrorResponse',
+        'after_error_response', 'afterErrorResponse']
 
 
 def init():
 _filterhooks = {}
 
 
-def applyFilters(methodName):
+def applyFilters(method_name, alternate_method_name = None):
     """Execute the given method for all registered filters."""
     special_methods = []
-    for f in _cputil.getSpecialAttribute("_cpFilterList"):
-        method = getattr(f, methodName, None)
+    for f in _cputil.get_special_attribute("_cp_filters", "_cpFilterList"):
+        method = getattr(f, method_name, None)
+        if (method is None) and alternate_method_name:
+            # alternate_method_name is for backward compatibility
+            method = getattr(f, alternate_method_name, None)
         if method:
             special_methods.append(method)
     
-    if methodName in _input_methods:
+    if method_name in _input_methods:
         # Run special filters after defaults.
-        for method in _filterhooks[methodName] + special_methods:
+        for method in _filterhooks[method_name] + special_methods:
             method()
     else:
         # Run special filters before defaults.
-        for method in special_methods + _filterhooks[methodName]:
+        for method in special_methods + _filterhooks[method_name]:
             method()

File filters/basefilter.py

View file
     override some of the methods to add some side-effects.
     """
     
-    def onStartResource(self):
+    def on_start_resource(self):
         """Called before any request processing has been done"""
         pass
     
-    def beforeRequestBody(self):
+    def before_request_body(self):
         """Called after the request header has been read/parsed"""
         pass
     
-    def beforeMain(self):
+    def before_main(self):
         """ Called after the request body has been read/parsed"""
         pass
     
-    def beforeFinalize(self):
+    def before_finalize(self):
         """Called before final output processing"""
         pass
     
-    def beforeErrorResponse(self):
-        """Called before _cpOnError and/or finalizing output"""
+    def before_error_response(self):
+        """Called before _cp_on_error and/or finalizing output"""
         pass
     
-    def afterErrorResponse(self):
-        """Called after _cpOnError and finalize"""
+    def after_error_response(self):
+        """Called after _cp_on_error and finalize"""
         pass
     
-    def onEndResource(self):
+    def on_end_resource(self):
         """Called after finalizing the output (status, header, and body)"""
         pass
     
-    def onEndRequest(self):
+    def on_end_request(self):
         """Called when the server closes the request."""
         pass
 

File filters/baseurlfilter.py

View file
     Useful when running a CP server behind Apache.
     """
     
-    def beforeRequestBody(self):
-        if not cherrypy.config.get('baseUrlFilter.on', False):
+    def before_request_body(self):
+        if not cherrypy.config.get('base_url_filter.on', False):
             return
         
         request = cherrypy.request
-        newBaseUrl = cherrypy.config.get('baseUrlFilter.baseUrl', 'http://localhost')
-        if cherrypy.config.get('baseUrlFilter.useXForwardedHost', True):
-            newBaseUrl = request.headerMap.get("X-Forwarded-Host", newBaseUrl)
+        newBaseUrl = cherrypy.config.get('base_url_filter.base_url', 'http://localhost')
+        if cherrypy.config.get('base_url_filter.use_x_forwarded_host', True):
+            newBaseUrl = request.headers.get("X-Forwarded-Host", newBaseUrl)
         
         if newBaseUrl.find("://") == -1:
             # add http:// or https:// if needed

File filters/cachefilter.py

View file
     If the page is not in the cache, caches the output.
     """
     
-    CacheClass = property(lambda self: cherrypy.config.get("cacheFilter.cacheClass", MemoryCache))
-    key = property(lambda self: cherrypy.config.get("cacheFilter.key", defaultCacheKey))
-    delay = property(lambda self: cherrypy.config.get("cacheFilter.delay", 600))
-    maxobjsize = property(lambda self: cherrypy.config.get("cacheFilter.maxobjsize", 100000))
-    maxsize = property(lambda self: cherrypy.config.get("cacheFilter.maxsize", 10000000))
-    maxobjects = property(lambda self: cherrypy.config.get("cacheFilter.maxobjects", 1000))
+    CacheClass = property(lambda self: cherrypy.config.get("cache_filter.cacheClass", MemoryCache))
+    key = property(lambda self: cherrypy.config.get("cache_filter.key", defaultCacheKey))
+    delay = property(lambda self: cherrypy.config.get("cache_filter.delay", 600))
+    maxobjsize = property(lambda self: cherrypy.config.get("cache_filter.maxobjsize", 100000))
+    maxsize = property(lambda self: cherrypy.config.get("cache_filter.maxsize", 10000000))
+    maxobjects = property(lambda self: cherrypy.config.get("cache_filter.maxobjects", 1000))
     
-    def beforeMain(self):
-        if not cherrypy.config.get('cacheFilter.on', False):
+    def before_main(self):
+        if not cherrypy.config.get('cache_filter.on', False):
             return
         
         if not hasattr(cherrypy, '_cache'):
         if cacheData:
             # found a hit! check the if-modified-since request header
             expirationTime, lastModified, obj = cacheData
-            modifiedSince = cherrypy.request.headerMap.get('If-Modified-Since', None)
+            modifiedSince = cherrypy.request.headers.get('If-Modified-Since', None)
             if modifiedSince is not None and modifiedSince == lastModified:
                 cherrypy._cache.totNonModified += 1
                 cherrypy.response.status = "304 Not Modified"
                 cherrypy.response.body = body
             raise cherrypy.RequestHandled()
     
-    def beforeFinalize(self):
-        if not (cherrypy.config.get('cacheFilter.on', False) and
+    def before_finalize(self):
+        if not (cherrypy.config.get('cache_filter.on', False) and
                 cherrypy.request.cacheable):
             return
         
                 yield chunk
         cherrypy.response.body = tee(cherrypy.response.body)
     
-    def onEndRequest(self):
+    def on_end_request(self):
         # Close & fix the cache entry after content was fully written
-        if not (cherrypy.config.get('cacheFilter.on', False) and
+        if not (cherrypy.config.get('cache_filter.on', False) and
                 cherrypy.request.cacheable):
             return
         
         headers = response.headers
         body = ''.join([chunk for chunk in response._cachefilter_tee])
         
-        if response.headerMap.get('Pragma', None) != 'no-cache':
-            lastModified = response.headerMap.get('Last-Modified', None)
+        if response.headers.get('Pragma', None) != 'no-cache':
+            lastModified = response.headers.get('Last-Modified', None)
             # saves the cache data
             cherrypy._cache.put(lastModified, (status, headers, body))
 
 class CacheStats:
     
     def index(self):
-        cherrypy.response.headerMap['Content-Type'] = 'text/plain'
-        cherrypy.response.headerMap['Pragma'] = 'no-cache'
+        cherrypy.response.headers['Content-Type'] = 'text/plain'
+        cherrypy.response.headers['Pragma'] = 'no-cache'
         cache = cherrypy._cache
         yield "Cache statistics\n"
         yield "Maximum object size: %s\n" % formatSize(cache.maxobjsize)

File filters/decodingfilter.py

View file
 class DecodingFilter(BaseFilter):
     """Automatically decodes request parameters (except uploads)."""
     
-    def beforeMain(self):
-        if not cherrypy.config.get('decodingFilter.on', False):
+    def before_main(self):
+        if not cherrypy.config.get('decoding_filter.on', False):
             return
         
-        enc = cherrypy.config.get('decodingFilter.encoding', 'utf-8')
-        for key, value in cherrypy.request.paramMap.items():
+        enc = cherrypy.config.get('decoding_filter.encoding', 'utf-8')
+        for key, value in cherrypy.request.params.items():
             if hasattr(value, 'file'):
                 # This is a file being uploaded: skip it
                 continue
             else:
                 # value is a regular string: decode it
                 newValue = value.decode(enc)
-            cherrypy.request.paramMap[key] = newValue
+            cherrypy.request.params[key] = newValue
 

File filters/encodingfilter.py

View file
         
         failmsg = "The response could not be encoded with %s"
         
-        enc = conf('encodingFilter.encoding', None)
+        enc = conf('encoding_filter.encoding', None)
         if enc is not None:
             # If specified, force this encoding to be used, or fail.
             if encode_body(enc):
         
         # Parse the Accept_Charset request header, and try to provide one
         # of the requested charsets (in order of user preference).
-        default_enc = conf('encodingFilter.defaultEncoding', 'utf-8')
+        default_enc = conf('encoding_filter.default_encoding', 'utf-8')
         
-        encs = cherrypy.request.headerMap.elements('Accept-Charset')
+        encs = cherrypy.request.headers.elements('Accept-Charset')
         if encs is None:
             # Any character-set is acceptable.
             if encode_body(default_enc):
         # No suitable encoding found.
         raise cherrypy.HTTPError(406)
     
-    def beforeFinalize(self):
+    def before_finalize(self):
         conf = cherrypy.config.get
-        if not conf('encodingFilter.on', False):
+        if not conf('encoding_filter.on', False):
             return
         
-        ct = cherrypy.response.headerMap.elements("Content-Type")
+        ct = cherrypy.response.headers.elements("Content-Type")
         if ct is not None:
             ct = ct[0]
             if ct.value.lower().startswith("text/"):
                 # Set "charset=..." param on response Content-Type header
                 ct.params['charset'] = self.find_acceptable_charset()
-                cherrypy.response.headerMap["Content-Type"] = str(ct)
+                cherrypy.response.headers["Content-Type"] = str(ct)
 

File filters/gzipfilter.py

View file
 class GzipFilter(BaseFilter):
     """Filter that gzips the response."""
     
-    def beforeFinalize(self):
-        if not cherrypy.config.get('gzipFilter.on', False):
+    def before_finalize(self):
+        if not cherrypy.config.get('gzip_filter.on', False):
             return
         
         response = cherrypy.response
         
         def zipit():
             # Return a generator that compresses the page
-            varies = response.headerMap.get("Vary", "")
+            varies = response.headers.get("Vary", "")
             varies = [x.strip() for x in varies.split(",") if x.strip()]
             if "Accept-Encoding" not in varies:
                 varies.append("Accept-Encoding")
-            response.headerMap['Vary'] = ", ".join(varies)
+            response.headers['Vary'] = ", ".join(varies)
             
-            response.headerMap['Content-Encoding'] = 'gzip'
-            level = cherrypy.config.get('gzipFilter.compresslevel', 9)
+            response.headers['Content-Encoding'] = 'gzip'
+            level = cherrypy.config.get('gzip_filter.compresslevel', 9)
             response.body = self.zip_body(response.body, level)
         
         from cherrypy.lib import httptools
-        acceptable = cherrypy.request.headerMap.elements('Accept-Encoding')
+        acceptable = cherrypy.request.headers.elements('Accept-Encoding')
         if acceptable is None:
             # If no Accept-Encoding field is present in a request,
             # the server MAY assume that the client will accept any
             # to the client.
             return
         
-        ct = response.headerMap.get('Content-Type').split(';')[0]
-        ct = ct in cherrypy.config.get('gzipFilter.mimeTypeList', ['text/html'])
+        ct = response.headers.get('Content-Type').split(';')[0]
+        ct = ct in cherrypy.config.get('gzip_filter.mime_types', ['text/html'])
         for coding in acceptable:
             if coding.value == 'identity' and coding.qvalue != 0:
                 return

File filters/logdebuginfofilter.py

View file
 class LogDebugInfoFilter(BaseFilter):
     """Filter that adds debug information to the page"""
     
-    def onStartResource(self):
+    def on_start_resource(self):
         cherrypy.request.startBuilTime = time.time()
     
-    def beforeFinalize(self):
-        if not cherrypy.config.get('logDebugInfoFilter.on', False):
+    def before_finalize(self):
+        if not cherrypy.config.get('log_debug_info_filter.on', False):
             return
         
-        mimelist = cherrypy.config.get('logDebugInfoFilter.mimeTypeList', ['text/html'])
-        ct = cherrypy.response.headerMap.get('Content-Type').split(';')[0]
+        mimelist = cherrypy.config.get('log_debug_info_filter.mime_types', ['text/html'])
+        ct = cherrypy.response.headers.get('Content-Type').split(';')[0]
         if ct in mimelist:
             body = cherrypy.response.collapse_body()
             debuginfo = '\n'
             
-            logAsComment = cherrypy.config.get('logDebugInfoFilter.logAsComment', False)
+            logAsComment = cherrypy.config.get('log_debug_info_filter.log_as_comment', False)
             if logAsComment:
                 debuginfo += '<!-- '
             else:
                 debuginfo += "<br/><br/>"
             logList = []
             
-            if cherrypy.config.get('logDebugInfoFilter.logBuildTime', True):
+            if cherrypy.config.get('log_debug_info_filter.log_build_time', True):
                 logList.append("Build time: %.03fs" % (
                     time.time() - cherrypy.request.startBuilTime))
             
-            if cherrypy.config.get('logDebugInfoFilter.logPageSize', True):
+            if cherrypy.config.get('log_debug_info_filter.log_page_size', True):
                 logList.append("Page size: %.02fKB" % (
                     len(body)/float(1024)))
             ''' 
             # this is not compatible with the session filter
-            if (cherrypy.config.get('logDebugInfoFilter.logSessionSize', True)
+            if (cherrypy.config.get('log_debug_info_filter.log_session_size', True)
                 and cherrypy.config.get('session.storageType')):
                 # Pickle session data to get its size
                 try:

File filters/nsgmlsfilter.py

View file
     """Filter that runs the response through Nsgmls.
     """
     
-    def beforeFinalize(self):
-        if not cherrypy.config.get('nsgmlsFilter.on', False):
+    def before_finalize(self):
+        if not cherrypy.config.get('nsgmls_filter.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 = cherrypy.response.collapse_body()
         
-        fct = cherrypy.response.headerMap.get('Content-Type', '')
+        fct = cherrypy.response.headers.get('Content-Type', '')
         ct = fct.split(';')[0]
         encoding = ''
         i = fct.find('charset=')
         if i != -1:
             encoding = fct[i+8:]
         if ct == 'text/html':
-            tmpdir = cherrypy.config.get('nsgmlsFilter.tmpDir')
+            tmpdir = cherrypy.config.get('nsgmls_filter.tmp_dir')
             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 = cherrypy.config.get('nsgmlsFilter.nsgmlsPath')
-            catalogPath = cherrypy.config.get('nsgmlsFilter.catalogPath')
+            nsgmlsPath = cherrypy.config.get('nsgmls_filter.nsgmls_path')
+            catalogPath = cherrypy.config.get('nsgmls_filter.catalog_path')
             command = '%s -c%s -f%s -s -E10 %s' % (
                 nsgmlsPath, catalogPath, errFile, pageFile)
             command = command.replace('\\', '/')
             newErrList = []
             for err in errList:
                 ignore = False
-                for errIgn in cherrypy.config.get('nsgmlsFilter.errorsToIgnore', []):
+                for errIgn in cherrypy.config.get('nsgmls_filter.errors_to_ignore', []):
                     if err.find(errIgn) != -1:
                         ignore = True
                         break

File filters/sessionauthenticatefilter.py

View file
     Filter allows for simple forms based authentication and access control
     """
     
-    def beforeMain(self):
-        if not cherrypy.config.get('sessionAuthenticateFilter.on', False):
+    def before_main(self):
+        if not cherrypy.config.get('session_authenticate_filter.on', False):
             return
         
         
-        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')
-        sessionKey = cherrypy.config.get('sessionAuthenticateFilter.sessionKey', 'username')
+        checkLoginAndPassword = cherrypy.config.get('session_authenticate_filter.check_login_and_password', defaultCheckLoginAndPassword)
+        loginScreen = cherrypy.config.get('session_authenticate_filter.login_screen', defaultLoginScreen)
+        notLoggedIn = cherrypy.config.get('session_authenticate_filter.not_logged_in')
+        loadUserByUsername = cherrypy.config.get('session_authenticate_filter.load_user_by_username')
+        sessionKey = cherrypy.config.get('session_authenticate_filter.session_key', 'username')
 
         if cherrypy.request.path.endswith('loginScreen'):
             return
         elif cherrypy.request.path.endswith('doLogout'):
             cherrypy.session[sessionKey] = None
             cherrypy.request.user = None
-            fromPage = cherrypy.request.paramMap.get('fromPage', '..')
+            fromPage = cherrypy.request.params.get('fromPage', '..')
             raise cherrypy.HTTPRedirect(fromPage)
         elif cherrypy.request.path.endswith('doLogin'):
-            fromPage = cherrypy.request.paramMap.get('fromPage', '..')
-            login = cherrypy.request.paramMap['login']
-            password = cherrypy.request.paramMap['password']
+            fromPage = cherrypy.request.params.get('fromPage', '..')
+            login = cherrypy.request.params['login']
+            password = cherrypy.request.params['password']
             errorMsg = checkLoginAndPassword(login, password)
             if errorMsg:
                 cherrypy.response.body = loginScreen(fromPage, login = login, errorMsg = errorMsg)

File filters/sessionfilter.py

View file
     - sess.expirationTime: date/time when the current session will expire
 
 Global variables (RAM backend only):
-    - cherrypy._sessionLockDict: dictionary containing the locks for all sessionIDs
+    - cherrypy._session_lock_dict: dictionary containing the locks for all sessionIDs
     - cherrypy._sessionHolder: dictionary containing the data for all sessions
 
 """
 
 
 class SessionNotEnabledError(Exception):
-    """ User forgot to set sessionFilter.on to True """
+    """ User forgot to set session_filter.on to True """
     pass
 
 
 class SessionFilter(basefilter.BaseFilter):
     
-    def beforeRequestBody(self):
+    def before_request_body(self):
         conf = cherrypy.config.get
         
         cherrypy.request._session = EmptyClass()
         sess = cherrypy.request._session
         now = datetime.datetime.now()
-        # Dont enable session if sessionFilter is off or if this is a
+        # Dont enable session if session_filter is off or if this is a
         #   request for static data
-        if ((not conf('sessionFilter.on', False))
-              or conf('staticFilter.on', False)):
+        if ((not conf('session_filter.on', False))
+              or conf('static_filter.on', False)):
             sess.sessionStorage = None
             return
         
         sess.locked = False # Not locked by default
         
         # Read config options
-        sess.sessionTimeout = conf('sessionFilter.timeout', 60)
-        sess.sessionLocking = conf('sessionFilter.locking', 'explicit')
-        sess.onCreateSession = conf('sessionFilter.onCreateSession',
+        sess.sessionTimeout = conf('session_filter.timeout', 60)
+        sess.sessionLocking = conf('session_filter.locking', 'explicit')
+        sess.onCreateSession = conf('session_filter.on_create_session',
                                     lambda data: None)
-        sess.onDeleteSession = conf('sessionFilter.onDeleteSession',
+        sess.onDeleteSession = conf('session_filter.on_delete_session',
                                     lambda data: None)
         
-        cleanUpDelay = conf('sessionFilter.cleanUpDelay', 5)
+        cleanUpDelay = conf('session_filter.clean_up_delay', 5)
         cleanUpDelay = datetime.timedelta(seconds = cleanUpDelay * 60)
         
-        cookieName = conf('sessionFilter.cookieName', 'sessionID')
-        sess.deadlockTimeout = conf('sessionFilter.deadlockTimeout', 30)
+        cookieName = conf('session_filter.cookie_name', 'sessionID')
+        sess.deadlockTimeout = conf('session_filter.deadlock_timeout', 30)
         
-        storage = conf('sessionFilter.storageType', 'Ram')
+        storage = conf('session_filter.storage_type', 'Ram')
         storage = storage[0].upper() + storage[1:]
         
         # People can set their own custom class
-        #   through sessionFilter.storageClass
-        sess.sessionStorage = conf('sessionFilter.storageClass', None)
+        #   through session_filter.storage_class
+        sess.sessionStorage = conf('session_filter.storage_class', None)
         if sess.sessionStorage is None:
             sess.sessionStorage = globals()[storage + 'Storage']()
         else:
             sess.sessionStorage = sess.sessionStorage()
         
         # Check if we need to clean up old sessions
-        if cherrypy._sessionLastCleanUpTime + cleanUpDelay < now:
-            sess.sessionStorage.cleanUp()
+        if cherrypy._session_last_clean_up_time + cleanUpDelay < now:
+            sess.sessionStorage.clean_up()
         
         # Check if request came with a session ID
         if cookieName in cherrypy.request.simpleCookie:
             # If using implicit locking, acquire lock
             if sess.sessionLocking == 'implicit':
                 sess.sessionData = {'_id': sess.sessionID}
-                sess.sessionStorage.acquireLock()
+                sess.sessionStorage.acquire_lock()
             
             data = sess.sessionStorage.load(sess.sessionID)
             # data is either None or a tuple (sessionData, expirationTime)
         cookie[cookieName]['max-age'] = sess.sessionTimeout * 60
         cookie[cookieName]['version'] = 1
     
-    def beforeFinalize(self):
+    def before_finalize(self):
         def saveData(body, sess):
             # If the body is a generator, we have to save the data
             #   *after* the generator has been consumed
                                      expirationTime)
             if sess.locked:
                 # Always release the lock if the user didn't release it
-                sess.sessionStorage.releaseLock()
+                sess.sessionStorage.release_lock()
             
             # If the body is not a generator, we save the data
             #   before the body is returned
         #   either before or after the body is returned
         cherrypy.response.body = saveData(cherrypy.response.body, sess)
     
-    def onEndRequest(self):
+    def on_end_request(self):
         sess = cherrypy.request._session
         if not getattr(sess, 'sessionStorage', None):
             # Sessions are not enabled: do nothing
             return
         if getattr(sess, 'locked', None):
             # If the session is still locked we release the lock
-            sess.sessionStorage.releaseLock()
+            sess.sessionStorage.release_lock()
         if getattr(sess, 'sessionStorage', None):
             del sess.sessionStorage
 
     """ Implementation of the RAM backend for sessions """
     
     def load(self, id):
-        return cherrypy._sessionDataHolder.get(id)
+        return cherrypy._session_data_holder.get(id)
     
     def save(self, id, data, expirationTime):
-        cherrypy._sessionDataHolder[id] = (data, expirationTime)
+        cherrypy._session_data_holder[id] = (data, expirationTime)
     
-    def acquireLock(self):
+    def acquire_lock(self):
         sess = cherrypy.request._session
         id = cherrypy.session['_id']
-        lock = cherrypy._sessionLockDict.get(id)
+        lock = cherrypy._session_lock_dict.get(id)
         if lock is None:
             lock = threading.Lock()
-            cherrypy._sessionLockDict[id] = lock
+            cherrypy._session_lock_dict[id] = lock
         startTime = time.time()
         while True:
             if lock.acquire(False):
             time.sleep(0.5)
         sess.locked = True
     
-    def releaseLock(self):
+    def release_lock(self):
         sess = cherrypy.request._session
         id = cherrypy.session['_id']
-        cherrypy._sessionLockDict[id].release()
+        cherrypy._session_lock_dict[id].release()
         sess.locked = False
     
-    def cleanUp(self):
+    def clean_up(self):
         sess = cherrypy.request._session
         toBeDeleted = []
         now = datetime.datetime.now()
-        for id, (data, expirationTime) in cherrypy._sessionDataHolder.iteritems():
+        for id, (data, expirationTime) in cherrypy._session_data_holder.iteritems():
             if expirationTime < now:
                 toBeDeleted.append(id)
         for id in toBeDeleted:
-            sess.onDeleteSession(cherrypy._sessionDataHolder[id])
-            del cherrypy._sessionDataHolder[id]
+            sess.onDeleteSession(cherrypy._session_data_holder[id])
+            del cherrypy._session_data_holder[id]
 
 
 class FileStorage:
         pickle.dump((data, expirationTime), f)
         f.close()
     
-    def acquireLock(self):
+    def acquire_lock(self):
         sess = cherrypy.request._session
         filePath = self._getFilePath(cherrypy.session['_id'])
         lockFilePath = filePath + self.LOCK_SUFFIX
         self._lockFile(lockFilePath)
         sess.locked = True
     
-    def releaseLock(self):
+    def release_lock(self):
         sess = cherrypy.request._session
         filePath = self._getFilePath(cherrypy.session['_id'])
         lockFilePath = filePath + self.LOCK_SUFFIX
         self._unlockFile(lockFilePath)
         sess.locked = False
     
-    def cleanUp(self):
+    def clean_up(self):
         sess = cherrypy.request._session
-        storagePath = cherrypy.config.get('sessionFilter.storagePath')
+        storagePath = cherrypy.config.get('session_filter.storage_path')
         now = datetime.datetime.now()
         # Iterate over all files in the dir/ and exclude non session files
         #   and lock files
                 self._unlockFile(lockFilePath)
     
     def _getFilePath(self, id):
-        storagePath = cherrypy.config.get('sessionFilter.storagePath')
+        storagePath = cherrypy.config.get('session_filter.storage_path')
         fileName = self.SESSION_PREFIX + id
         filePath = os.path.join(storagePath, fileName)
         return filePath
     """
     
     def __init__(self):
-        self.db = cherrypy.config.get('sessionFilter.getDB')()
+        self.db = cherrypy.config.get('session_filter.get_db')()
         self.cursor = self.db.cursor()
     
     def __del__(self):
             'insert into session (id, data, expiration_time) values (%s, %s, %s)',
             (id, pickled_data, expirationTime))
     
-    def acquireLock(self):
+    def acquire_lock(self):
         # We use the "for update" clause to lock the row
         self.cursor.execute(
             'select id from session where id=%s for update',
             (cherrypy.session['_id'],))
     
-    def releaseLock(self):
+    def release_lock(self):
         # We just close the cursor and that will remove the lock
         #   introduced by the "for update" clause
         self.cursor.close()
         self.cursor = None
     
-    def cleanUp(self):
+    def clean_up(self):
         sess = cherrypy.request._session
         now = datetime.datetime.now()
         self.cursor.execute(
             raise SessionNotEnabledError()
         # Create thread-specific dictionary if needed
         sess.sessionData = getattr(sess, 'sessionData', {})
-        if name == 'acquireLock':
-            return sess.sessionStorage.acquireLock
-        elif name == 'releaseLock':
-            return sess.sessionStorage.releaseLock
+        if name == 'acquire_lock':
+            return sess.sessionStorage.acquire_lock
+        elif name == 'release_lock':
+            return sess.sessionStorage.release_lock
         return getattr(sess.sessionData, name)
 

File filters/staticfilter.py

View file
 class StaticFilter(BaseFilter):
     """Filter that handles static content."""
     
-    def beforeMain(self):
+    def before_main(self):
         config = cherrypy.config
-        if not config.get('staticFilter.on', False):
+        if not config.get('static_filter.on', False):
             return
         
         request = cherrypy.request
         path = request.objectPath
         
-        regex = config.get('staticFilter.match', '')
+        regex = config.get('static_filter.match', '')
         if regex:
             import re
             if not re.search(regex, path):
                 return
         
-        filename = config.get('staticFilter.file')
+        filename = config.get('static_filter.file')
         if not filename:
-            staticDir = config.get('staticFilter.dir')
-            section = config.get('staticFilter.dir', returnSection=True)
+            staticDir = config.get('static_filter.dir')
+            section = config.get('static_filter.dir', return_section=True)
             if section == 'global':
                 section = "/"
             section = section.rstrip(r"\/")
         
         # If filename is relative, make absolute using "root".
         if not os.path.isabs(filename):
-            root = config.get('staticFilter.root', '').rstrip(r"\/")
+            root = config.get('static_filter.root', '').rstrip(r"\/")
             if root:
                 filename = os.path.join(root, filename)
         

File filters/tidyfilter.py

View file
     server would also crash)
     """
     
-    def beforeFinalize(self):
-        if not cherrypy.config.get('tidyFilter.on', False):
+    def before_finalize(self):
+        if not cherrypy.config.get('tidy_filter.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 = cherrypy.response.collapse_body()
         
-        fct = cherrypy.response.headerMap.get('Content-Type', '')
+        fct = cherrypy.response.headers.get('Content-Type', '')
         ct = fct.split(';')[0]
         encoding = ''
         i = fct.find('charset=')
         if i != -1:
             encoding = fct[i+8:]
         if ct == 'text/html':
-            tmpdir = cherrypy.config.get('tidyFilter.tmpDir')
+            tmpdir = cherrypy.config.get('tidy_filter.tmp_dir')
             pageFile = os.path.join(tmpdir, 'page.html')
             outFile = os.path.join(tmpdir, 'tidy.out')
             errFile = os.path.join(tmpdir, 'tidy.err')
                 tidyEncoding = '-' + tidyEncoding
             
             strictXml = ""
-            if cherrypy.config.get('tidyFilter.strictXml', False):
+            if cherrypy.config.get('tidy_filter.strict_xml', False):
                 strictXml = ' -xml'
             os.system('"%s" %s%s -f %s -o %s %s' %
-                      (cherrypy.config.get('tidyFilter.tidyPath'), tidyEncoding,
+                      (cherrypy.config.get('tidy_filter.tidy_path'), tidyEncoding,
                        strictXml, errFile, outFile, pageFile))
             f = open(errFile, 'rb')
             err = f.read()
             for err in errList:
                 if (err.find('Warning') != -1 or err.find('Error') != -1):
                     ignore = 0
-                    for errIgn in cherrypy.config.get('encodingFilter.errorsToIgnore', []):
+                    for errIgn in cherrypy.config.get('tidy_filter.errors_to_ignore', []):
                         if err.find(errIgn) != -1:
                             ignore = 1
                             break

File filters/xmlrpcfilter.py

View file
 ##        longString.exposed = True
 ##
 ##    cherrypy.root = Root()
-##    cherrypy.config.update({'xmlRpcFilter.on': True,
-##                            'socketPort': 9001,
-##                            'threadPool':0,
-##                            'socketQueueSize':10 })
+##    cherrypy.config.update({'xmlrpc_filter.on': True,
+##                            'socket_port': 9001,
+##                            'thread_pool':0,
+##                            'socket_queue_size':10 })
 ##    if __name__=='__main__':
 ##        cherrypy.server.start()
 ##
     
     PLEASE NOTE:
     
-    beforeRequestBody:
+    before_request_body:
         Unmarshalls the posted data to a methodname and parameters.
         - These are stored in cherrypy.request.rpcMethod and .rpcParams
         - The method is also stored in cherrypy.request.objectPath,
           so CP2 will find the right method to call for you,
           based on the root's position.
-    beforeMain:
+    before_main:
         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
     
     def testValidityOfRequest(self):
         # test if the content-length was sent
-        length = cherrypy.request.headerMap.get('Content-Length') or 0
-        ct = cherrypy.request.headerMap.get('Content-Type') or 'text/xml'
+        length = cherrypy.request.headers.get('Content-Length') or 0
+        ct = cherrypy.request.headers.get('Content-Type') or 'text/xml'
         return int(length) > 0 and ct.lower() in ['text/xml']
     
-    def beforeRequestBody(self):
+    def before_request_body(self):
         """ Called after the request header has been read/parsed"""
         request = cherrypy.request
         
-        request.xmlRpcFilterOn = cherrypy.config.get('xmlRpcFilter.on', False)
-        if not request.xmlRpcFilterOn:
+        request.xmlrpc_filter_on = cherrypy.config.get('xmlrpc_filter.on', False)
+        if not request.xmlrpc_filter_on:
             return
         
-        request.isRPC = self.testValidityOfRequest()
-        if not request.isRPC: 
+        request.is_rpc = self.testValidityOfRequest()
+        if not request.is_rpc: 
             return
         
         request.processRequestBody = False
-        dataLength = int(request.headerMap.get('Content-Length') or 0)
+        dataLength = int(request.headers.get('Content-Length') or 0)
         data = request.rfile.read(dataLength)
         try:
             params, method = xmlrpclib.loads(data)
         request.objectPath += str(method).replace('.', '/')
         request.paramList = list(params)
     
-    def beforeMain(self):
+    def before_main(self):
         """This is a variation of main() from _cphttptools.
         
         It is redone here because:
             2. we need to pass our own paramList
         """
         
-        if (not cherrypy.config.get('xmlRpcFilter.on', False)
-            or not getattr(cherrypy.request, 'isRPC', False)):
+        if (not cherrypy.config.get('xmlrpc_filter.on', False)
+            or not getattr(cherrypy.request, 'is_rpc', False)):
             return
         
         path = cherrypy.request.objectPath
                 # Remove "root" from object_path and join it to get objectPath
                 self.objectPath = '/' + '/'.join(object_path[1:])
                 args = virtual_path + cherrypy.request.paramList
-                body = page_handler(*args, **cherrypy.request.paramMap)
+                body = page_handler(*args, **cherrypy.request.params)
                 break
             except cherrypy.InternalRedirect, x:
                 # Try again with the new path
         # See xmlrpclib documentation
         # Python's None value cannot be used in standard XML-RPC;
         # to allow using it via an extension, provide a true value for allow_none.
-        encoding = cherrypy.config.get('xmlRpcFilter.encoding', 'utf-8')
+        encoding = cherrypy.config.get('xmlrpc_filter.encoding', 'utf-8')
         body = xmlrpclib.dumps((body,), methodresponse=1,
                                encoding=encoding, allow_none=0)
         self.respond(body)
         cherrypy.request.executeMain = False
     
-    def afterErrorResponse(self):
-        if (not cherrypy.config.get('xmlRpcFilter.on', False)
-            or no