【问题标题】:POST request with Flask Restful leads to TypeError使用 Flask Restful 的 POST 请求导致 TypeError
【发布时间】:2020-03-10 19:46:27
【问题描述】:
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' 对象不可下标

为什么我的数据会导致这种情况?谁能帮帮我?

【问题讨论】:

  • 邮递员是否将您的内容类型发送为application/jsonget_json will return None 如果 mimetype 不指示 JSON。我猜这个错误与data['price'] 有关。 request.is_json 的结果是什么?

标签: python flask flask-restful


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您的问题是您的 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 的其余部分。您的代码没有任何问题;您需要在发出 Postman 请求时指定 `Content-Type: application/json" 标头。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 2020-08-15
      • 2018-08-31
      • 2018-07-05
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多