Skip to content

Commit

Permalink
implement update user functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
kalsmic committed Jun 21, 2022
1 parent d0188b2 commit c794fe7
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
53 changes: 53 additions & 0 deletions api/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,56 @@ def create_user():
db.session.rollback()
return jsonify({'message': f'Username {username} already exists'}), 409
return jsonify(user.serialize), 201


@users_bp.route('/<int:user_id>', methods=['PUT'])
def update_user(user_id):
"""
Update a user.
___
parameters:
user_id: The id of the user.
body:
username: The username of the user.
returns:
- 200: OK
The user object.
- 400: Bad Request
message: Invalid request data.
- 404: Not Found
message:The user with the given id was not found.
- 409: Conflict
message: Username already exists.
"""
try:
user = User.query.get_or_404(user_id)
username = request.json['username']

if not validate_username(username):
raise BadRequest
if user.username == username:
return '', 204

username_already_assigned_another_user = User.query.filter(
User.id.notin_([user_id])).filter(User.username.ilike(username)).first()

if username_already_assigned_another_user:
raise Conflict

user.username = username
user.update()
except (BadRequest, KeyError):
print(sys.exc_info())
db.session.rollback()
return jsonify({'message': 'Invalid request data'}), 400
except (IntegrityError, Conflict):
print(sys.exc_info())
db.session.rollback()
return jsonify({'message': f'Username {username} already exists'}), 409
except NotFound:
print(sys.exc_info())
db.session.rollback()
return jsonify({'message': 'User not found'}), 404
return jsonify(user=user.serialize,
message="User Updated Successfully"), 200
2 changes: 1 addition & 1 deletion helpers/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ def is_username_in_db(username):
Returns UserObject if the username exists, None otherwise.
"""
if not username:
return False
return None
user = User.query.filter_by(username=username).first()
return user

0 comments on commit c794fe7

Please sign in to comment.