Python/JSON:字符串索引必须是整数
我正在尝试使用Flask编写一个Web服务器,例如,具有以下post功能:Python/JSON:字符串索引必须是整数,python,json,python-3.x,flask,Python,Json,Python 3.x,Flask,我正在尝试使用Flask编写一个Web服务器,例如,具有以下post功能: @app.route('/v1/tasks', methods=['POST']) def post(): data=request.get_json() title=data["title"] tasks.append(json.dumps({"id": len(tasks), "title": title, "is_completed": "false"})) index=len(ta
@app.route('/v1/tasks', methods=['POST'])
def post():
data=request.get_json()
title=data["title"]
tasks.append(json.dumps({"id": len(tasks), "title": title, "is_completed": "false"}))
index=len(tasks)-1
return json.dumps({"id":index}), 200
title=数据[title]引发以下错误:
TypeError: string indices must be integers
POST的输入格式应为:
{title: "Test Task 2"}
我很困惑,因为我看到了一个不同的post函数,在这里访问JSON的内容是这样工作的:
@app.route('/post', methods=['POST'])
def post():
data=request.get_json()
dictionary[data["key"]]=data["value"]
data["message"]="success"
return json.dumps(data)
我需要更改什么才能从输入JSON访问标题
谢谢你的帮助 没有什么不对的。验证是否使用正确的MIME媒体类型发布JSON,即application/JSON。使用此代码测试Flask服务器,看看它是否正常工作
import requests
response = requests.post('http://localhost:5000/v1/tasks', json={'title': "Test Task 2"})
print(response.status_code)
另一方面,在运行flask时,我看到*Serving flask app project1-backend.py t.*环境:生产警告:这是一台开发服务器。不要在生产部署中使用它。请改用生产WSGI服务器。*调试模式:off*Running on是否需要记住此警告?如果您只是在内部使用此服务器进行部署或测试,则可以忽略此警告。但如果您假装在生产环境中运行服务器,则必须采取更多步骤。遵循本教程