Commits

Robert Brewer committed 8f6f557

Cleanup of cherrypy and cherrypy.config namespaces. Changed 'log_config_options' to 'log_config'. Moved cherrypy.set_config to cherrypy.config.wrap.

  • Participants
  • Parent commits a249734
  • Branches cherrypy

Comments (0)

Files changed (5)

 
 __version__ = '3.0.0alpha'
 
-import logging
+import logging as _logging
 
-from _cperror import HTTPError, HTTPRedirect, InternalRedirect, NotFound, WrongConfigValue
+from _cperror import (HTTPError, HTTPRedirect, InternalRedirect,
+                      NotFound, WrongConfigValue)
 import config
 
 import _cptools
                 'a': request.headers.get('user-agent', ''),
                 }
     try:
-        request.app.access_log.log(logging.INFO, s)
+        request.app.access_log.log(_logging.INFO, s)
     except:
         log(traceback=True)
 
 
-_error_log = logging.getLogger("cherrypy.error")
-_error_log.setLevel(logging.DEBUG)
+_error_log = _logging.getLogger("cherrypy.error")
+_error_log.setLevel(_logging.DEBUG)
 
-def _log_message(msg, context = '', severity = logging.DEBUG):
+def _log_message(msg, context = '', severity = _logging.DEBUG):
     """Default method for logging messages (error log).
     
     This is not just for errors! Applications may call this at any time to
         log = _error_log
     log.log(severity, ' '.join((logtime(), context, msg)))
 
-def log(msg='', context='', severity=logging.DEBUG, traceback=False):
+def log(msg='', context='', severity=_logging.DEBUG, traceback=False):
     """Syntactic sugar for writing to the (error) log.
     
     This is not just for errors! Applications may call this at any time to
             alias = func
         return expose_
 
-def set_config(**kwargs):
-    """Decorator to set _cp_config using the given kwargs."""
-    def wrapper(f):
-        if not hasattr(f, "_cp_config"):
-            f._cp_config = {}
-        f._cp_config.update(kwargs)
-        return f
-    return wrapper
-
         conf = cherrypy.config.get
         
         # Output config options to log
-        if conf("log_config_options", True):
-            cherrypy.config.output_config_map()
+        if conf("log_config", True):
+            cherrypy.config.log_config()
         
         # Autoreload. Note that, if we're not starting our own HTTP server,
         # autoreload could do Very Bad Things when it calls sys.exit, but
 """Configuration system for CherryPy."""
 
 import ConfigParser
-import logging
-_logfmt = logging.Formatter("%(message)s")
-import os
-import sys
+import logging as _logging
+_logfmt = _logging.Formatter("%(message)s")
+import os as _os
 
 import cherrypy
-from cherrypy.lib import autoreload, unrepr
 
 environments = {
     "development": {
 def merge(base, other):
     """Merge one app config (from a dict, file, or filename) into another."""
     if isinstance(other, basestring):
-        if other not in autoreload.reloadFiles:
-            autoreload.reloadFiles.append(other)
-        other = dict_from_config_file(other)
+        if other not in cherrypy.lib.autoreload.reloadFiles:
+            cherrypy.lib.autoreload.reloadFiles.append(other)
+        other = Parser().dict_from_file(other)
     elif hasattr(other, 'read'):
-        other = dict_from_config_file(other)
+        other = Parser().dict_from_file(other)
     
     # Load other into base
     for section, value_map in other.iteritems():
     'server.reverse_dns': False,
     'server.thread_pool': 10,
     'log_to_screen': True,
-    'log_file': os.path.join(os.getcwd(), os.path.dirname(__file__),
+    'log_file': _os.path.join(_os.getcwd(),_os.path.dirname(__file__),
                              "error.log"),
     'tools.log_tracebacks.on': True,
     'environment': "development",
 def update(conf):
     """Update globalconf from a dict, file or filename."""
     if isinstance(conf, basestring):
-        if conf not in autoreload.reloadFiles:
-            autoreload.reloadFiles.append(conf)
-        conf = dict_from_config_file(conf)
+        if conf not in cherrypy.lib.autoreload.reloadFiles:
+            cherrypy.lib.autoreload.reloadFiles.append(conf)
+        conf = Parser().dict_from_file(conf)
     elif hasattr(conf, 'read'):
-        conf = dict_from_config_file(conf)
+        conf = Parser().dict_from_file(conf)
+    
     if isinstance(conf.get("global", None), dict):
         conf = conf["global"]
     globalconf.update(conf)
     _configure_builtin_logging(globalconf, cherrypy._error_log)
 
 def _add_builtin_screen_handler(log):
-    h = logging.StreamHandler(sys.stdout)
-    h.setLevel(logging.DEBUG)
+    import sys
+    h = _logging.StreamHandler(sys.stdout)
+    h.setLevel(_logging.DEBUG)
     h.setFormatter(_logfmt)
     h._cpbuiltin = "screen"
     log.addHandler(h)
 
 def _add_builtin_file_handler(log, fname):
-    h = logging.FileHandler(fname)
-    h.setLevel(logging.DEBUG)
+    h = _logging.FileHandler(fname)
+    h.setLevel(_logging.DEBUG)
     h.setFormatter(_logfmt)
     h._cpbuiltin = "file"
     log.addHandler(h)
     fname = conf.get(filekey)
     if fname:
         if h:
-            if h.baseFilename != os.path.abspath(fname):
+            if h.baseFilename != _os.path.abspath(fname):
                 h.close()
                 log.handlers.remove(h)
                 _add_builtin_file_handler(log, fname)
             return default
 
 
-class CaseSensitiveConfigParser(ConfigParser.ConfigParser):
+def wrap(**kwargs):
+    """Decorator to set _cp_config on a handler using the given kwargs."""
+    def wrapper(f):
+        if not hasattr(f, "_cp_config"):
+            f._cp_config = {}
+        f._cp_config.update(kwargs)
+        return f
+    return wrapper
+
+
+class Parser(ConfigParser.ConfigParser):
     """Sub-class of ConfigParser that keeps the case of options and that raises
     an exception if the file cannot be read.
     """
                 self._read(fp, filename)
             finally:
                 fp.close()
+    
+    def as_dict(self, raw=False, vars=None):
+        """Convert an INI file to a dictionary"""
+        # Load INI file into a dict
+        from cherrypy.lib import unrepr
+        result = {}
+        for section in self.sections():
+            if section not in result:
+                result[section] = {}
+            for option in self.options(section):
+                value = self.get(section, option, raw, vars)
+                try:
+                    value = unrepr(value)
+                except Exception, x:
+                    msg = ("section: %s, option: %s, value: %s" %
+                           (repr(section), repr(option), repr(value)))
+                    e = cherrypy.WrongConfigValue(msg)
+                    e.args += (x.__class__.__name__, x.args)
+                    raise e
+                result[section][option] = value
+        return result
+    
+    def dict_from_file(self, file):
+        if hasattr(file, 'read'):
+            self.readfp(file)
+        else:
+            self.read(file)
+        return self.as_dict()
 
-def dict_from_config_file(config_file, raw=False, vars=None):
-    """Convert an INI file to a dictionary"""
-    
-    # Parse config file
-    configParser = CaseSensitiveConfigParser()
-    if hasattr(config_file, 'read'):
-        configParser.readfp(config_file)
-    else:
-        configParser.read(config_file)
-    
-    # Load INI file into a dict
-    result = {}
-    for section in configParser.sections():
-        if section not in result:
-            result[section] = {}
-        for option in configParser.options(section):
-            value = configParser.get(section, option, raw, vars)
-            try:
-                value = unrepr(value)
-            except Exception, x:
-                msg = ("section: %s, option: %s, value: %s" %
-                       (repr(section), repr(option), repr(value)))
-                e = cherrypy.WrongConfigValue(msg)
-                e.args += (x.__class__.__name__, x.args)
-                raise e
-            result[section][option] = value
-    return result
 
-
-def output_config_map():
+def log_config():
     """Log engine configuration parameters."""
     cherrypy.log("Server parameters:", 'CONFIG')
     
     for var in serverVars:
         cherrypy.log("  %s: %s" % (var, get(var)), 'CONFIG')
 
+
+del ConfigParser

test/test_core.py

             raise ValueError()
         
         # We support Python 2.3, but the @-deco syntax would look like this:
-        # @cherrypy.set_config(stream_response=True)
+        # @cherrypy.config.wrap(stream_response=True)
         def page_streamed(self):
             yield "word up"
             raise ValueError()
             yield "very oops"
-        page_streamed = cherrypy.set_config(stream_response=True)(page_streamed)
+        page_streamed = cherrypy.config.wrap(stream_response=True)(page_streamed)
         assert(page_streamed._cp_config == {'stream_response': True})
         
         def cause_err_in_finalize(self):

test/test_states.py

             'server.socket_port': port,
             'server.thread_pool': 10,
             'log_to_screen': False,
-            'log_config_options': False,
+            'log_config': False,
             'environment': "production",
             'show_tracebacks': True,
             }
                 'server.socket_port': port,
                 'server.thread_pool': 10,
                 'log_to_screen': False,
-                'log_config_options': False,
+                'log_config': False,
                 'environment': "production",
                 'show_tracebacks': True,
                 }