【问题标题】:Python Flask/JSON: string indices must be integersPython Flask/JSON:字符串索引必须是整数
【发布时间】:2020-02-26 00:11:37
【问题描述】:

我正在尝试使用 Flask 编写一个网络服务器,例如具有以下功能:

@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=data["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 访问标题?

感谢您的帮助!

【问题讨论】:

    标签: python json python-3.x flask


    【解决方案1】:

    没有错。验证您是否使用正确的 MIME 媒体类型来发布 JSON,即 application/json。用这段代码测试你的 Flask 服务器,看看它是否正常工作。

    import requests
    
    response = requests.post('http://localhost:5000/v1/tasks', json={'title': "Test Task 2"})
    print(response.status_code)
    

    【讨论】:

    • 附注,刚运行烧瓶时,我看到了 * Serving Flask app "project1-backend.py" t。 * 环境:生产警告:这是一个开发服务器。不要在生产部署中使用它。请改用生产 WSGI 服务器。 * 调试模式:关闭 * Running on 0.0.0.0:5000 对于这个警告我需要注意什么?
    • 如果您只是在内部使用此服务器,用于部署或测试,您可以忽略此警告。但是,如果您假装在生产环境中运行您的服务器,则必须采取更多步骤。按照本教程flask.palletsprojects.com/en/1.1.x/tutorial/deploy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多