2013-10-07 38 views
4

我正在爲我的項目使用Api,我正在使用Tastypie 9.9.0。我希望JSON格式的PUT,POST和DELETE操作響應。Tastypie以JSON格式響應每個請求

像STATUS 201 CREATED,STATUS 204 NO CONTENT,STATUS 410 GONE這樣的現有響應很好。

它必須以自定義格式進行響應。 例如

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", 
    } 

這是我工作的代碼。我不知道如何在get_list(request, **kwargs)和/或get_object(request, **kwargs)

例如添加自定義的響應消息

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) 
+0

目前尚不清楚是什麼' action'和'status'指的是http響應的上下文。 –

回答

0

您可以添加/修改自定義數據,

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)