Commits

Anonymous committed 7df622c

Now using "unrepr" to read config file;
Got rid of "cast" option in config.get;
Using long names for "server.environment";

  • Participants
  • Parent commits ac6f651
  • Branches cherrypy

Comments (0)

Files changed (24)

             'server.socketFile': '',
             'server.socketQueueSize': 5,
 
-            'server.env': 'dev',
+            'server.environment': 'development',
             'server.protocolVersion': 'HTTP/1.0',
             'server.logToScreen': True,
             'server.logFile': '',
             'session.cleanUpDelay': 60,
             'session.cookieName': 'CherryPySession',
             'session.storageFileDir': '',
-
-            'staticContent': {}
         },
     }
 
                 return res
     return defaultValue
 
-def _cast(type, value):
-    if type is None:
-        return value
-    if type == 'int':
-        return int(value)
-    elif type == 'float':
-        return float(value)
-    elif type == 'bool':
-        if isinstance(value, basestring):
-            value = value.lower()
-        if (not value) or (value in ('false', 'off', '0')):
-            return False
-        return True
-    elif type == 'list':
-        if isinstance(value, list):
-            return value
-        assert (not value) or (
-            value[0] in ('(', '[') and value[-1] in (')', ']'))
-        return eval(value) # Convert value to list
-
-def get(key, defaultValue = None, cast = None, returnSection = False):
+def get(key, defaultValue = None, returnSection = False):
     # First try the whole browserUrl
     try:
         path = cpg.request.browserUrl
         path = '/'
     res = _getFor(path, key, '#NULL#', returnSection)
     if res != '#NULL#':
-        return _cast(cast, res)
+        return res
     # Then try just path
     try:
         path = cpg.request.path
         path = '/'
     res = _getFor(path, key, '#NULL#', returnSection)
     if res != '#NULL#':
-        return _cast(cast, res)
-    return _cast(cast, defaultValue)
+        return res
+    return defaultValue
 
 class CaseSensitiveConfigParser(ConfigParser.ConfigParser):
     """ Sub-class of ConfigParser that keeps the case of options and
         if section not in configMap:
             configMap[section] = {}
         for option in configParser.options(section):
-            value = configParser.get(section, option)
+            value = _cputil.unrepr(configParser.get(section, option))
             configMap[section][option] = value
 
 def outputConfigMap():
     _cpLogMessage = _cputil.getSpecialFunction('_cpLogMessage')
     _cpLogMessage("Server parameters:", 'CONFIG')
-    _cpLogMessage("  server.env: %s" % cpg.config.get('server.env'), 'CONFIG')
-    _cpLogMessage("  server.logToScreen: %s" % cpg.config.get('server.logToScreen', cast='bool'), 'CONFIG')
+    _cpLogMessage("  server.environment: %s" % cpg.config.get('server.environment'), 'CONFIG')
+    _cpLogMessage("  server.logToScreen: %s" % cpg.config.get('server.logToScreen'), 'CONFIG')
     _cpLogMessage("  server.logFile: %s" % cpg.config.get('server.logFile'), 'CONFIG')
     _cpLogMessage("  server.protocolVersion: %s" % cpg.config.get('server.protocolVersion'), 'CONFIG')
     _cpLogMessage("  server.socketHost: %s" % cpg.config.get('server.socketHost'), 'CONFIG')
-    _cpLogMessage("  server.socketPort: %s" % cpg.config.get('server.socketPort', cast='int'), 'CONFIG')
+    _cpLogMessage("  server.socketPort: %s" % cpg.config.get('server.socketPort'), 'CONFIG')
     _cpLogMessage("  server.socketFile: %s" % cpg.config.get('server.socketFile'), 'CONFIG')
-    _cpLogMessage("  server.reverseDNS: %s" % cpg.config.get('server.reverseDNS', cast='bool'), 'CONFIG')
-    _cpLogMessage("  server.socketQueueSize: %s" % cpg.config.get('server.socketQueueSize', cast='int'), 'CONFIG')
-    _cpLogMessage("  server.threadPool: %s" % cpg.config.get('server.threadPool', cast='int'), 'CONFIG')
+    _cpLogMessage("  server.reverseDNS: %s" % cpg.config.get('server.reverseDNS'), 'CONFIG')
+    _cpLogMessage("  server.socketQueueSize: %s" % cpg.config.get('server.socketQueueSize'), 'CONFIG')
+    _cpLogMessage("  server.threadPool: %s" % cpg.config.get('server.threadPool'), 'CONFIG')
     _cpLogMessage("  session.storageType: %s" % cpg.config.get('session.storageType'), 'CONFIG')
     if cpg.config.get('session.storageType'):
-        _cpLogMessage("  session.timeout: %s min" % cpg.config.get('session.timeout', cast='float'), 'CONFIG')
-        _cpLogMessage("  session.cleanUpDelay: %s min" % cpg.config.get('session.cleanUpDelay', cast='float'), 'CONFIG')
+        _cpLogMessage("  session.timeout: %s min" % cpg.config.get('session.timeout'), 'CONFIG')
+        _cpLogMessage("  session.cleanUpDelay: %s min" % cpg.config.get('session.cleanUpDelay'), 'CONFIG')
         _cpLogMessage("  session.cookieName: %s" % cpg.config.get('session.cookieName'), 'CONFIG')
         _cpLogMessage("  session.storageFileDir: %s" % cpg.config.get('session.storageFileDir'), 'CONFIG')
     _cpLogMessage("  staticContent: %s" % cpg.config.get('staticContent'), 'CONFIG')
     else:
         lebel = "UNKNOWN"
     try:
-        logToScreen = int(cpg.config.get('server.logToScreen', cast='bool'))
+        logToScreen = int(cpg.config.get('server.logToScreen'))
     except:
         logToScreen = True
     s = nowStr + ' ' + context + ' ' + level + ' ' + msg
     """ Save session data if needed """
 
     if threadPool is None:
-        threadPool = cpg.config.get('server.threadPool', cast='int')
+        threadPool = cpg.config.get('server.threadPool')
     if sessionStorageType is None:
         sessionStorageType = cpg.config.get('session.storageType')
     if sessionStorageFileDir is None:
     """
 
     if threadPool is None:
-        threadPool = cpg.config.get('server.threadPool', cast='int')
+        threadPool = cpg.config.get('server.threadPool')
     if sessionStorageType is None:
         sessionStorageType = cpg.config.get('session.storageType')
     if sessionStorageFileDir is None:
     """ Clean up old sessions """
 
     if threadPool is None:
-        threadPool = cpg.config.get('server.threadPool', cast='int')
+        threadPool = cpg.config.get('server.threadPool')
     if sessionStorageType is None:
         sessionStorageType = cpg.config.get('session.storageType')
     if sessionStorageFileDir is None:
     cpg._server.shutdown()
 
 def start():
-    if cpg.config.get("server.env") == "dev":
+    if cpg.config.get("server.environment") == "development":
         autoreload.main(_start)
     else:
         _start()
 
     # If sessions are stored in files and we
     # use threading, we need a lock on the file
-    if (cpg.config.get('server.threadPool', cast='int') > 1) and \
+    if (cpg.config.get('server.threadPool') > 1) and \
             cpg.config.get('session.storageType') == 'file':
         cpg._sessionFileLock = threading.RLock()
 
         class MyCherryHTTPServer(CherryHTTPServer): address_family = socket.AF_UNIX
     else:
         # AF_INET socket
-        if cpg.config.get('server.threadPool', cast='int') > 1:
+        if cpg.config.get('server.threadPool') > 1:
             MyCherryHTTPServer = PooledThreadServer
         else:
             MyCherryHTTPServer = CherryHTTPServer
 
-    MyCherryHTTPServer.request_queue_size = cpg.config.get('server.socketQueueSize', cast='int')
+    MyCherryHTTPServer.request_queue_size = cpg.config.get('server.socketQueueSize')
 
     # Set protocol_version
     CherryHTTPRequestHandler.protocol_version = cpg.config.get('server.protocolVersion')
 
     run_server(CherryHTTPRequestHandler, MyCherryHTTPServer, \
-        (cpg.config.get('server.socketHost'), cpg.config.get('server.socketPort', cast='int')), \
+        (cpg.config.get('server.socketHost'), cpg.config.get('server.socketPort')), \
         cpg.config.get('server.socketFile'))
 
 def run_server(HandlerClass, ServerClass, server_address, socketFile):
         try: os.unlink(cpg.config.get('server.socketFile')) # So we can reuse the socket
         except: pass
         server_address = cpg.config.get('server.socketFile')
-    if cpg.config.get('server.threadPool', cast='int') > 1:
-        myCherryHTTPServer = ServerClass(server_address, cpg.config.get('server.threadPool', cast='int'), HandlerClass)
+    if cpg.config.get('server.threadPool') > 1:
+        myCherryHTTPServer = ServerClass(server_address, cpg.config.get('server.threadPool'), HandlerClass)
     else:
         myCherryHTTPServer = ServerClass(server_address, HandlerClass)
     cpg._server = myCherryHTTPServer
     _cpLogMessage = _cputil.getSpecialFunction('_cpLogMessage')
 
     servingWhat = "HTTP"
-    if cpg.config.get('server.socketPort', cast='int'): 
+    if cpg.config.get('server.socketPort'): 
         onWhat = ("socket: ('%s', %s)" % 
-                 (cpg.config.get('server.socketHost'), cpg.config.get('server.socketPort', cast='int')))
+                 (cpg.config.get('server.socketHost'), cpg.config.get('server.socketPort')))
     else: onWhat = "socket file: %s" % cpg.config.get('server.socketFile')
     _cpLogMessage("Serving %s on %s" % (servingWhat, onWhat), 'HTTP')
 
 
     def address_string(self):
         """ Try to do a reverse DNS based on [server]reverseDNS in the config file """
-        if cpg.config.get('server.reverseDNS', cast='bool'):
+        if cpg.config.get('server.reverseDNS'):
             return BaseHTTPServer.BaseHTTPRequestHandler.address_string(self)
         else:
             return self.client_address[0]
     # Save session data
     if cpg.config.get('session.storageType') and not cpg.request.isStatic:
         sessionId = cpg.response.simpleCookie[cpg.config.get('session.cookieName')].value
-        expirationTime = time.time() + cpg.config.get('session.timeout', cast='float') * 60
+        expirationTime = time.time() + cpg.config.get('session.timeout') * 60
         _cputil.getSpecialFunction('_cpSaveSessionData')(sessionId, cpg.request.sessionMap, expirationTime)
 
     wfile.write('%s %s\r\n' % (cpg.response.headerMap['protocolVersion'], cpg.response.headerMap['Status']))
     # Clean up expired sessions if needed:
     now = time.time()
     if (cpg.config.get('session.storageType') and 
-        cpg.config.get('session.cleanUpDelay', cast='float') and 
-        (cpg._lastSessionCleanUpTime + cpg.config.get('session.cleanUpDelay', cast='float') * 60) <= now):
+        cpg.config.get('session.cleanUpDelay') and 
+        (cpg._lastSessionCleanUpTime + cpg.config.get('session.cleanUpDelay') * 60) <= now):
         cpg._lastSessionCleanUpTime = now
         _cputil.getSpecialFunction('_cpCleanUpOldSessions')()
 
 
     raise cperror.InternalError, "Special function %s could not be found" % repr(name)
 
+
+# public domain "unrepr" implementation, found on the web and then improved.
+import compiler
+
+def getObj(s):
+    s="a="+s
+    return compiler.parse(s).getChildren()[1].getChildren()[0].getChildren()[1]
+
+class UnknownType(Exception):
+    pass
+
+class Builder:
+
+    def build(self, o):
+        m = getattr(self, 'build_'+o.__class__.__name__, None)
+        if m is None:
+            raise UnknownType(o.__class__.__name__)
+        return m(o)
+
+    def build_List(self, o):
+        return map(self.build, o.getChildren())
+
+    def build_Const(self, o):
+        return o.value
+
+    def build_Dict(self, o):
+        d = {}
+        i = iter(map(self.build, o.getChildren()))
+        for el in i:
+            d[el] = i.next()
+        return d
+
+    def build_Tuple(self, o):
+        return tuple(self.build_List(o))
+
+    def build_Name(self, o):
+        if o.name == 'None':
+            return None
+        elif o.name == 'True':
+            return True
+        elif o.name == 'False':
+            return False
+        raise UnknownType(o.name)
+
+    def build_Add(self, o):
+        real, imag = map(self.build_Const, o.getChildren())
+        try:
+            real = float(real)
+        except TypeError:
+            raise UnknownType('Add')
+        if not isinstance(imag, complex) or imag.real != 0.0:
+            raise UnknownType('Add')
+        return real+imag
+
+def unrepr(s):
+      return Builder().build(getObj(s))
+

lib/filter/baseurlfilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.baseUrlFilterOn = cpg.config.get('baseUrlFilter', False, cast='bool')
+        cpg.threadData.baseUrlFilterOn = cpg.config.get('baseUrlFilter.on', False)
         cpg.threadData.baseUrlFilterBaseUrl = cpg.config.get('baseUrlFilter.baseUrl', 'http://localhost')
-        cpg.threadData.baseUrlFilterUseXForwardedHost = cpg.config.get('baseUrlFilter.useXForwardedHost', True, cast='bool')
+        cpg.threadData.baseUrlFilterUseXForwardedHost = cpg.config.get('baseUrlFilter.useXForwardedHost', True)
 
     def afterRequestHeader(self):
         if not cpg.threadData.baseUrlFilterOn:

lib/filter/cachefilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.cacheFilterOn = cpg.config.get('cacheFilter', False, cast='bool')
+        cpg.threadData.cacheFilterOn = cpg.config.get('cacheFilter.on', False)
         if cpg.threadData.cacheFilterOn and not hasattr(cpg, '_cache'):
             cpg._cache = self.CacheClass(self.key, self.delay,
                 self.maxobjsize, self.maxsize, self.maxobjects)

lib/filter/decodingfilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.decodingFilterOn = cpg.config.get('decodingFilter', False, cast='bool')
+        cpg.threadData.decodingFilterOn = cpg.config.get('decodingFilter.on', False)
         cpg.threadData.decodingFilterEncoding = cpg.config.get('decodingFilter.encoding', 'utf-8')
 
     def afterRequestBody(self):

lib/filter/encodingfilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.encodingFilterOn = cpg.config.get('encodingFilter', False, cast='bool')
+        cpg.threadData.encodingFilterOn = cpg.config.get('encodingFilter.on', False)
         cpg.threadData.encodingFilterEncoding = cpg.config.get('encodingFilter.encoding', 'utf-8')
-        cpg.threadData.encodingFilterMimeTypeList = cpg.config.get('encodingFilter.mimeTypeList', ['text/html'], cast='list')
+        cpg.threadData.encodingFilterMimeTypeList = cpg.config.get('encodingFilter.mimeTypeList', ['text/html'])
 
     def beforeResponse(self):
         if not cpg.threadData.encodingFilterOn:

lib/filter/gzipfilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.gzipFilterOn = cpg.config.get('gzipFilter', False, cast='bool')
-        cpg.threadData.gzipFilterMimeTypeList = cpg.config.get('gzipFilter.mimeTypeList', ['text/html'], cast='list')
-        cpg.threadData.gzipFilterCompressLevel = cpg.config.get('gzipFilter.compresslevel', 9, cast='int')
+        cpg.threadData.gzipFilterOn = cpg.config.get('gzipFilter.on', False)
+        cpg.threadData.gzipFilterMimeTypeList = cpg.config.get('gzipFilter.mimeTypeList', ['text/html'])
+        cpg.threadData.gzipFilterCompressLevel = cpg.config.get('gzipFilter.compresslevel', 9)
 
     def beforeResponse(self):
         if not cpg.threadData.gzipFilterOn:

lib/filter/logdebuginfofilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        if cpg.config.get('server.environment') == 'dev':
-            # In "dev" environment, log everything by default
+        if cpg.config.get('server.environment') == 'development':
+            # In "development" environment, log everything by default
             defaultOn = True
         else:
             defaultOn = False
 
-        cpg.threadData.logDebugInfoFilterOn = cpg.config.get('logDebugInfoFilter', defaultOn, cast='bool')
+        cpg.threadData.logDebugInfoFilterOn = cpg.config.get('logDebugInfoFilter.on', defaultOn)
         cpg.threadData.logDebugInfoFilterMimeTypeList = cpg.config.get('logDebugInfoFilter.mimeTypeList', ['text/html'])
-        cpg.threadData.logDebugInfoFilterLogBuildTime = cpg.config.get('logDebugInfoFilter.logBuildTime', True, cast='bool')
-        cpg.threadData.logDebugInfoFilterLogPageSize = cpg.config.get('logDebugInfoFilter.logPageSize', True, cast='bool')
-        cpg.threadData.logDebugInfoFilterLogSessionSize = cpg.config.get('logDebugInfoFilter.logSessionSize', True, cast='bool')
-        cpg.threadData.logDebugInfoFilterLogAsComment = cpg.config.get('logDebugInfoFilter.logAsComment', False, cast='bool')
+        cpg.threadData.logDebugInfoFilterLogBuildTime = cpg.config.get('logDebugInfoFilter.logBuildTime', True)
+        cpg.threadData.logDebugInfoFilterLogPageSize = cpg.config.get('logDebugInfoFilter.logPageSize', True)
+        cpg.threadData.logDebugInfoFilterLogSessionSize = cpg.config.get('logDebugInfoFilter.logSessionSize', True)
+        cpg.threadData.logDebugInfoFilterLogAsComment = cpg.config.get('logDebugInfoFilter.logAsComment', False)
 
 class LogDebugInfoInputFilter(BaseInputFilter, SetConfig):
     """

lib/filter/staticfilter.py

         #   circular module imports :-(
         global cpg, _cphttptools, cperror
         from cherrypy import cpg, _cphttptools, cperror
-        cpg.threadData.staticFilterOn = cpg.config.get('staticFilter', False, cast='bool')
+        cpg.threadData.staticFilterOn = cpg.config.get('staticFilter.on', False)
         cpg.threadData.staticFilterFile = cpg.config.get('staticFilter.file')
         cpg.threadData.staticFilterDir = cpg.config.get('staticFilter.dir')
         if cpg.threadData.staticFilterDir:

lib/filter/tidyfilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.tidyFilterOn = cpg.config.get('tidyFilter', False, cast='bool')
+        cpg.threadData.tidyFilterOn = cpg.config.get('tidyFilter.on', False)
         cpg.threadData.tifyFilterTidyPath = cpg.config.get('tidyFilter.tidyPath')
         cpg.threadData.tifyFilterTmpDir = cpg.config.get('tidyFilter.tmpDir')
-        cpg.threadData.tidyFilterStrictXml = cpg.config.get('tidyFilter.strictXml', False, cast='bool')
-        cpg.threadData.tidyFilterErrorsToIgnore = cpg.config.get('encodingFilter.errorsToIgnore', [], cast='list')
+        cpg.threadData.tidyFilterStrictXml = cpg.config.get('tidyFilter.strictXml', False)
+        cpg.threadData.tidyFilterErrorsToIgnore = cpg.config.get('encodingFilter.errorsToIgnore', [])
 
     def beforeResponse(self):
         if not cpg.threadData.tidyFilterOn:

lib/filter/virtualhostfilter.py

         #   circular module imports :-(
         global cpg, _cphttptools
         from cherrypy import cpg, _cphttptools
-        cpg.threadData.virtualFilterOn = cpg.config.get('virtualHostFilter', False, cast='bool')
+        cpg.threadData.virtualFilterOn = cpg.config.get('virtualHostFilter.on', False)
         cpg.threadData.virtualFilterPrefix = cpg.config.get('virtualHostFilter.prefix', '/')
 
     def afterRequestHeader(self):

lib/filter/xmlrpcfilter.py

         #   circular module imports :-(
         global cpg
         from cherrypy import cpg
-        cpg.threadData.xmlRpcFilterOn = cpg.config.get('xmlRpcFilter', False, cast='bool')
+        cpg.threadData.xmlRpcFilterOn = cpg.config.get('xmlRpcFilter.on', False)
 
 class XmlRpcInputFilter(BaseInputFilter, SetConfig):
     """
         f.write(extraConfig)
         f.write('''
 [/]
-session.storageType = ram
+session.storageType = "ram"
 server.socketPort = 8000
+server.environment = "production"
 ''')
         f.write(modeConfig)
         f.close()

test/testBaseUrlFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'baseUrlFilter': True,
+        'server.environment': 'production',
+        'baseUrlFilter.on': True,
         'baseUrlFilter.baseUrl': 'http://www.mydomain.com'
     }
 })

test/testCacheFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'cacheFilter': True,
+        'server.environment': 'production',
+        'cacheFilter.on': True,
     }
 })
 cpg.server.start()

test/testCombinedFilters.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'gzipFilter': True,
-        'encodingFilter': True,
+        'server.environment': 'production',
+        'gzipFilter.on': True,
+        'encodingFilter.on': True,
     }
 })
 cpg.server.start()

test/testDecodingEncodingFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'encodingFilter': True,
-        'decodingFilter': True
+        'server.environment': 'production',
+        'encodingFilter.on': True,
+        'decodingFilter.on': True,
     }
 })
 cpg.server.start()

test/testGzipFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'gzipFilter': True,
+        'server.environment': 'production',
+        'gzipFilter.on': True,
     }
 })
 cpg.server.start()

test/testLogDebugInfoFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'server.environment': 'dev',
+        'server.environment': 'production',
+        'logDebugInfoFilter.on': True,
     }
 })
 cpg.server.start()

test/testStaticFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
+        'server.environment': 'production',
     },
     '/static': {
-        'staticFilter': True,
+        'staticFilter.on': True,
         'staticFilter.dir': 'static',
     },
     '/style.css': {
-        'staticFilter': True,
+        'staticFilter.on': True,
         'staticFilter.file': 'style.css',
     }
 })

test/testVirtualHostFilter.py

 cpg.config.update({
     '/': {
         'server.socketPort': 8000,
-        'virtualHostFilter': True,
+        'server.environment': 'production',
+        'virtualHostFilter.on': True,
         'virtualHostFilter.prefix': '/index2',
     },
     '/shutdown': {
-        'virtualHostFilter': False,
+        'virtualHostFilter.on': False,
     }
 })
 cpg.server.start()