"""Copyright (c) 2004, CherryPy Team (team@cherrypy.org)All rights reserved.Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the CherryPy Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""""""Configuration system for CherryPy."""importConfigParserimportcherrypyfromcherrypyimport_cputil,_cperrorfromcherrypy.libimportautoreload# This configMap dict holds the settings metadata for all cherrypy objects.# Keys are URL paths, and values are dicts.configMap={}defaultGlobal={'server.socketPort':8080,'server.socketHost':'','server.socketFile':'','server.socketQueueSize':5,'server.environment':'development','server.httpErrors':True,'server.protocolVersion':'HTTP/1.0','server.logToScreen':True,'server.logFile':'','server.reverseDNS':False,'server.threadPool':0,}defreset(useDefaults=True):"""Clear configuration and restore defaults"""configMap.clear()ifuseDefaults:configMap["global"]=defaultGlobal.copy()reset()defupdate(updateMap=None,file=None,override=True):"""Update configMap from a dictionary or a config file If override is True then the update will not modify values already defined in the configMap. """ifupdateMap:forsection,valueMapinupdateMap.iteritems():ifnotisinstance(valueMap,dict):# Shortcut syntax# ex: update({'server.socketPort': 80})valueMap={section:valueMap}section='global'sectionMap=configMap.setdefault(section,{})ifoverride:sectionMap.update(valueMap)else:forkey,valueinvalueMap.iteritems():sectionMap.setdefault(key,value)iffile:iffilenotinautoreload.reloadFiles:autoreload.reloadFiles.append(file)_load(file,override)defget(key,defaultValue=None,returnSection=False,path=None):"""Return the configuration value corresponding to key If specified, return defaultValue on lookup failure. If returnSection is specified, return the path to the value, instead of the value itself. """# Look, ma, no Python function calls! Uber-fast.ifpathisNone:try:path=cherrypy.request.pathexceptAttributeError:# There's no request.path yet, so use the global settings.path="global"whileTrue:ifpath=="":path="/"try:result=configMap[path][key]exceptKeyError:ifpath=="global":result=defaultValueelifpath=="/":path="global"continueelse:path=path[:path.rfind("/")]continuebreakifreturnSection:returnpathelse:returnresultdefgetAll(key):"""Lookup key in the current node and all of its parent nodes as a list of path, value pairs. """# Needed by the session filtertry:results=[('global',configMap['global'][key])]exceptKeyError:results=[]try:path=cherrypy.request.pathexceptAttributeError:returnresultspathList=path.split('/')forninxrange(1,len(pathList)):path='/'+'/'.join(pathList[0:n+1])try:results.append((path,configMap[path][key]))exceptKeyError:passreturnresultsclassCaseSensitiveConfigParser(ConfigParser.ConfigParser):"""Sub-class of ConfigParser that keeps the case of options and that raises an exception if the file cannot be read. """defoptionxform(self,optionstr):returnoptionstrdefread(self,filenames):ifisinstance(filenames,basestring):filenames=[filenames]forfilenameinfilenames:# try:# fp = open(filename)# except IOError:# continuefp=open(filename)try:self._read(fp,filename)finally:fp.close()defdict_from_config_file(configFile):"""Convert an INI file to a dictionary"""# Parse config fileconfigParser=CaseSensitiveConfigParser()ifhasattr(configFile,'read'):configParser.readfp(configFile)else:configParser.read(configFile)# Load INI file into a dictresult={}forsectioninconfigParser.sections():ifsectionnotinresult:result[section]={}foroptioninconfigParser.options(section):value=configParser.get(section,option)try:value=_cputil.unrepr(value)except_cperror.WrongUnreprValue,s:msg=("section: %s, option: %s, value: %s"%(repr(section),repr(option),repr(value)))raise_cperror.WrongConfigValue(msg)result[section][option]=valuereturnresultdef_load(configFile,override=True):"""Merge an INI file into configMap If override is false, preserve values already in the configMap. """conf=dict_from_config_file(configFile)# Load new conf into cherrypy.configMapforsection,optionsinconf.iteritems():bucket=configMap.setdefault(section,{})forkey,valueinoptions.iteritems():ifoverride:bucket[key]=valueelse:bucket.setdefault(key,value)defoutputConfigMap():"""Log server configuration parameters"""cherrypy.log("Server parameters:",'CONFIG')serverVars=['server.environment','server.logToScreen','server.logFile','server.protocolVersion','server.socketHost','server.socketPort','server.socketFile','server.reverseDNS','server.socketQueueSize','server.threadPool']forvarinserverVars:cherrypy.log(" %s: %s"%(var,get(var)),'CONFIG')