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

root/branches/cherrypy-2.x/cherrypy/config.py

Revision 1508 (checked in by fumanchu, 2 years ago)

2.x backport of [1226] (new server.socket_timeout config entry).

  • Property svn:eol-style set to native
Line 
1 """Configuration system for CherryPy."""
2
3 import ConfigParser
4 import os
5
6 import cherrypy
7 from cherrypy import _cputil
8 from cherrypy.lib import autoreload, cptools, httptools
9
10
11 # This configs dict holds the settings metadata for all cherrypy objects.
12 # Keys are URL paths, and values are dicts.
13 configs = {}
14 configMap = configs # Backward compatibility
15
16 default_global = {
17     'server.socket_port': 8080,
18     'server.socket_host': '',
19     'server.socket_file': '',
20     'server.socket_queue_size': 5,
21     'server.socket_timeout': 10,
22     'server.protocol_version': 'HTTP/1.0',
23     'server.log_to_screen': True,
24     'server.log_tracebacks': True,
25     'server.log_file': '',
26     'server.reverse_dns': False,
27     'server.thread_pool': 10,
28     'server.environment': "development",
29    
30     '/favicon.ico': {
31         'static_filter.on': True,
32         'static_filter.file': os.path.join(os.path.dirname(__file__), "favicon.ico"),}
33     }
34
35 environments = {
36     "development": {
37         'autoreload.on': True,
38         'log_debug_info_filter.on': True,
39         'server.log_file_not_found': True,
40         'server.show_tracebacks': True,
41         'server.log_request_headers': True,
42         },
43     "staging": {
44         'autoreload.on': False,
45         'log_debug_info_filter.on': False,
46         'server.log_file_not_found': False,
47         'server.show_tracebacks': False,
48         'server.log_request_headers': False,
49         },
50     "production": {
51         'autoreload.on': False,
52         'log_debug_info_filter.on': False,
53         'server.log_file_not_found': False,
54         'server.show_tracebacks': False,
55         'server.log_request_headers': False,
56         },
57     "embedded": {
58         'autoreload.on': False,
59         'server.log_to_screen': False,
60         'server.init_only': True,
61         'server.class': None,
62         },
63     }
64
65 def update(updateMap=None, file=None, overwrite=True, baseurl=""):
66     """Update configs from a dictionary or a config file.
67     
68     If overwrite is False then the update will not modify values
69     already defined in the configs.
70     """
71     if updateMap is None:
72         updateMap = {}
73    
74     if file:
75         if file not in autoreload.reloadFiles:
76             autoreload.reloadFiles.append(file)
77         updateMap = updateMap.copy()
78         updateMap.update(dict_from_config_file(file))
79    
80     # Load new conf into cherrypy.configs
81     for section, valueMap in updateMap.iteritems():
82         # Handle shortcut syntax for "global" section
83         #   example: update({'server.socket_port': 80})
84         if not isinstance(valueMap, dict):
85             valueMap = {section: valueMap}
86             section = 'global'
87        
88         if baseurl and section.startswith("/"):
89             if section == "/":
90                 section = baseurl
91             else:
92                 section = httptools.urljoin(baseurl, section)
93        
94         bucket = configs.setdefault(section, {})
95         if overwrite:
96             bucket.update(valueMap)
97         else:
98             for key, value in valueMap.iteritems():
99                 bucket.setdefault(key, value)
100
101 def reset(useDefaults=True):
102     """Clear configuration and restore defaults"""
103     configs.clear()
104     if useDefaults:
105         update(default_global)
106 reset()
107
108 def get(key, default_value=None, return_section=False, path = None):
109     """Return the configuration value corresponding to key
110     If specified, return default_value on lookup failure. If return_section is
111     specified, return the path to the value, instead of the value itself.
112     """
113    
114     if path is None:
115         try:
116             path = cherrypy.request.object_path
117         except AttributeError:
118             # There's no request.object_path yet, so use the global settings.
119             path = "global"
120    
121     while True:
122         if path == "":
123             path = "/"
124        
125         if cherrypy.lowercase_api is False:
126             # We don't know for sure if user uses the new lowercase API
127             try:
128                 result = configs[path][_cputil.lower_to_camel(key)]
129                 break
130             except KeyError:
131                 try:
132                     result = configs[path][key]
133                     break
134                 except KeyError:
135                     pass
136                 pass
137            
138             try:
139                 # Check for a server.environment entry at this node.
140                 env = configs[path]["server.environment"]
141                 # For backward compatibility, check for camelCase key first
142                 result = environments[env][_cputil.lower_to_camel(key)]
143                 break
144             except KeyError:
145                 try:
146                     env = configs[path]["server.environment"]
147                     result = environments[env][key]
148                     break
149                 except KeyError:
150                     pass
151                 pass
152         else:
153             # We know for sure that user uses the new lowercase api
154             try:
155                 result = configs[path][key]
156                 break
157             except KeyError:
158                 pass
159            
160             try:
161                 env = configs[path]["server.environment"]
162                 result = environments[env][key]
163                 break
164             except KeyError:
165                 pass
166             pass
167
168         if path == "global":
169             result = default_value
170             break
171        
172         # Move one node up the tree and try again.
173         if path == "/":
174             path = "global"
175         elif path in cherrypy.tree.mount_points:
176             # We've reached the mount point for an application,
177             # and should skip the rest of the tree (up to "global").
178             path = "global"
179         else:
180             path = path[:path.rfind("/")]
181    
182     if return_section:
183         return path
184     else:
185         return result
186
187 def getAll(key):
188     """Return a list of (path, value) pairs for current node and all parents."""
189     try:
190         results = [('global', configs['global'][key])]
191     except KeyError:
192         results = []
193    
194     try:
195         path = cherrypy.request.object_path
196     except AttributeError:
197         return results
198    
199     try:
200         results.append(('/', configs['/'][key]))
201     except KeyError:
202         pass
203    
204     atoms = path.strip('/').split('/')
205     path = ""
206     for atom in atoms:
207         path = path + "/" + atom
208         try:
209             results.append((path, configs[path][key]))
210         except KeyError:
211             pass
212    
213     return results
214
215
216 class CaseSensitiveConfigParser(ConfigParser.ConfigParser):
217     """Sub-class of ConfigParser that keeps the case of options and that raises
218     an exception if the file cannot be read.
219     """
220    
221     def optionxform(self, optionstr):
222         return optionstr
223    
224     def read(self, filenames):
225         if isinstance(filenames, basestring):
226             filenames = [filenames]
227         for filename in filenames:
228             # try:
229             #     fp = open(filename)
230             # except IOError:
231             #     continue
232             fp = open(filename)
233             try:
234                 self._read(fp, filename)
235             finally:
236                 fp.close()
237
238 def dict_from_config_file(configFile, raw=False, vars=None):
239     """Convert an INI file to a dictionary"""
240    
241     # Parse config file
242     configParser = CaseSensitiveConfigParser()
243     if hasattr(configFile, 'read'):
244         configParser.readfp(configFile)
245     else:
246         configParser.read(configFile)
247    
248     # Load INI file into a dict
249     result = {}
250     for section in configParser.sections():
251         if section not in result:
252             result[section] = {}
253         for option in configParser.options(section):
254             value = configParser.get(section, option, raw, vars)
255             try:
256                 value = cptools.unrepr(value)
257             except Exception, x:
258                 msg = ("section: %s, option: %s, value: %s" %
259                        (repr(section), repr(option), repr(value)))
260                 e = cherrypy.WrongConfigValue(msg)
261                 e.args += (x.__class__.__name__, x.args)
262                 raise e
263             result[section][option] = value
264     return result
265
266
267 def outputConfigMap():
268     """Log server configuration parameters"""
269     cherrypy.log("Server parameters:", 'CONFIG')
270    
271     serverVars = [
272                   'server.environment',
273                   'server.log_to_screen',
274                   'server.log_file',
275                   'server.log_tracebacks',
276                   'server.log_request_headers',
277                   'server.protocol_version',
278                   'server.socket_host',
279                   'server.socket_port',
280                   'server.socket_file',
281                   'server.reverse_dns',
282                   'server.socket_queue_size',
283                   'server.thread_pool',
284                  ]
285
286     for var in serverVars:
287         cherrypy.log("  %s: %s" % (var, get(var)), 'CONFIG')
288
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets