【问题标题】:Tastypie deserialize results in {"error": ""}Tastypie 反序列化导致 {"error": ""}
【发布时间】:2014-03-15 05:39:17
【问题描述】:

我在 django 中使用了 sweetpie。我有一行代码:

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

我使用命令行中的这段代码向我的网络服务器发送一个发布请求:

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

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

【问题讨论】:

    标签: json django rest tastypie


    【解决方案1】:

    您的 JSON 无效。请检查它here。 400(错误请求)状态应该为您提供线索。应该是:{"username": "user", "password": "password"}Here 您有一些解决方案如何在 CURL 命令中转义 " 字符。不幸的是,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'])
    

    【讨论】:

    • 我正面临这个“名称'Serializer'未定义”错误。谢谢
    • 上述问题在我从 'tastypie.serializers' 导入 'Serializer' 后得到修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多