2012-09-26 56 views
1

今天早上我遇到了一個我不知道如何解決的問題時,我正在用Tastypie開發我的Django REST API。 我有資源,看起來像這樣:返回異常錯誤作爲Tastypie中的JSON

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-格式化數據,並創建一個新的資源(我只permmit 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

+1

'e.response.content'似乎是一個字符串而不是字典。這就是爲什麼JSON序列化程序如此處理它。 – Wessie

回答

2

你可能想發送的響應內容爲JSON,而不是作爲一個序列化JSON字符串:??

import json 
bundle = {"code": 777, "status": False, "error": json.loads(e.response.content)} 
+0

非常感謝您的先生!有效! – Cibomank