我在tastypie得到400 BAD REQUEST

时间:2014-07-21 13:50:18

标签: django tastypie

我正在使用tastypie。当我想将数据发布到我的服务器时,我得到了:

我的curl命令是:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{{"shop" : "/api/shop/1/","transactions" : [{"item" : "/api/item/53/","note" : "Normal"}]}' 'http://localhost:5000/api/order/'

回复是:

HTTP/1.0 400 BAD REQUEST
Date: Mon, 21 Jul 2014 13:41:52 GMT
Server: WSGIServer/0.1 Python/2.7.5
Access-Control-Allow-Headers: Origin,Content-Type,Accept
Content-Language: tr
Vary: Accept-Language, Cookie
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: text/html; charset=utf

表创建语法:

CREATE TABLE `t_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `table` varchar(100) NOT NULL,
  `shop_id` int(11) NOT NULL,
  `date_modified` datetime NOT NULL,
  `status` int(11) DEFAULT '0',
  `date_created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `shop_id_refs_id_d3748fa9` (`shop_id`),
  CONSTRAINT `shop_id_refs_id_d3748fa9` FOREIGN KEY (`shop_id`) REFERENCES `t_shop` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=231 DEFAULT CHARSET=utf8;

CREATE TABLE `t_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `note` varchar(500) NOT NULL,
  `item_id` int(11) NOT NULL,
  `closed` tinyint(1) NOT NULL,
  `date_modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `item_id_refs_id_348f1ee9` (`item_id`),
  KEY `order_id_refs_id_d9a0bcc6` (`order_id`),
  CONSTRAINT `item_id_refs_id_348f1ee9` FOREIGN KEY (`item_id`) REFERENCES `t_item` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8;

我的模特:

class Order(models.Model):
STATUSES = (
    (0, 'OPEN'),
    (1, 'CLOSED'),
    (2, 'CANCELLED'),
)
table = CharField(max_length=100)
shop = ForeignKey(Shop)
date_modified = DateTimeField(auto_now=True)
date_created = DateTimeField(auto_now_add=True)
status = IntegerField(choices=STATUSES)
class Meta:
        db_table = 't_order'

class Transaction(models.Model):
order = ForeignKey('Order')
note = CharField(max_length=500)
item = ForeignKey(Item)
closed = BooleanField(default=False)
date_modified = DateTimeField(auto_now=True)

class Meta:
        db_table = 't_transaction'

有什么问题?

1 个答案:

答案 0 :(得分:1)

您的JSON无效。请验证您的卷曲数据here。 400(错误的请求)状态应该给你线索。确保您可以创建可以处理该异常的序列化程序。

from tastypie.exceptions import BadRequest

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'])