Question

I'm getting started with Pyramid, and am excited about traversal as a routing strategy. It seems natural and powerful. However, my thinking has led me down a questionable path. Can you suggest a better pattern?

I'm trying to implement a few RESTful routes. For example, I'd like to map the following:

  • GET /users -> index
  • GET /users/chris -> show
  • GET /users/new -> new
  • POST /users -> create
  • PUT /users/chris -> update
  • DELETE /users/chris -> destroy

It seems like the final context of the show and update actions ought to be the appropriate instance of User, but what about index and create? It seems like the User class itself would be an appropriate context, however the traversal mechanism, the __getitem__ method, can't be implemented on classes without some metaclass magic. It seemed like there might be a cleaner way to do this. Obviously I could create a UserResourceContainer whose only job would be to handle traversal, but I'm attracted to the elegance of using the User class. Thoughts?

Was it helpful?

Solution

Don't forget that you need a context for the views that map to /users. Having a single User class would make it quite difficult, and certainly not elegant.

My guess is that a separate UserContainer would be the simpler solution you can find. Depending on you database backend, you might even be able to do it in a generic way. For example, with SqlAlchemy:

class Container:
    def __getitem__(self, item):
        try:
            id = int(item)
            return DBSession.query(self.cls).filter_by(id=id).one()
        except (NoResultFound, ValueError):
            raise KeyError(item)

Then, your UserContainer is just:

class UserContainer(Container):
    cls = User

Elegant, isn't it ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top