【问题标题】:django-tastypie to have JSON responsedjango-tastypie 有 JSON 响应
【发布时间】:2012-06-07 00:21:23
【问题描述】:

我的意思是,我希望在修改 obj_create() 时得到 JSON 响应。我已经实现了 UserSignUpResource(ModelResource) 并在 obj_create() 内部进行了一些验证,当它失败时,我提出了 BadRequest()。但是,这并不会丢弃 JSON。它会抛出 String。

知道我是否可以让它抛出 {'error': 184, 'message': 'This username already exists'} 格式?还是我不打算修改 obj_create()?或者我应该怎么做?

多多帮助,谢谢。

干杯, 米奇

【问题讨论】:

  • 我在 django-piston 中遇到了同样的问题,其中方便的错误响应类型是纯 html 响应。我必须将它们包装在我自己的自定义 JsonResponse 中,这样会重新格式化它。

标签: django tastypie


【解决方案1】:

您应该使用资源中的 error_response 方法。

类似:

    def obj_create(self, bundle, **kwargs):
        # Code that finds Some error
        my_errors = {"error": ["Some error"]}
            raise ImmediateHttpResponse(response=self.error_response(bundle.request, my_errors))

通常你会调用 super 并且错误应该来自于 sweetpie 验证过程。将自动抛出异常(错误字典保存在 bundle.errors 属性中)。

【讨论】:

    【解决方案2】:

    很简单,我刚刚在tastepies http 模块中创建了一个小辅助方法:

    import json
    
    #tastypies HttpResponse classes here...
    
    def create_json_response(data, http_response_class):
        return http_response_class(content=json.dumps(data), content_type="application/json; charset=utf-8")
    

    那么你可以简单地说:

    from tastypie.http import HttpNotFound, create_json_response
    
    #choose HttpNotFound, HttpCreated whatever...
    raise ImmediateHttpResponse(create_json_response({"error":"resource not found"}, HttpNotFound))
    

    【讨论】:

    • 我不认为在 sweetpie http 模块上创建一个方法是一个好主意。如果你真的需要在你的一些帮助模块中创建它,而不是在美味的馅饼上(尽管我认为你不需要它)。
    猜你喜欢
    • 1970-01-01
    • 2013-02-16
    • 2016-02-18
    • 2013-10-13
    • 2014-01-18
    • 1970-01-01
    • 2014-11-15
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多