Search code examples
pythonpyramidtraversal

Pyramid traversal HTTP PUT to URI that doesn't exist


So I have a pyramid traversal app and I'd like to be able to PUT to URIs that don't exist. Is there a way to do this in the view config?

So for example I have this

@view_defaults(context=models.Groups, renderer='json')
@view_config(request_method='GET')
class GroupsView(object):

    def __call__(self):
        ''' This URI corresponds to GET /groups '''
        pass

    @view_config(request_method='PUT')
    def put(self):
        ''' This URI should correspond to PUT /groups/doesnotexist '''
        pass

Of course the put doesn't work. The context throws a keyerror on doesnotexist, but how do I get the traverser to match a view in this case?


Solution

  • This sounds like a separate class for Group objects with a Group context and an UndefinedGroup context. Most views work on Group, but you could have a special method responding to PUT requests for UndefinedGroup objects. Note that UndefinedGroup should not subclass Group.

    @view_defaults(context=Group, renderer='json')
    class GroupView(object):
        def __init__(self, request):
            self.request = request
    
        @view_config(request_method='GET')
        def get(self):
            # return information about the group
    
        @view_config(context=UndefinedGroup, request_method='PUT')
        def put_new(self):
            # create a Group from the UndefinedGroup
    
        @view_config(request_method='PUT')
        def put_overwrite(self):
            # overwrite the old group with a new one
    

    Your traversal tree would then be responsible for creating an UndefinedGroup object if it cannot find a Group.