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

root/branches/cherrypy-2.1/cherrypy/config.py

Revision 692 (checked in by fumanchu, 3 years ago)

1. Fix for #305 (produce an error if a custom error page file can not be opened).

2. Also, a fix in _cputil.getErrorPage, where messages (and other kwargs set to None) were not printing defaults.

3. Removed defunct "server.httpErrors" config entry.

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.protocolVersion': 'HTTP/1.0',
52     'server.logToScreen': True,
53     'server.logFile': '',
54     'server.reverseDNS': False,
55     'server.threadPool': 0,
56     }
57
58 def reset(useDefaults=True):
59     """Clear configuration and restore defaults"""
60     configMap.clear()
61     if useDefaults:
62         configMap["global"] = defaultGlobal.copy()
63 reset()
64
65 def update(updateMap=None, file=None, override=True):
66     """Update configMap from a dictionary or a config file
67     If override is True then the update will not modify values already defined
68     in the configMap.
69     """
70     if updateMap:
71         for section, valueMap in updateMap.iteritems():
72             if not isinstance(valueMap, dict):
73                 # Shortcut syntax
74                 #   ex: update({'server.socketPort': 80})
75                 valueMap = {section: valueMap}
76                 section = 'global'
77             sectionMap = configMap.setdefault(section, {})
78             if override:
79                 sectionMap.update(valueMap)
80             else:
81                 for key, value in valueMap.iteritems():
82                     sectionMap.setdefault(key, value)
83     if file:
84         if file not in autoreload.reloadFiles:
85             autoreload.reloadFiles.append(file)
86         _load(file, override)
87
88 def get(key, defaultValue=None, returnSection=False, path = None):
89     """Return the configuration value corresponding to key
90     If specified, return defaultValue on lookup failure. If returnSection is
91     specified, return the path to the value, instead of the value itself.
92     """
93     # Look, ma, no Python function calls! Uber-fast.
94
95     if path is None:
96         try:
97             path = cherrypy.request.path
98         except AttributeError:
99             # There's no request.path yet, so use the global settings.
100             path = "global"
101
102     while True:
103         if path == "":
104             path = "/"
105        
106         try:
107             result = configMap[path][key]
108         except KeyError:
109             if path == "global":
110                 result = defaultValue
111             elif path == "/":
112                 path = "global"
113                 continue
114             else:
115                 path = path[:path.rfind("/")]
116                 continue
117         break
118    
119     if returnSection:
120         return path
121     else:
122         return result
123
124 def getAll(key):
125     """Lookup key in the current node and all of its parent nodes
126     as a list of path, value pairs.
127     """
128     # Needed by the session filter
129    
130     try:
131         results = [('global', configMap['global'][key])]
132     except KeyError:
133         results = []
134    
135     try:
136         path = cherrypy.request.path
137     except AttributeError:
138         return results
139    
140     pathList = path.split('/')
141    
142     for n in xrange(1, len(pathList)):
143         path = '/' + '/'.join(pathList[0:n+1])
144         try:
145             results.append((path, configMap[path][key]))
146         except KeyError:
147             pass
148    
149     return results
150
151
152 class CaseSensitiveConfigParser(ConfigParser.ConfigParser):
153     """Sub-class of ConfigParser that keeps the case of options and that raises
154     an exception if the file cannot be read.
155     """
156    
157     def optionxform(self, optionstr):
158         return optionstr
159    
160     def read(self, filenames):
161         if isinstance(filenames, basestring):
162             filenames = [filenames]
163         for filename in filenames:
164             # try:
165             #     fp = open(filename)
166             # except IOError:
167             #     continue
168             fp = open(filename)
169             try:
170                 self._read(fp, filename)
171             finally:
172                 fp.close()
173
174 def dict_from_config_file(configFile):
175     """Convert an INI file to a dictionary"""
176    
177     # Parse config file
178     configParser = CaseSensitiveConfigParser()
179     if hasattr(configFile, 'read'):
180         configParser.readfp(configFile)
181     else:
182         configParser.read(configFile)
183    
184     # Load INI file into a dict
185     result = {}
186     for section in configParser.sections():
187         if section not in result:
188             result[section] = {}
189         for option in configParser.options(section):
190             value = configParser.get(section, option)
191             try:
192                 value = _cputil.unrepr(value)
193             except _cperror.WrongUnreprValue, s:
194                 msg = ("section: %s, option: %s, value: %s" %
195                        (repr(section), repr(option), repr(value)))
196                 raise _cperror.WrongConfigValue(msg)
197             result[section][option] = value
198     return result
199
200
201 def _load(configFile, override=True):
202     """Merge an INI file into configMap
203     If override is false, preserve values already in the configMap.
204     """
205    
206     conf = dict_from_config_file(configFile)
207    
208     # Load new conf into cherrypy.configMap
209     for section, options in conf.iteritems():
210         bucket = configMap.setdefault(section, {})
211         for key, value in options.iteritems():
212             if override:
213                 bucket[key] = value
214             else:
215                 bucket.setdefault(key, value)
216
217
218 def outputConfigMap():
219     """Log server configuration parameters"""
220     cherrypy.log("Server parameters:", 'CONFIG')
221    
222     serverVars = [
223                   'server.environment',
224                   'server.logToScreen',
225                   'server.logFile',
226                   'server.protocolVersion',
227                   'server.socketHost',
228                   'server.socketPort',
229                   'server.socketFile',
230                   'server.reverseDNS',
231                   'server.socketQueueSize',
232                   'server.threadPool'
233                  ]
234
235     for var in serverVars:
236         cherrypy.log("  %s: %s" % (var, get(var)), 'CONFIG')
237
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets