Search code examples
pythonflaskput

Updating Dict with Python Flask Put Request


I would like to seek advice on how to update a dict with a Put request

I would like to update the email in the dict below with {“email”: “abc@bmail.com”}

users=[{"userid":1,"username":"John","email":"john@gmailer.com","role":"member","password":"abc123"}]

The code will check if userid exists and return with if else.

However, I am unable to append userEmail as it shares that instance of dict has no append method

@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

Alternatively, I tried to insert the key into dict but it also shares that instance of dict has no insert members

@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

How would it be possible to change the dict item?


Solution

  • The methods append and insert are method of a list, a dict is a mapping of key/value, to add a new mapping do : reqUser['email'] = user_email["email"]

    With some improvements on the code style:

    @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