Tastypie以Json格式响应每个请求

时间:2013-10-07 06:31:41

标签: django json tastypie

我正在为我的项目工作Api,我正在使用Tastypie 9.9.0。我希望JSON格式的响应能用于PUT,POST和DELETE操作。

现有回复如状态201已创建,状态204无内容,状态410已停止。

必须以自定义格式回复。    例如

1.  {
        "resource_name": "user",
        "action":"password_reset",
        "status": "success" 
    }

2.  {
      "resource_name": "todo",
      "action":"insert",
      "status":"sucess",
    }
3.  {
      "resource_name": "todo",
      "action":"delete",
      "status":"sucess",
    }

这是我正在处理的代码。我不知道如何添加自定义响应消息

  class ToDoResource(ModelResource):
        user = fields.ToOneField(UserResource, 'user')

        class Meta:
            queryset = ToDo.objects.all()
            fields=['alert_time','description','status','user']
            resource_name = 'todo'
            filtering = {
                         'user': ALL_WITH_RELATIONS,
                         'alert_time': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'],
                        }
            serializer = Serializer()
            authentication= MyApiKeyAuthentication()
            authorization=Authorization()
            always_return_data = True
            allowed_methods = ['post','get','put','delete']


        def obj_create(self, bundle,request=None, **kwargs):
            if not request.user.is_superuser:
                try:
                    bundle.data.pop('user')
                except:
                    pass
            return super(ToDoResource, self).obj_create(bundle, request, user=request.user)

        def create_response(self, request, data):
            """
            Extracts the common "which-format/serialize/return-response" cycle.

            Mostly a useful shortcut/hook.
            """
            desired_format = self.determine_format(request)
            serialized = self.serialize(request, data, desired_format)
            return HttpResponse(content=serialized, content_type=build_content_type(desired_format))

        def apply_authorization_limits(self, request, object_list):
            return object_list.filter(user=request.user)

1 个答案:

答案 0 :(得分:0)

您可以在get_list(request, **kwargs)和/或get_object(request, **kwargs)

中添加/修改自定义数据

例如,

import json
from django.http import HttpResponse

class ToDoResource(ModelResource):
    # ... the rest of code
    def get_list(self, request, **kwargs):
        resp = super(ToDoResource, self).get_list(request, **kwargs)
        data = json.loads(resp.content)

        # ... the rest of code

        data['meta']['resource_name'] = self._meta.resource_name
        data['meta']['action'] = request.method
        data['meta']['status'] = ANY_STATUS

        # ... the rest of code

        data = json.dumps(data)

        return HttpResponse(data, mimetype='application/json', status=ANY_STATUS)