-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathamenities.py
More file actions
executable file
·67 lines (55 loc) · 1.87 KB
/
Copy pathamenities.py
File metadata and controls
executable file
·67 lines (55 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/python3
""" Amenities """
from flask import abort, jsonify, request
from api.v1.views import app_views
from models.amenity import Amenity
from models import storage
@app_views.route('/amenities', methods=['GET'])
def get_amenities():
"""retrieve all amenities"""
amenities = storage.all(Amenity).values()
amenities_list = []
for amenity in amenities:
amenities_list.append(amenity.to_dict())
return jsonify(amenities_list)
@app_views.route('/amenities/<amenity_id>', methods=['GET'])
def get_amenity(amenity_id):
"""get amenity by id"""
amenity = storage.get(Amenity, amenity_id)
if amenity is None:
abort(404)
return jsonify(amenity.to_dict())
@app_views.route('/amenities/<amenity_id>', methods=['DELETE'])
def delete_amenity(amenity_id):
"""Deletes an Amenity object"""
amenity = storage.get(Amenity, amenity_id)
if amenity is None:
abort(404)
storage.delete(amenity)
storage.save()
@app_views.route('/amenities', methods=['POST'])
def create_amenity():
"""Creates an Amenity object"""
if not request.get_json():
abort(400, 'Not a JSON')
if 'name' not in request.get_json():
abort(400, 'Missing name')
amenity = Amenity(**request.get_json())
storage.new(amenity)
storage.save()
return jsonify(amenity.to_dict()), '201'
@app_views.route('/amenities/<amenity_id>', methods=['PUT'])
def update_amenity(amenity_id):
"""Updates an Amenity object"""
amenity = storage.get(Amenity, amenity_id)
if amenity is None:
abort(404)
if not request.get_json():
abort(400, 'Not a JSON')
payload = request.get_json()
ignore_keys = ['id', 'created_at', 'updated_at']
for key, value in payload.items():
if key not in ignore_keys:
setattr(amenity, key, value)
storage.save()
return jsonify(amenity.to_dict()), '200'