[Twisted-web] Leaf Resources with child Leaf Resources

Jonathan Jacobs jonathan+twisted at jsphere.com
Thu Mar 1 09:42:25 EST 2012

On Wed, Feb 29, 2012 at 23:00, Jacek Furmankiewicz <jacek99 at gmail.com> wrote:
> OK, so the issue I have is that I cannot create two separate REST Resources
> with nested URLs  e.g.
> class CustomerRestService(Resource):
>      """Handles REST operations for Customer /customer"""
>      pass
> class CustomerAddressRestService(Resource):
>      """Handles REST operations for Customer Address
> /customer/<customerId>/address"""
>      pass
> Instead I would need to have one common Resource that handles everything
> under '/customer',
> including the customer entity and customer address entity in one (and any
> other entity whose root is '/customer').

Perhaps I'm misunderstanding something here, but the idea with Twisted
resources (that aren't leaf resources) is not to have two things
handle the same path. The way the resource lookups work is that Site
loops through request.postpath from the root resource, locating child
resources one segment at a time, until it either runs out of path
segments *or* encounters a resource with isLeaf=True, that resource is
then rendered.

So in this example you might implement a CustomerIndexResource (that
exists at /customers) with a getChild method (/customers/<name>) that
creates a CustomerResource with some information (via a database call,
web service call, etc.). That CustomerResource then handles child
resource location for things like "address"
(/customers/<name>/address). This approach also makes it easier to do
things like swap out CustomerResource for ReadOnlyCustomerResource
that perhaps doesn't allow POST/PUT methods or prevents access to
certain child resources by not even having those child resources.

> That isn't a very good design...especially if you maybe have 50 different
> entities hooked up  under '/customer' (like in our app).
> It seems in order to enable having nice cohesive classes that provide a REST
> service for just one entity I would need to manually
> route the request from the root Resource into each of them myself.

You can easily design a plugin system or other programmatic method for
handling dynamic child dispatch for these 50 methods on a customer

Hope this helps.


More information about the Twisted-web mailing list