【问题标题】:Pyramid traversal HTTP PUT to URI that doesn't exist金字塔遍历 HTTP PUT 到不存在的 URI
【发布时间】:2013-06-06 01:05:05
【问题描述】:

所以我有一个金字塔遍历应用程序,我希望能够 PUT 到不存在的 URI。有没有办法在视图配置中做到这一点?

例如我有这个

@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

当然 put 不起作用。上下文在doesnotexist 上抛出了一个keyerror,但是在这种情况下如何让遍历器匹配一个视图?

【问题讨论】:

    标签: python pyramid traversal


    【解决方案1】:

    这听起来像是Group 对象的单独类,具有Group 上下文和UndefinedGroup 上下文。大多数视图都适用于Group,但您可以有一个特殊的方法来响应UndefinedGroup 对象的PUT 请求。请注意,UndefinedGroup 不应继承 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
    

    如果找不到Group,您的遍历树将负责创建UndefinedGroup 对象。

    【讨论】:

    • 好吧,这是有道理的。我希望不必定义额外的类。
    • 您可以避免定义额外的类,但是您的 GET/POST/etc 方法将不得不考虑Group 对象的两种状态。一种是真实的,一种是未定义的。这样你就没有UndefinedGroup 的视图,而这些 url 将是 404。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多