source file: /Library/Python/2.3/site-packages/CherryPy-3.0.1-py2.3.egg/cherrypy/_cptools.py
file stats: 191 lines, 122 executed: 63.9% covered
   1. """CherryPy tools. A "tool" is any helper, adapted to CP.
   2. 
   3. Tools are usually designed to be used in a variety of ways (although some
   4. may only offer one if they choose):
   5. 
   6.     Library calls:
   7.         All tools are callables that can be used wherever needed.
   8.         The arguments are straightforward and should be detailed within the
   9.         docstring.
  10. 
  11.     Function decorators:
  12.         All tools, when called, may be used as decorators which configure
  13.         individual CherryPy page handlers (methods on the CherryPy tree).
  14.         That is, "@tools.anytool()" should "turn on" the tool via the
  15.         decorated function's _cp_config attribute.
  16. 
  17.     CherryPy config:
  18.         If a tool exposes a "_setup" callable, it will be called
  19.         once per Request (if the feature is "turned on" via config).
  20. 
  21. Tools may be implemented as any object with a namespace. The builtins
  22. are generally either modules or instances of the tools.Tool class.
  23. """
  24. 
  25. import cherrypy
  26. 
  27. 
  28. class Tool(object):
  29.     """A registered function for use with CherryPy request-processing hooks.
  30. 
  31.     help(tool.callable) should give you more information about this Tool.
  32.     """
  33. 
  34.     namespace = "tools"
  35. 
  36.     def __init__(self, point, callable, name=None, priority=50):
  37.         self._point = point
  38.         self.callable = callable
  39.         self._name = name
  40.         self._priority = priority
  41.         self.__doc__ = self.callable.__doc__
  42.         self._setargs()
  43. 
  44.     def _setargs(self):
  45.         """Copy func parameter names to obj attributes."""
  46.         try:
  47.             import inspect
  48.             for arg in inspect.getargspec(self.callable)[0]:
  49.                 setattr(self, arg, None)
  50.         except (ImportError, AttributeError):
  51.             pass
  52.         except TypeError:
  53.             if hasattr(self.callable, "__call__"):
  54.                 for arg in inspect.getargspec(self.callable.__call__)[0]:
  55.                     setattr(self, arg, None)
  56.         # IronPython 1.0 raises NotImplementedError because
  57.         # inspect.getargspec tries to access Python bytecode
  58.         # in co_code attribute.
  59.         except NotImplementedError:
  60.             pass
  61. 
  62.     def _merged_args(self, d=None):
  63.         tm = cherrypy.request.toolmaps[self.namespace]
  64.         if self._name in tm:
  65.             conf = tm[self._name].copy()
  66.         else:
  67.             conf = {}
  68.         if d:
  69.             conf.update(d)
  70.         if "on" in conf:
  71.             del conf["on"]
  72.         return conf
  73. 
  74.     def __call__(self, *args, **kwargs):
  75.         """Compile-time decorator (turn on the tool in config).
  76. 
  77.         For example:
  78. 
  79.             @tools.proxy()
  80.             def whats_my_base(self):
  81.                 return cherrypy.request.base
  82.             whats_my_base.exposed = True
  83.         """
  84.         if args:
  85.             raise TypeError("The %r Tool does not accept positional "
  86.                             "arguments; you must use keyword arguments."
  87.                             % self._name)
  88.         def tool_decorator(f):
  89.             if not hasattr(f, "_cp_config"):
  90.                 f._cp_config = {}
  91.             subspace = self.namespace + "." + self._name + "."
  92.             f._cp_config[subspace + "on"] = True
  93.             for k, v in kwargs.iteritems():
  94.                 f._cp_config[subspace + k] = v
  95.             return f
  96.         return tool_decorator
  97. 
  98.     def _setup(self):
  99.         """Hook this tool into cherrypy.request.
 100. 
 101.         The standard CherryPy request object will automatically call this
 102.         method when the tool is "turned on" in config.
 103.         """
 104.         conf = self._merged_args()
 105.         p = conf.pop("priority", None)
 106.         if p is None:
 107.             p = getattr(self.callable, "priority", self._priority)
 108.         cherrypy.request.hooks.attach(self._point, self.callable,
 109.                                       priority=p, **conf)
 110. 
 111. 
 112. class HandlerTool(Tool):
 113.     """Tool which is called 'before main', that may skip normal handlers.
 114. 
 115.     If the tool successfully handles the request (by setting response.body),
 116.     if should return True. This will cause CherryPy to skip any 'normal' page
 117.     handler. If the tool did not handle the request, it should return False
 118.     to tell CherryPy to continue on and call the normal page handler. If the
 119.     tool is declared AS a page handler (see the 'handler' method), returning
 120.     False will raise NotFound.
 121.     """
 122. 
 123.     def __init__(self, callable, name=None):
 124.         Tool.__init__(self, 'before_handler', callable, name)
 125. 
 126.     def handler(self, *args, **kwargs):
 127.         """Use this tool as a CherryPy page handler.
 128. 
 129.         For example:
 130.             class Root:
 131.                 nav = tools.staticdir.handler(section="/nav", dir="nav",
 132.                                               root=absDir)
 133.         """
 134.         def handle_func(*a, **kw):
 135.             handled = self.callable(*args, **self._merged_args(kwargs))
 136.             if not handled:
 137.                 raise cherrypy.NotFound()
 138.             return cherrypy.response.body
 139.         handle_func.exposed = True
 140.         return handle_func
 141. 
 142.     def _wrapper(self, **kwargs):
 143.         if self.callable(**kwargs):
 144.             cherrypy.request.handler = None
 145. 
 146.     def _setup(self):
 147.         """Hook this tool into cherrypy.request.
 148. 
 149.         The standard CherryPy request object will automatically call this
 150.         method when the tool is "turned on" in config.
 151.         """
 152.         conf = self._merged_args()
 153.         p = conf.pop("priority", None)
 154.         if p is None:
 155.             p = getattr(self.callable, "priority", self._priority)
 156.         cherrypy.request.hooks.attach(self._point, self._wrapper,
 157.                                       priority=p, **conf)
 158. 
 159. 
 160. class ErrorTool(Tool):
 161.     """Tool which is used to replace the default request.error_response."""
 162. 
 163.     def __init__(self, callable, name=None):
 164.         Tool.__init__(self, None, callable, name)
 165. 
 166.     def _wrapper(self):
 167.         self.callable(**self._merged_args())
 168. 
 169.     def _setup(self):
 170.         """Hook this tool into cherrypy.request.
 171. 
 172.         The standard CherryPy request object will automatically call this
 173.         method when the tool is "turned on" in config.
 174.         """
 175.         cherrypy.request.error_response = self._wrapper
 176. 
 177. 
 178. #                              Builtin tools                              #
 179. 
 180. from cherrypy.lib import cptools, encoding, auth, static, tidy
 181. from cherrypy.lib import sessions as _sessions, xmlrpc as _xmlrpc
 182. from cherrypy.lib import caching as _caching, wsgiapp as _wsgiapp
 183. 
 184. 
 185. class SessionTool(Tool):
 186.     """Session Tool for CherryPy.
 187. 
 188.     sessions.locking:
 189.         When 'implicit' (the default), the session will be locked for you,
 190.             just before running the page handler.
 191.         When 'early', the session will be locked before reading the request
 192.             body. This is off by default for safety reasons; for example,
 193.             a large upload would block the session, denying an AJAX
 194.             progress meter (see http://www.cherrypy.org/ticket/630).
 195.         When 'explicit' (or any other value), you need to call
 196.             cherrypy.session.acquire_lock() yourself before using
 197.             session data.
 198.     """
 199. 
 200.     def __init__(self):
 201.         # _sessions.init must be bound after headers are read
 202.         Tool.__init__(self, 'before_request_body', _sessions.init)
 203. 
 204.     def _lock_session(self):
 205.         cherrypy._serving.session.acquire_lock()
 206. 
 207.     def _setup(self):
 208.         """Hook this tool into cherrypy.request.
 209. 
 210.         The standard CherryPy request object will automatically call this
 211.         method when the tool is "turned on" in config.
 212.         """
 213.         hooks = cherrypy.request.hooks
 214. 
 215.         conf = self._merged_args()
 216. 
 217.         p = conf.pop("priority", None)
 218.         if p is None:
 219.             p = getattr(self.callable, "priority", self._priority)
 220. 
 221.         hooks.attach(self._point, self.callable, priority=p, **conf)
 222. 
 223.         locking = conf.pop('locking', 'implicit')
 224.         if locking == 'implicit':
 225.             hooks.attach('before_handler', self._lock_session)
 226.         elif locking == 'early':
 227.             # Lock before the request body (but after _sessions.init runs!)
 228.             hooks.attach('before_request_body', self._lock_session,
 229.                          priority=60)
 230.         else:
 231.             # Don't lock
 232.             pass
 233. 
 234.         hooks.attach('before_finalize', _sessions.save)
 235.         hooks.attach('on_end_request', _sessions.close)
 236. 
 237. 
 238. class XMLRPCController(object):
 239. 
 240.     # Note we're hard-coding this into the 'tools' namespace. We could do
 241.     # a huge amount of work to make it relocatable, but the only reason why
 242.     # would be if someone actually disabled the default_toolbox. Meh.
 243.     _cp_config = {'tools.xmlrpc.on': True}
 244. 
 245.     def __call__(self, *vpath, **params):
 246.         rpcparams, rpcmethod = _xmlrpc.process_body()
 247. 
 248.         subhandler = self
 249.         for attr in str(rpcmethod).split('.'):
 250.             subhandler = getattr(subhandler, attr, None)
 251. 
 252.         if subhandler and getattr(subhandler, "exposed", False):
 253.             body = subhandler(*(vpath + rpcparams), **params)
 254. 
 255.         else:
 256.             # http://www.cherrypy.org/ticket/533
 257.             # if a method is not found, an xmlrpclib.Fault should be returned
 258.             # raising an exception here will do that; see
 259.             # cherrypy.lib.xmlrpc.on_error
 260.             raise Exception, 'method "%s" is not supported' % attr
 261. 
 262.         conf = cherrypy.request.toolmaps['tools'].get("xmlrpc", {})
 263.         _xmlrpc.respond(body,
 264.                         conf.get('encoding', 'utf-8'),
 265.                         conf.get('allow_none', 0))
 266.         return cherrypy.response.body
 267.     __call__.exposed = True
 268. 
 269.     index = __call__
 270. 
 271. 
 272. class WSGIAppTool(HandlerTool):
 273.     """A tool for running any WSGI middleware/application within CP.
 274. 
 275.     Here are the parameters:
 276. 
 277.     wsgi_app - any wsgi application callable
 278.     env_update - a dictionary with arbitrary keys and values to be
 279.                  merged with the WSGI environ dictionary.
 280. 
 281.     Example:
 282. 
 283.     class Whatever:
 284.         _cp_config = {'tools.wsgiapp.on': True,
 285.                       'tools.wsgiapp.app': some_app,
 286.                       'tools.wsgiapp.env': app_environ,
 287.                       }
 288.     """
 289. 
 290.     def _setup(self):
 291.         # Keep request body intact so the wsgi app can have its way with it.
 292.         cherrypy.request.process_request_body = False
 293.         HandlerTool._setup(self)
 294. 
 295. 
 296. class SessionAuthTool(HandlerTool):
 297. 
 298.     def _setargs(self):
 299.         for name in dir(cptools.SessionAuth):
 300.             if not name.startswith("__"):
 301.                 setattr(self, name, None)
 302. 
 303. 
 304. class CachingTool(Tool):
 305.     """Caching Tool for CherryPy."""
 306. 
 307.     def _wrapper(self, **kwargs):
 308.         request = cherrypy.request
 309.         if _caching.get(**kwargs):
 310.             request.handler = None
 311.         else:
 312.             if request.cacheable:
 313.                 # Note the devious technique here of adding hooks on the fly
 314.                 request.hooks.attach('before_finalize', _caching.tee_output,
 315.                                      priority = 90)
 316.     _wrapper.priority = 20
 317. 
 318.     def _setup(self):
 319.         """Hook caching into cherrypy.request."""
 320.         conf = self._merged_args()
 321. 
 322.         p = conf.pop("priority", None)
 323.         cherrypy.request.hooks.attach('before_handler', self._wrapper,
 324.                                       priority=p, **conf)
 325. 
 326. 
 327. 
 328. class Toolbox(object):
 329.     """A collection of Tools.
 330. 
 331.     This object also functions as a config namespace handler for itself.
 332.     """
 333. 
 334.     def __init__(self, namespace):
 335.         self.namespace = namespace
 336.         cherrypy.engine.request_class.namespaces[namespace] = self
 337. 
 338.     def __setattr__(self, name, value):
 339.         # If the Tool._name is None, supply it from the attribute name.
 340.         if isinstance(value, Tool):
 341.             if value._name is None:
 342.                 value._name = name
 343.             value.namespace = self.namespace
 344.         object.__setattr__(self, name, value)
 345. 
 346.     def __enter__(self):
 347.         """Populate request.toolmaps from tools specified in config."""
 348.         cherrypy.request.toolmaps[self.namespace] = map = {}
 349.         def populate(k, v):
 350.             toolname, arg = k.split(".", 1)
 351.             bucket = map.setdefault(toolname, {})
 352.             bucket[arg] = v
 353.         return populate
 354. 
 355.     def __exit__(self, exc_type, exc_val, exc_tb):
 356.         """Run tool._setup() for each tool in our toolmap."""
 357.         map = cherrypy.request.toolmaps.get(self.namespace)
 358.         if map:
 359.             for name, settings in map.items():
 360.                 if settings.get("on", False):
 361.                     tool = getattr(self, name)
 362.                     tool._setup()
 363. 
 364. 
 365. default_toolbox = _d = Toolbox("tools")
 366. _d.session_auth = SessionAuthTool(cptools.session_auth)
 367. _d.proxy = Tool('before_request_body', cptools.proxy, priority=30)
 368. _d.response_headers = Tool('on_start_resource', cptools.response_headers)
 369. _d.log_tracebacks = Tool('before_error_response', cptools.log_traceback)
 370. _d.log_headers = Tool('before_error_response', cptools.log_request_headers)
 371. _d.err_redirect = ErrorTool(cptools.redirect)
 372. _d.etags = Tool('before_finalize', cptools.validate_etags)
 373. _d.decode = Tool('before_handler', encoding.decode)
 374. # the order of encoding, gzip, caching is important
 375. _d.encode = Tool('before_finalize', encoding.encode, priority=70)
 376. _d.gzip = Tool('before_finalize', encoding.gzip, priority=80)
 377. _d.staticdir = HandlerTool(static.staticdir)
 378. _d.staticfile = HandlerTool(static.staticfile)
 379. _d.sessions = SessionTool()
 380. _d.xmlrpc = ErrorTool(_xmlrpc.on_error)
 381. _d.wsgiapp = WSGIAppTool(_wsgiapp.run)
 382. _d.caching = CachingTool('before_handler', _caching.get, 'caching')
 383. _d.expires = Tool('before_finalize', _caching.expires)
 384. _d.tidy = Tool('before_finalize', tidy.tidy)
 385. _d.nsgmls = Tool('before_finalize', tidy.nsgmls)
 386. _d.ignore_headers = Tool('before_request_body', cptools.ignore_headers)
 387. _d.referer = Tool('before_request_body', cptools.referer)
 388. _d.basic_auth = Tool('on_start_resource', auth.basic_auth)
 389. _d.digest_auth = Tool('on_start_resource', auth.digest_auth)
 390. _d.trailing_slash = Tool('before_handler', cptools.trailing_slash)
 391. _d.flatten = Tool('before_finalize', cptools.flatten)
 392. _d.accept = Tool('on_start_resource', cptools.accept)
 393. 
 394. del _d, cptools, encoding, auth, static, tidy