0

我在我的新项目中使用tastepie 来创建一个RESTful API。我想为每种方法(Get、POST、PUT 和 DELETE)创建单独的函数并在其中处理不同的逻辑。我怎样才能做到这一点?

4

1 回答 1

1

您应该覆盖dispatch资源中的方法,并在那里创建您的每一个函数。如果您想做一些简单的逻辑,您可以将代码放在对 Resource original 的调用之后dispatch。代码看起来像这样:

def dispatch(self, request_type, request, **kwargs):
    response = super(Resource, self).dispatch(request_type, request, **kwargs)

    # Pass any parameters that you require to the functions
    if request.method == 'GET':
        custom_get()
    if request.method == 'POST':
        custom_post()
    if request.method == 'PUT':
        custom_put()
    if request.method == 'DELETE':
        custom_delete()

    return response

一般来说,它应该足以满足您的目的,除非您想对响应做一些更复杂的事情。

于 2013-08-30T11:01:21.013 回答