带Flask Restful的POST请求导致TypeError

时间:2020-03-10 19:46:27

标签: python flask flask-restful

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)

这是我的代码。尝试通过邮递员发出发帖请求:

http://127.0.0.1:5000/item/chair

这是身体:

{
    "price": 15.99
}

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

TypeError:“ NoneType”对象不可下标

为什么我的数据会导致这种情况?有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您的问题是您的POST请求没有正确填写其标题。使用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的其余部分。您的代码没有错;发出邮递员请求时,您需要指定`Content-Type:application / json“标头。

答案 1 :(得分:1)

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

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