ExposeItems
Utility class that exposes a getitem-aware object. It does not provide index() or default() methods, and it does not expose the individual item objects - just the list or dict that contains them. User-specific index() and default() methods can be implemented by inheriting from this class.
Rationale
The standard way of publishing objects in CherryPy is simple: just add the object to the cpg.root tree, and make sure that it has an attribute exposed = True. However, in some situations it is useful to publish container objects that don't fulfill all requirements. For example, lists and dicts - they may contain several objects that can be published, but the list (or dict) itself can't be published directly for two reasons.
- It does not have an exposed attribute, and one can't be directly added.
- It works with the getitem protocol, while CherryPy uses the getattr protocol for object mapping.
The ExposeItems utility class acts as a wrapper around getitem-aware objects. It adds the necessary functionality for CherryPy, and also allow for easy implementation of index() and default() methods.
Use cases
Exposing simple lists or dicts
from cherrypy.lib.cptools import ExposeItems ... cpg.root.foo = ExposeItems(mylist) # publishes a list object cpg.root.bar = ExposeItems(mydict) # publishes a dict object
In the code above, the following URLs will be mapped to the members of the list (or dict):
- /foo/1 maps to mylist[1]
- /bar/something maps to mydict['something']
It's up to the programmer to make sure that the actual objects referred to are properly exposed, and that they can be published via the Web. Also, if no object is found, then the standard behavior will be invoked - checks for a suitable default() method, and if one does not exist, raises an exception.
Adding custom index() & default() methods
from cherrypy.lib.cptools import ExposeItems ... class Foo(ExposeItems): def index(self, ...): ... index.exposed = True def default(self, ...): ... default.exposed = True ... cpg.root.foo = Foo(mylist)
Using ExposeItems as a decorator
from cherrypy.lib.cptools import ExposeItems as ExposedItems class Root: @ExposedItems def foo(self, ...): ...

