【问题标题】:Python (tastypie) - Bad request on POST, returns "error" dictPython (tastypie) - POST 上的错误请求,返回“错误”字典
【发布时间】:2014-05-17 20:00:45
【问题描述】:

我正在尝试使用 Tastypie 将数据发送到我的 Django 驱动的服务器。

我有这个模型

class Open(models.Model):
    name=models.TextField()

还有这个 URLconf

open_resource=OpenResource()

urlpatterns = patterns('',
    url(r'^api/', include(open_resource.urls)),
    url(r'^admin/', include(admin.site.urls)),
)

当我运行 sweetpie 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": ""}

我已经尝试了所有方法,但似乎无法正常工作。

有人知道这个吗?

提前非常感谢

【问题讨论】:

  • 你试过 GET 吗?它是工作还是给出相同的错误?.. 默认情况下只允许 GET,但在这种情况下应该返回 501 或 405 而不是 400 .. 只是为了确保请尝试 GET 一次

标签: python json django http tastypie


【解决方案1】:

每当我提供无效的 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 validator 仔细检查。

【讨论】:

  • 我在对象的最后一个元素后面多了一个逗号,这导致了错误。至少可以说这是一个相当无益的错误。
【解决方案2】:

由于 sweetpie 使用 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()  

因为默认情况下,tastepie 使用 ReadOnlyAuthorization 设置资源,禁止发布、放置访问。

更多信息请阅读文档:https://django-tastypie.readthedocs.org

希望这会有所帮助,干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多