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:进行投递请求
http://127.0.0.1:5000/item/chair
这就是机身:
{
"price": 15.99
}
当进行Post请求时,我得到以下错误:
TypeError:"NoneType"对象不是可下标的
为什么我的数据会导致这种情况?有人能帮我吗?
确保将请求的Content-Type
标头配置为application/json
。如果请求mimetype的ContentType没有指示JSON,Flask的Request.get_json()
方法将返回None
。
请参阅Postman文档中有关配置请求标头的内容。
您的问题是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&cmd=resource&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&cmd=resource&f=console.png">
<script src="?__debugger__=yes&cmd=resource&f=jquery.js"></script>
<script src="?__debugger__=yes&cmd=resource&f=debugger.js"></script>
<script type="text/javascript">
var TRACEBACK = 140264881526352,
CONSOLE_MODE = false,
...
为了简洁起见,我删掉了HTML的其余部分。您的代码没有任何问题;当您发出Postman请求时,您需要指定`Content-Type:application/json"标头。