1

今天早上,当我遇到一个我不知道如何解决的问题时,我正在使用 Tastypie 开发我的 Django REST API。我有一个看起来像这样的资源:

class UserSignUpResource(ModelResource):

    class Meta:
        object_class = User
        queryset = User.objects.all()
        allowed_methods = ['post']
        include_resource_uri = False
        resource_name = 'newuser'
        serializer = CamelCaseJSONSerializer(formats=['json'])
        authentication = Authentication()
        authorization = Authorization()
        always_return_data = True
        validation = FormValidation(form_class=UserSignUpForm)

此资源接收 JSON 格式的数据并创建一个新资源(我只允许 POST 操作)。因此,首先通过以下方式检查数据:

validation = FormValidation(form_class=UserSignUpForm)

问题是,如果数据不正确,它会返回一个ImmediateHttpResponse。但我想捕获这个异常并创建一个这样的 JSON:

{"status": False, "code": 777, "errors": {"pass":["Required"], ...}

因此,我覆盖了我的wrap_view并添加了以下代码片段:

except ImmediateHttpResponse, e:
    bundle = {"code": 777, "status": False, "error": e.response.content}
    return self.create_response(request, bundle, response_class = HttpBadRequest) 

这段代码正确地捕获了异常,但它有一个问题。e.response包含带有错误的 unicode 字符串。所以,它最终给出的回应是

{"code": 777, 
"error": "{\"birthdayDay\": [\"This field is required.\"], 
         \"birthdayMonth\": [\"This field is required.\"], 
         \"birthdayYear\": [\"This field is required.\"], 
         \"csrfmiddlewaretoken\": [\"This field is required.\"], 
         \"email\": [\"This field is required.\"], 
         \"email_2\": [\"This field is required.\"], 
         \"firstName\": [\"This field is required.\"], 
         \"gender\": [\"This field is required.\"], 
         \"lastName\": [\"This field is required.\"], 
         \"password1\": [\"This field is required.\"]}", 
"status": false}

该死的 \ 和第一个 " 正在杀死我。另一方面,正在使用 AJAX 的前端开发人员告诉我他无法解析错误。

我在这里做错什么了吗?有人知道如何将异常响应转换为 JSON 吗?

4

1 回答 1

2

您可能希望将响应内容作为 json 发送,而不是作为序列化的 json 字符串:

import json
bundle = {"code": 777, "status": False, "error": json.loads(e.response.content)}
于 2012-09-26T17:06:49.080 回答