Created
August 29, 2020 09:13
-
-
Save jamescalam/80e28c599c052682db02bfec81658075 to your computer and use it in GitHub Desktop.
Example script of a PUT API method implemented with Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Users(Resource): | |
def put(self): | |
parser = reqparse.RequestParser() # initialize | |
parser.add_argument('userId', required=True) # add args | |
parser.add_argument('location', required=True) | |
args = parser.parse_args() # parse arguments to dictionary | |
# read our CSV | |
data = pd.read_csv('users.csv') | |
if args['userId'] in list(data['userId']): | |
# evaluate strings of lists to lists | |
data['locations'] = data['locations'].apply( | |
lambda x: ast.literal_eval(x) | |
) | |
# select our user | |
user_data = data[data['userId'] == args['userId']] | |
# update user's locations | |
user_data['locations'] = user_data['locations'].values[0] \ | |
.append(args['location']) | |
# save back to CSV | |
data.to_csv('users.csv', index=False) | |
# return data and 200 OK | |
return {'data': data.to_dict()}, 200 | |
else: | |
# otherwise the userId does not exist | |
return { | |
'message': f"'{args['userId']}' user not found." | |
}, 404 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment