Tastypie如何在注入Post数据后获得自定义Json Response

时间:2015-03-05 10:20:27

标签: json django tastypie

我希望在将sendind数据发布到我的Tastypie API模型django之后有自定义json响应。

class MyModelResource(ModelResource):

my_field=""
class Meta:
    queryset = MyModel.objects.all()
    resource_name = 'nick_name'
    authentication = ApiKeyAuthentication()
    authorization = DjangoAuthorization()


def hydrate(self, bundle):
    #on recupere les donnée injectée par bundle.data['title']
    #et on inject les donnée via bundle.obj.title


    #bundle.data['my_field'] ="1234"
    bundle.obj.my_field=bundle.data['my_field']
    self.my_field = bundle.data['my_field']



    return bundle





def wrap_view(self, view):
    """
    Wraps views to return custom error codes instead of generic 500's
    """
    @csrf_exempt
    def wrapper(request, *args, **kwargs):
        try:
            callback = getattr(self, view)
            response = callback(request, *args, **kwargs)

            if request.is_ajax():
                patch_cache_control(response, no_cache=True)



            lst_dic=[]
            mon_dic = dict(success=True,  my_field=self.my_field


                       )
            # response is a HttpResponse object, so follow Django's instructions
            # to change it to your needs before you return it.
            # https://docs.djangoproject.com/en/dev/ref/request-response/
            lst_dic.append(mon_dic)   

            response = HttpResponse(simplejson.dumps(lst_dic), content_type='application/json')
            return response
        except (BadRequest, fields.ApiFieldError), e:
            return HttpBadRequest({'success':False,'code': 666, 'message':e.args[0]})
        except ValidationError, e:
            # Or do some JSON wrapping around the standard 500
            return HttpBadRequest({'success':False,'code': 777, 'message':', '.join(e.messages)})
        except Exception, e:
            # Rather than re-raising, we're going to things similar to
            # what Django does. The difference is returning a serialized
            # error message.
            return self._handle_500(request, e)

    return wrapper 

我的问题在这里,我无法获取self.my_field值以放入mon_dic,我总是有数据对象,而不是值......

请求帮助

编辑:添加my_field全局变量,然后从包中获取值;)

1 个答案:

答案 0 :(得分:1)

也许我不明白你想在这里做什么。但wrap_view用于处理客户错误响应。如果你要做的只是返回发布的数据,你可以在Meta中将always_return_data设置为true:

class Meta:
     always_return_data = True 

或者,如果您想控制发回的数据,可以使用dehydrate方法:

def dehydrate(self, bundle):
    bundle.data['custom_field'] = "Whatever you want"
    return bundle
相关问题