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

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

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

Removed redundant lines in _cputil.

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 A module containing a few utility classes/functions used by CherryPy
31 """
32
33 import sys
34 import traceback
35 import time
36 import os
37 #import os.path
38
39 import cherrypy
40
41 class EmptyClass:
42     """ An empty class """
43     pass
44
45
46 def getObjectTrail():
47     """ Return all objects from the currenct object to cherrypy """
48     root = getattr(cherrypy, 'root', None)
49     if root:
50         objectTrail = [root]
51         # Try object path
52         try:
53             path = cherrypy.request.objectPath or cherrypy.request.path
54         except AttributeError:
55             path = '/'
56         if path:
57             pathList = path.split('/')[1:]
58            
59             # Successively get objects from the path
60             for newObj in pathList:
61                 try:
62                     root = getattr(root, newObj)
63                     objectTrail.append(root)
64                 except AttributeError:
65                     break
66        
67         return objectTrail
68     return None
69
70 def getSpecialAttribute(name):
71     """Return the special attribute. A special attribute is one that
72     applies to all of the children from where it is defined, such as
73     _cpFilterList."""
74    
75     # First, we look in the right-most object if this special attribute is implemented.
76     # If not, then we try the previous object and so on until we reach cherrypy.root
77     # If it's still not there, we use the implementation from this module.
78    
79     objectList = getObjectTrail()
80     if objectList:
81        
82         objectList.reverse()
83         for obj in objectList:
84             attr = getattr(obj, name, None)
85             if attr != None:
86                 return attr
87    
88     try:
89         return globals()[name]
90     except KeyError:
91         raise cherrypy.InternalError("Special attribute %s could not be found"
92                                      % repr(name))
93
94 def getSpecialAttributePath(name):
95     """ Return the path to the special attribute """
96     objectList = getObjectTrail()
97     if objectList:
98         pathList = cherrypy.request.objectPath or cherrypy.request.path
99         pathList = pathList.split("/")[1:]
100         for i in xrange(len(objectList) - 1, -1, -1):
101             if hasattr(objectList[i], name):
102                 return "/" + "/".join(pathList[:i] + [name])
103     raise cherrypy.InternalError("Special attribute %s could not be found"
104                                  % repr(name))
105
106
107 def logtime():
108     return '%04d/%02d/%02d %02d:%02d:%02d' % time.localtime(time.time())[:6]
109
110 def _cpLogAccess():
111     """ Default method for logging access """
112    
113     tmpl = '%(h)s %(l)s %(u)s [%(t)s] "%(r)s" %(s)s %(b)s'
114     s = tmpl % {'h': cherrypy.request.remoteHost,
115                 'l': '-',
116                 'u': getattr(cherrypy.request, "login", None) or "-",
117                 't': logtime(),
118                 'r': cherrypy.request.requestLine,
119                 's': cherrypy.response.status.split(" ", 1)[0],
120                 'b': cherrypy.response.headerMap.get('Content-Length', '') or "-",
121                 }
122    
123     if cherrypy.config.get('server.logToScreen', True):
124         print s
125    
126     fname = cherrypy.config.get('server.logAccessFile', '')
127     if fname:
128         f = open(fname, 'ab')
129         f.write(s + '\n')
130         f.close()
131
132
133 _log_severity_levels = {0: "INFO", 1: "WARNING", 2: "ERROR"}
134
135 def _cpLogMessage(msg, context = '', severity = 0):
136     """ Default method for logging messages (error log)"""
137    
138     level = _log_severity_levels.get(severity, "UNKNOWN")
139     s = logtime() + ' ' + context + ' ' + level + ' ' + msg
140    
141     if cherrypy.config.get('server.logToScreen', True):
142         print s
143    
144     fname = cherrypy.config.get('server.logFile', '')
145     #logdir = os.path.dirname(fname)
146     #if logdir and not os.path.exists(logdir):
147     #    os.makedirs(logdir)
148     if fname:
149         f = open(fname, 'ab')
150         f.write(s + '\n')
151         f.close()
152
153 def _HTTPErrorTemplate(errorString, message, traceback, version):
154     subTuple = (errorString, errorString, message, traceback, cherrypy.__version__)
155    
156     return '''<?xml version="1.0" encoding="UTF-8"?>
157     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
158       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
159     <html>
160     <head>
161         <title>%s</title>
162         <style type="text/css">
163         #poweredBy {
164             margin-top: 20px;
165             border-top: 2px solid black;
166             font-style: italic;
167         }
168
169         #traceback {
170             color: red;
171         }
172         </style>
173     </head>
174         <body>
175             <h2>%s</h2>
176             <p>%s</p>
177             <pre id="traceback">%s</pre>
178         <div id="poweredBy">
179         <span>Powered by <a href="Cherrypy">http://www.cherrypy.org">Cherrypy %s</a></span>
180         </div>
181         </body>
182     </html>
183     ''' % subTuple
184
185 import BaseHTTPServer
186 _HTTPResponses = BaseHTTPServer.BaseHTTPRequestHandler.responses
187
188 def getErrorStatusAndPage(status, traceback = None):
189     statusString, message = _HTTPResponses[status]
190     statusString = '%d %s' % (status, statusString)
191    
192     if traceback is None:
193         traceback = ''
194         # get the traceback from formatExc
195         developmentMode = (cherrypy.config.get('server.environment') == 'development')
196         if cherrypy.config.get('server.showTracebacks') or developmentMode:
197             traceback = formatExc()
198    
199     page = _HTTPErrorTemplate(statusString, message, traceback, cherrypy.__version__)
200    
201     return statusString, page
202
203 def formatExc(exc=None):
204     """formatExc(exc=None) -> exc (or sys.exc_info), formatted."""
205     if exc is None:
206         exc = sys.exc_info()
207
208     if exc == (None, None, None):
209         return ""
210     return "".join(traceback.format_exception(*exc))
211
212 def _cpOnError():
213     """ Default _cpOnError method """
214    
215     logTracebacks  = cherrypy.config.get('server.logTracebacks', True)
216     if logTracebacks:
217         cherrypy.log(formatExc())
218    
219     response = cherrypy.response
220    
221     response.status, response.body = getErrorStatusAndPage(500)
222    
223     if cherrypy.response.headerMap.has_key('Content-Encoding'):
224         del cherrypy.response.headerMap['Content-Encoding']
225
226 _cpFilterList = []
227
228 # Filters that are always included
229 from cherrypy.lib.filter import baseurlfilter, cachefilter, \
230     decodingfilter, encodingfilter, gzipfilter, logdebuginfofilter, \
231     staticfilter, nsgmlsfilter, tidyfilter, \
232     virtualhostfilter, xmlrpcfilter, sessionauthenticatefilter, \
233     sessionfilter
234
235 # this contains the classes for each filter type
236 # we do not store the instances here because the test
237 # suite must reinitilize the filters without restarting
238 # the server
239 _cpDefaultFilterClasses = {
240     'BaseUrlFilter'      : baseurlfilter.BaseUrlFilter,
241     'CacheFilter'        : cachefilter.CacheFilter,
242     'DecodingFilter'     : decodingfilter.DecodingFilter,
243     'EncodingFilter'     : encodingfilter.EncodingFilter,
244     'GzipFilter'         : gzipfilter.GzipFilter,
245     'LogDebugInfoFilter' : logdebuginfofilter.LogDebugInfoFilter,
246     'NsgmlsFilter'       : nsgmlsfilter.NsgmlsFilter,
247     'SessionAuthenticateFilter' : sessionauthenticatefilter.SessionAuthenticateFilter,
248     'SessionFilter'      : sessionfilter.SessionFilter,
249     'StaticFilter'       : staticfilter.StaticFilter,
250     'TidyFilter'         : tidyfilter.TidyFilter,
251     'VirtualHostFilter'  : virtualhostfilter.VirtualHostFilter,
252     'XmlRpcFilter'       : xmlrpcfilter.XmlRpcFilter,
253 }
254
255 # this is where the actuall filter instances are first stored
256 _cpDefaultFilterInstances = {}
257
258 # These are in order for a reason!
259 # They must be strings matching keys in _cpDefaultFilterClasses
260 __cpDefaultInputFilters = [
261     'CacheFilter',
262     'LogDebugInfoFilter',
263     'VirtualHostFilter',
264     'BaseUrlFilter',
265     'DecodingFilter',
266     'SessionFilter',
267     'SessionAuthenticateFilter',
268     'StaticFilter',
269     'NsgmlsFilter',
270     'TidyFilter',
271     'XmlRpcFilter',
272 ]
273
274 __cpDefaultOutputFilters = [
275     'XmlRpcFilter',
276     'EncodingFilter',
277     'TidyFilter',
278     'NsgmlsFilter',
279     'LogDebugInfoFilter',
280     'GzipFilter',
281     'SessionFilter',
282     'CacheFilter',
283 ]
284
285 # these are the lists cp internally uses to access the filters
286 # they are populated when _cpInitDefaultFilters is called
287 _cpDefaultInputFilterList  = []
288 _cpDefaultOutputFilterList = []
289
290 # initilize the default filters
291 def _cpInitDefaultFilters():
292     global _cpDefaultInputFilterList, _cpDefaultOutputFilterList
293     global _cpDefaultFilterInstances
294     _cpDefaultInputFilterList  = []
295     _cpDefaultOutputFilterList = []
296     _cpDefaultFilterInstances = {}
297    
298     for filterName in __cpDefaultInputFilters:
299         filterClass = _cpDefaultFilterClasses[filterName]
300         filterInstance = _cpDefaultFilterInstances[filterName] = filterClass()
301         _cpDefaultInputFilterList.append(filterInstance)
302    
303     for filterName in __cpDefaultOutputFilters:
304         filterClass = _cpDefaultFilterClasses[filterName]
305         filterInstance = _cpDefaultFilterInstances.setdefault(filterName, filterClass())
306         _cpDefaultOutputFilterList.append(filterInstance)
307
308 def _cpInitUserDefinedFilters():
309     filtersRoot = cherrypy.config.get('server.filtersRoot', [])
310     inputFiltersDict = cherrypy.config.get('server.inputFiltersDict', {})
311     outputFiltersDict = cherrypy.config.get('server.outputFiltersDict', {})
312    
313     if len(filtersRoot) == 0:
314         return
315
316     sys.path.extend(filtersRoot)
317        
318     for filterName, filterClassname in inputFiltersDict.items():
319         filterModule = __import__(filterName, globals(),  locals(), [])
320         filterClass = getattr(filterModule, filterClassname, None)
321         filterInstance = filterClass()
322         _cpDefaultInputFilterList.append(filterInstance)
323
324     for filterName, filterClassname in outputFiltersDict.items():
325         filterModule = __import__(filterName, globals(),  locals(), [])
326         filterClass = getattr(filterModule, filterClassname, None)
327         filterInstance = filterClass()
328         _cpDefaultOutputFilterList.append(filterInstance)
329
330     # Avoid pollution of the system path
331     for path in filtersRoot:
332         sys.path.remove(path)
333
334
335 # public domain "unrepr" implementation, found on the web and then improved.
336 import compiler
337
338 def getObj(s):
339     s = "a=" + s
340     p = compiler.parse(s)
341     return p.getChildren()[1].getChildren()[0].getChildren()[1]
342
343
344 class UnknownType(Exception):
345    
346     # initialize the built-in filters
347     for n in xrange(len(_cpDefaultInputFilterList)):
348         try:
349             _cpDefaultInputFilterList[n] = _cpDefaultInputFilterList[n]()
350         except:
351             pass
352    
353     for n in xrange(len(_cpDefaultOutputFilterList)):
354         try:
355             _cpDefaultOutputFilterList[n] = _cpDefaultOutputFilterList[n]()
356         except:
357             pass
358
359
360 class Builder:
361    
362     def build(self, o):
363         m = getattr(self, 'build_' + o.__class__.__name__, None)
364         if m is None:
365             raise UnknownType(o.__class__.__name__)
366         return m(o)
367    
368     def build_List(self, o):
369         return map(self.build, o.getChildren())
370    
371     def build_Const(self, o):
372         return o.value
373    
374     def build_Dict(self, o):
375         d = {}
376         i = iter(map(self.build, o.getChildren()))
377         for el in i:
378             d[el] = i.next()
379         return d
380    
381     def build_Tuple(self, o):
382         return tuple(self.build_List(o))
383    
384     def build_Name(self, o):
385         if o.name == 'None':
386             return None
387         if o.name == 'True':
388             return True
389         if o.name == 'False':
390             return False
391        
392         # See if the Name is a package or module
393         try:
394             return modules(o.name)
395         except ImportError:
396             pass
397        
398         raise UnknownType(o.name)
399    
400     def build_Add(self, o):
401         real, imag = map(self.build_Const, o.getChildren())
402         try:
403             real = float(real)
404         except TypeError:
405             raise UnknownType('Add')
406         if not isinstance(imag, complex) or imag.real != 0.0:
407             raise UnknownType('Add')
408         return real+imag
409    
410     def build_Getattr(self, o):
411         parent = self.build(o.expr)
412         return getattr(parent, o.attrname)
413
414
415 def unrepr(s):
416     if not s:
417         return s
418     try:
419         return Builder().build(getObj(s))
420     except:
421         raise cherrypy.WrongUnreprValue(repr(s))
422
423 def modules(modulePath):
424     """Load a module and retrieve a reference to that module."""
425     try:
426         mod = sys.modules[modulePath]
427         if mod is None:
428             raise KeyError()
429     except KeyError:
430         # The last [''] is important.
431         mod = __import__(modulePath, globals(), locals(), [''])
432     return mod
433
434 def attributes(fullAttributeName):
435     """Load a module and retrieve an attribute of that module."""
436    
437     # Parse out the path, module, and attribute
438     lastDot = fullAttributeName.rfind(u".")
439     attrName = fullAttributeName[lastDot + 1:]
440     modPath = fullAttributeName[:lastDot]
441    
442     aMod = modules(modPath)
443     # Let an AttributeError propagate outward.
444     try:
445         attr = getattr(aMod, attrName)
446     except AttributeError:
447         raise AttributeError("'%s' object has no attribute '%s'"
448                              % (modPath, attrName))
449    
450     # Return a reference to the attribute.
451     return attr
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets