Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/tags/cherrypy-2.1.0-rc1/cherrypy/config.py

Revision 626 (checked in by rdelon, 3 years ago)

Implemented ticket #90 (still need to write docs though)

Line 
1 """
2 Copyright (c) 2004, CherryPy Team (team@cherrypy.org)
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8     * Redistributions of source code must retain the above copyright notice,
9       this list of conditions and the following disclaimer.
10     * Redistributions in binary form must reproduce the above copyright notice,
11       this list of conditions and the following disclaimer in the documentation
12       and/or other materials provided with the distribution.
13     * Neither the name of the CherryPy Team nor the names of its contributors
14       may be used to endorse or promote products derived from this software
15       without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
21 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 """
28
29 """
30 Configuration system for CherryPy.
31 """
32
33 import ConfigParser
34
35 import cherrypy
36 from cherrypy import _cputil, _cperror
37 from cherrypy.lib import autoreload
38
39
40 # This configMap dict holds the settings metadata for all cherrypy objects.
41 # Keys are URL paths, and values are dicts.
42 configMap = {}
43
44 defaultGlobal = {
45     'server.socketPort': 8080,
46     'server.socketHost': '',
47     'server.socketFile': '',
48     'server.socketQueueSize': 5,
49    
50     'server.environment': 'development',
51     'server.httpErrors' : True,
52     'server.protocolVersion': 'HTTP/1.0',
53     'server.logToScreen': True,
54     'server.logFile': '',
55     'server.reverseDNS': False,
56     'server.threadPool': 0,
57     }
58
59 def reset(useDefaults=True):
60     """Clear configuration and restore defaults"""
61     configMap.clear()
62     if useDefaults:
63         configMap["global"] = defaultGlobal.copy()
64 reset()
65
66 def update(updateMap=None, file=None, override=True):
67     """Update configMap from a dictionary or a config file
68     If override is True then the update will not modify values already defined
69     in the configMap.
70     """
71     if updateMap:
72         for section, valueMap in updateMap.iteritems():
73             if not isinstance(valueMap, dict):
74                 # Shortcut syntax
75                 #   ex: update({'server.socketPort': 80})
76                 valueMap = {section: valueMap}
77                 section = 'global'
78             sectionMap = configMap.setdefault(section, {})
79             if override:
80                 sectionMap.update(valueMap)
81             else:
82                 for key, value in valueMap.iteritems():
83                     sectionMap.setdefault(key, value)
84     if file:
85         if file not in autoreload.reloadFiles:
86             autoreload.reloadFiles.append(file)
87         _load(file, override)
88
89 def get(key, defaultValue=None, returnSection=False, path = None):
90     """Return the configuration value corresponding to key
91     If specified, return defaultValue on lookup failure. If returnSection is
92     specified, return the path to the value, instead of the value itself.
93     """
94     # Look, ma, no Python function calls! Uber-fast.
95
96     if path is None:
97         try:
98             path = cherrypy.request.path
99         except AttributeError:
100             # There's no request.path yet, so use the global settings.
101             path = "global"
102
103     while True:
104         if path == "":
105             path = "/"
106        
107         try:
108             result = configMap[path][key]
109         except KeyError:
110             if path == "global":
111                 result = defaultValue
112             elif path == "/":
113                 path = "global"
114                 continue
115             else:
116                 path = path[:path.rfind("/")]
117                 continue
118         break
119    
120     if returnSection:
121         return path
122     else:
123         return result
124
125 def getAll(key):
126     """Lookup key in the current node and all of its parent nodes
127     as a list of path, value pairs.
128     """
129     # Needed by the session filter
130    
131     try:
132         results = [('global', configMap['global'][key])]
133     except KeyError:
134         results = []
135    
136     try:
137         path = cherrypy.request.path
138     except AttributeError:
139         return results
140    
141     pathList = path.split('/')
142    
143     for n in xrange(1, len(pathList)):
144         path = '/' + '/'.join(pathList[0:n+1])
145         try:
146             results.append((path, configMap[path][key]))
147         except KeyError:
148             pass
149    
150     return results
151
152
153 class CaseSensitiveConfigParser(ConfigParser.ConfigParser):
154     """Sub-class of ConfigParser that keeps the case of options and that raises
155     an exception if the file cannot be read.
156     """
157    
158     def optionxform(self, optionstr):
159         return optionstr
160    
161     def read(self, filenames):
162         if isinstance(filenames, basestring):
163             filenames = [filenames]
164         for filename in filenames:
165             # try:
166             #     fp = open(filename)
167             # except IOError:
168             #     continue
169             fp = open(filename)
170             try:
171                 self._read(fp, filename)
172             finally:
173                 fp.close()
174
175 def dict_from_config_file(configFile):
176     """Convert an INI file to a dictionary"""
177    
178     # Parse config file
179     configParser = CaseSensitiveConfigParser()
180     if hasattr(configFile, 'read'):
181         configParser.readfp(configFile)
182     else:
183         configParser.read(configFile)
184    
185     # Load INI file into a dict
186     result = {}
187     for section in configParser.sections():
188         if section not in result:
189             result[section] = {}
190         for option in configParser.options(section):
191             value = configParser.get(section, option)
192             try:
193                 value = _cputil.unrepr(value)
194             except _cperror.WrongUnreprValue, s:
195                 msg = ("section: %s, option: %s, value: %s" %
196                        (repr(section), repr(option), repr(value)))
197                 raise _cperror.WrongConfigValue(msg)
198             result[section][option] = value
199     return result
200
201
202 def _load(configFile, override=True):
203     """Merge an INI file into configMap
204     If override is false, preserve values already in the configMap.
205     """
206    
207     conf = dict_from_config_file(configFile)
208    
209     # Load new conf into cherrypy.configMap
210     for section, options in conf.iteritems():
211         bucket = configMap.setdefault(section, {})
212         for key, value in options.iteritems():
213             if override:
214                 bucket[key] = value
215             else:
216                 bucket.setdefault(key, value)
217
218
219 def outputConfigMap():
220     """Log server configuration parameters"""
221     cherrypy.log("Server parameters:", 'CONFIG')
222    
223     serverVars = [
224                   'server.environment',
225                   'server.logToScreen',
226                   'server.logFile',
227                   'server.protocolVersion',
228                   'server.socketHost',
229                   'server.socketPort',
230                   'server.socketFile',
231                   'server.reverseDNS',
232                   'server.socketQueueSize',
233                   'server.threadPool'
234                  ]
235
236     for var in serverVars:
237         cherrypy.log("  %s: %s" % (var, get(var)), 'CONFIG')
238
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets