我正在查看官方的 Flask Restful 文档,但无法让他们的 put 和 post 请求正常工作。
https://flask-restful.readthedocs.io/en/latest/quickstart.html#full-example
我正在使用 Python 3.8、Flask 2.2.2 和 Flask-RESTful 0.3.9。
为了测试,我们发送curl 请求。获取和删除工作正常但用于发布:
curl http://localhost:5000/todos -d "task=something new" -X POST -v
* Connected to localhost (127.0.0.1) port 5000 (#0)
> POST /todos HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.83.1
> Accept: */*
> Content-Length: 18
> Content-Type: application/x-www-form-urlencoded
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 400 BAD REQUEST
< Server: Werkzeug/2.2.2 Python/3.8.1
< Date: Wed, 05 Oct 2022 18:04:54 GMT
< Content-Type: application/json
< Content-Length: 116
< Connection: close
<
{
"message": "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}
* Closing connection 0
我相信问题源于我发送 application/x-www-form-urlencoded。所以我需要发送json格式,对吗?我尝试了这个,但得到了同样的错误:
curl -X POST http://localhost:5000/todos -H 'Content-Type: application/json' -d '{"task":"something different"}'
{
"message": "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}
curl: (6) Could not resolve host: application
请求中我还需要什么?
我也从 POST 和 PUT 请求的官方文档示例中得到了同样的错误。我认为这是
curl
的问题,因为当我尝试使用Postman Desktop App时,我可以成功地发出POST和PUT请求。据我了解,curl
无法正确解释Content-Type
并导致此错误。
我与Postman的解决方案如下:
安装Postman后,在新的
collections
中,创建一个新的request
,并在其中添加一个名为Content-Type
的新密钥,并在application/json
下添加值Headers
。如果没有此密钥(或禁用),您将收到错误{ "message": "Did not attempt to load JSON data because the request Content-Type was not 'application/json'." }
现在使用
http://localhost:5000/todos
JSON 格式向 raw
发出 POST 请求 {"task": "Do that task2"}
这将附加
TODOS
字典,并添加新的 todoX
和新数字 X
根据 GET 请求,您可以看到更新的
TODOS
。 (这甚至可以使用curl
)
对于 PUT 请求,您可以再次在邮递员上使用新值
http://localhost:5000/todos/todo2
对 {"task": "Do mytask"}
进行 PUT,并将使用新值更新 "todo2"
。
我正在使用
flask 2.2.2
、werkzeug 2.2.2
、flask-restful 0.3.9
和 Python 3.9.13