2014-02-15 28 views
3

我在用django使用tastypie。我有一个代码行:Tastypie反序列化结果{“error”:“”}

data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) 

我使用此代码通过命令行来发送POST请求到我的web服务器:

curl -X post -d "{ 'username' : 'user', 'password' : 'password' }" http://127.0.0.1:8000/api/employee/login/ --header "Content-Type:application/json" 

当我运行它,它导致的JSON响应

{"error": ""} 

看着我的服务器日志我看到:

[15/Feb/2014 20:39:49] "post /api/user/login/ HTTP/1.1" 400 13 

在反序列化行之前记录的日志消息将成功记录,但是在反序列化行之后立即记录日志消息将不会被记录,所以我非常确定反序列化是错误的。有谁知道什么可能是错的,或者如果我应该考虑其他问题?

回答

5

您的JSON无效。请检查它here。 400(不好的请求)状态应该给你提供线索。它应该是:{"username": "user", "password": "password"}Here你有一些解决方法如何在CURL命令中使用" char。不幸的是,Tastypie在没有消息的情况下引发异常,但我们可以轻松解决这个问题,以便为将来使用您的API的其他人节省时间。

from tastypie.exceptions import BadRequest 
from tastypie.serializers import Serializer 
class VerboseSerializer(Serializer): 
    """ 
    Gives message when loading JSON fails. 
    """ 
    # Tastypie>=0.9.6,<=0.11.0 
    def from_json(self, content): 
     """ 
     Override method of `Serializer.from_json`. Adds exception message when loading JSON fails. 
     """ 
     try: 
      return json.loads(content) 
     except ValueError as e: 
      raise BadRequest(u"Incorrect JSON format: Reason: \"{}\" (See www.json.org for more info.)".format(e.message)) 

class MyResource(BaseModelResource): 
    class Meta: 
     serializer = VerboseSerializer(formats=['json']) 
+0

我正面临这个“名称”串行器“未定义”的错误。谢谢 –

+0

上面的问题,它是固定的,一旦我从'tastypie.serializers'导入'串行器'。 –