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

root/tags/cherrypy-3.0.0/cherrypy/_cptree.py

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

Allow loggers to use a different logging root (e.g. "tg.error" instead of "cherrypy.error").

  • Property svn:eol-style set to native
Line 
1 """CherryPy Application and Tree objects."""
2
3 import os
4 import cherrypy
5 from cherrypy import _cpconfig, _cplogging, _cpwsgi, tools
6
7
8 class Application(object):
9     """A CherryPy Application.
10     
11     An instance of this class may also be used as a WSGI callable
12     (WSGI application object) for itself.
13     
14     root: the top-most container of page handlers for this app.
15     script_name: the URL "mount point" for this app; for example,
16         if script_name is "/my/cool/app", then the URL
17         "http://my.domain.tld/my/cool/app/page1" might be handled
18         by a "page1" method on the root object. If script_name is
19         explicitly set to None, then CherryPy will attempt to provide
20         it each time from request.wsgi_environ['SCRIPT_NAME'].
21     config: a dict of {path: pathconf} pairs, where 'pathconf' is itself
22         a dict of {key: value} pairs.
23     """
24    
25     def __init__(self, root, script_name=""):
26         self.log = _cplogging.LogManager(id(self), cherrypy.log.logger_root)
27         self.root = root
28         self.script_name = script_name
29         self.wsgiapp = _cpwsgi.CPWSGIApp(self)
30         self.namespaces = {"log": lambda k, v: setattr(self.log, k, v),
31                            "wsgi": self.wsgiapp.namespace_handler,
32                            }
33         self.config = {}
34    
35     def _get_script_name(self):
36         if self._script_name is None:
37             # None signals that the script name should be pulled from WSGI environ.
38             return cherrypy.request.wsgi_environ['SCRIPT_NAME']
39         return self._script_name
40     def _set_script_name(self, value):
41         self._script_name = value
42     script_name = property(fget=_get_script_name, fset=_set_script_name)
43    
44     def merge(self, config):
45         """Merge the given config into self.config."""
46         _cpconfig.merge(self.config, config)
47        
48         # Handle namespaces specified in config.
49         _cpconfig._call_namespaces(self.config.get("/", {}), self.namespaces)
50    
51     def __call__(self, environ, start_response):
52         return self.wsgiapp(environ, start_response)
53
54
55 class Tree(object):
56     """A registry of CherryPy applications, mounted at diverse points.
57     
58     An instance of this class may also be used as a WSGI callable
59     (WSGI application object), in which case it dispatches to all
60     mounted apps.
61     
62     apps: a dict of the form {script name: application}, where "script name"
63         is a string declaring the URL mount point (no trailing slash),
64         and "application" is an instance of cherrypy.Application (or an
65         arbitrary WSGI callable if you happen to be using a WSGI server).
66     """
67    
68     def __init__(self):
69         self.apps = {}
70    
71     def mount(self, root, script_name="", config=None):
72         """Mount a new app from a root object, script_name, and config."""
73         # Next line both 1) strips trailing slash and 2) maps "/" -> "".
74         script_name = script_name.rstrip("/")
75        
76         if isinstance(root, Application):
77             app = root
78         else:
79             app = Application(root, script_name)
80            
81             # If mounted at "", add favicon.ico
82             if script_name == "" and root and not hasattr(root, "favicon_ico"):
83                 favicon = os.path.join(os.getcwd(), os.path.dirname(__file__),
84                                        "favicon.ico")
85                 root.favicon_ico = tools.staticfile.handler(favicon)
86        
87         if config:
88             app.merge(config)
89        
90         self.apps[script_name] = app
91        
92         return app
93    
94     def graft(self, wsgi_callable, script_name=""):
95         """Mount a wsgi callable at the given script_name."""
96         # Next line both 1) strips trailing slash and 2) maps "/" -> "".
97         script_name = script_name.rstrip("/")
98         self.apps[script_name] = wsgi_callable
99    
100     def script_name(self, path=None):
101         """The script_name of the app at the given path, or None.
102         
103         If path is None, cherrypy.request is used.
104         """
105        
106         if path is None:
107             try:
108                 path = cherrypy.request.script_name + cherrypy.request.path_info
109             except AttributeError:
110                 return None
111        
112         while True:
113             if path in self.apps:
114                 return path
115            
116             if path == "":
117                 return None
118            
119             # Move one node up the tree and try again.
120             path = path[:path.rfind("/")]
121    
122     def __call__(self, environ, start_response):
123         # If you're calling this, then you're probably setting SCRIPT_NAME
124         # to '' (some WSGI servers always set SCRIPT_NAME to '').
125         # Try to look up the app using the full path.
126         path = environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')
127         sn = self.script_name(path or "/")
128         if sn is None:
129             start_response('404 Not Found', [])
130             return []
131        
132         app = self.apps[sn]
133        
134         # Correct the SCRIPT_NAME and PATH_INFO environ entries.
135         environ = environ.copy()
136         environ['SCRIPT_NAME'] = sn
137         environ['PATH_INFO'] = path[len(sn.rstrip("/")):]
138         return app(environ, start_response)
139
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets