POST 使用 Flask Restful 的请求导致 TypeError

POST request with Flask Restful leads to TypeError

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

items = []

class Item(Resource):

    def post(self, name):
        data = request.get_json()
        item = {'name': name, 'price': data['price']}
        items.append(item)
        return item

api.add_resource(Item, "/item/<string:name>")


app.run(port=5000, debug=True)

这是我的代码。尝试用 Postman:

发出 post 请求
http://127.0.0.1:5000/item/chair

这是正文:

{
    "price": 15.99
}

在执行 Post 请求时,出现以下错误:

TypeError: 'NoneType' object is not subscriptable

为什么我的数据会这样?谁能帮帮我?

您的问题是您的 POST 请求没有正确填写其 header。使用 CURL 的快速测试证明了这一点:

vagrant@vagrant:~$ curl -d '{"price":15.99}' -H "Content-Type: application/json" -X POST http://localhost:5000/item/chair
{
    "name": "chair",
    "price": 15.99
}
vagrant@vagrant:~$ curl -d '{"price":15.99}' -X POST http://localhost:5000/item/chair
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>TypeError: 'NoneType' object has no attribute '__getitem__' // Werkzeug Debugger</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"
        type="text/css">
    <!-- We need to make sure this has a favicon so that the debugger does
         not by accident trigger a request to /favicon.ico which might
         change the application state. -->
    <link rel="shortcut icon"
        href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script type="text/javascript">
      var TRACEBACK = 140264881526352,
          CONSOLE_MODE = false,
...

为了简洁起见,我删除了 HTML 的其余部分。您的代码没有问题;您需要在发出 Postman 请求时指定 `Content-Type: application/json" header。

确保将请求的 Content-Type header 配置为 application/json。 Flask 的 Request.get_json() 方法 will return None 如果您的请求 mimetype 的 Content-Type 不表示 JSON。

请参阅 configuring request headers 上的 Postman 文档。