使用 Python Flask Put 请求更新字典

Updating Dict with Python Flask Put Request

我想咨询如何使用 Put 请求更新字典

我想用 {“email”: “abc@bmail.com”}

更新下面字典中的电子邮件
users=[{"userid":1,"username":"John","email":"john@gmailer.com","role":"member","password":"abc123"}]

代码将检查 userid 是否存在,return if else。

但是,我无法附加 userEmail,因为它共享 dict 实例没有附加方法

@app.route('/users/<int:userid>', methods=["PUT"])
def addEmail(userid):

userEmail=request.json

reqUser = None
for user in users:
    if user['userid']==userid:
        reqUser=user
        break

if reqUser != None: 
    reqUser.append(userEmail)
    output={“User with <id> has been successfully updated!”}
    return jsonify(output),200
else:
    output={"Message":“User with <id> does not exist!”}
    return jsonify(output),404

或者,我尝试将密钥插入字典,但它也共享字典实例没有插入成员

@app.route('/users/<int:userid>', methods=["PUT"])
def addEmail(userid):

userEmail=request.json

reqUser = None
for user in users:
    if user['userid']==userid:
        reqUser=user
        break

if reqUser != None: 
    reqUser.insert(0,{
        "email":userEmail["email"]
    })
    
    output={"Message":"User Updated"}
    return jsonify(output),200
else:
    output={"Message":“User with <id> does not exist!”}
    return jsonify(output),404

怎样才能改变字典项?

方法 appendinsert 是列表的方法,dict 是 key/value 的映射,要添加新的映射,请执行以下操作:reqUser['email'] = user_email["email"]

在代码风格上做了一些改进:

@app.route('/users/<int:userid>', methods=["PUT"])
def addEmail(userid):
    user_email = request.json
    for user in users:
        if user['userid'] == userid:
            user["email"] = user_email["email"]
            return jsonify({"Message": "User Updated"})
    return jsonify({"Message": f"User with id={userid} does not exist!"}), 404