Python (tastypie) - POST请求错误,返回"error"字典
我正在尝试使用Tastypie将数据发送到我的Django服务器。
我有这个模型
class Open(models.Model):
name=models.TextField()
还有这个URL配置
open_resource=OpenResource()
urlpatterns = patterns('',
url(r'^api/', include(open_resource.urls)),
url(r'^admin/', include(admin.site.urls)),
)
当我运行tastypie的curl命令时
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name","awdawd"}' http://localhost:8000/api/open/
我遇到了这个错误
HTTP/1.0 400 BAD REQUEST
Date: Sat, 05 Apr 2014 12:18:48 GMT
Server: WSGIServer/0.1 Python/2.7.3
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
{"error": ""}
我尝试了所有方法,但还是无法解决这个问题。
有没有人知道该怎么回事?
非常感谢大家的帮助!
2 个回答
0
因为tastypie是用来处理JSON数据的,所以你也需要提供这种格式的数据。
--data '{"name": "myName"}'
另外,我不太确定你是怎么构建你的网址的,但我可以给你展示一个有效的网址设置:
v1_api = Api(api_name='v1')
v1_api.register(OpenResource())
urlpatterns = patterns('',
url(r'^api/', include(v1_api.urls)),
...
}
这样就会创建一个可以访问你资源的网址:
/api/v1/open/?format=json
最后,这会变成这个curl命令:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name": "myName"}' http://localhost:8000/api/v1/open/
别忘了在你的资源的元数据中添加授权和认证信息。
OpenResource(ModelResource)
class Meta:
queryset = Open.objects.all()
authorization = Authorization()
默认情况下,tastypie会把资源设置为只读权限,这样就不允许进行添加或修改操作。
想了解更多信息,可以查看文档: https://django-tastypie.readthedocs.org
希望这些对你有帮助,祝好!
2
每当我提供无效的JSON数据时,就会出现这个没什么帮助的错误。
正确的 JSON格式是:
{"foo": "bar"} // correct!
[{"foo": "bar"}, {"fiz": "baz"}] // correct!
{"foo": "bar", "fiz": "baz"} // correct!
一些常见的错误示例:
{'foo': 'bar'} // error is using single quotes instead of double quotes
{foo: "bar"} // error is not using double quotes for "foo"
{"foo", "bar"} // error is using a comma (,) instead of a colon (:) ← Your error
一些更复杂的错误示例:
[{"foo": "bar"}, {"fiz": "baz"},]
// error is using a comma at the end of a list or array
{"foo": "bar", "fiz": "baz",} // courtesy @gthmb
// error is using a comma at the end of the final key-value pair
觉得你的JSON是有效的吗?可以用JSON验证工具再检查一下。