-
Notifications
You must be signed in to change notification settings - Fork 2
/
cities.py
99 lines (82 loc) · 2.74 KB
/
cities.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python3
""" objects that handles all default RestFul API actions for cities """
from models.city import City
from models.state import State
from models import storage
from api.v1.views import app_views
from flask import abort, jsonify, make_response, request
from flasgger.utils import swag_from
@app_views.route('/states/<state_id>/cities', methods=['GET'],
strict_slashes=False)
@swag_from('documentation/city/cities_by_state.yml', methods=['GET'])
def get_cities(state_id):
"""
Retrieves the list of all cities objects
of a specific State, or a specific city
"""
list_cities = []
state = storage.get(State, state_id)
if not state:
abort(404)
for city in state.cities:
list_cities.append(city.to_dict())
return jsonify(list_cities)
@app_views.route('/cities/<city_id>/', methods=['GET'], strict_slashes=False)
@swag_from('documentation/city/get_city.yml', methods=['GET'])
def get_city(city_id):
"""
Retrieves a specific city based on id
"""
city = storage.get(City, city_id)
if not city:
abort(404)
return jsonify(city.to_dict())
@app_views.route('/cities/<city_id>', methods=['DELETE'], strict_slashes=False)
@swag_from('documentation/city/delete_city.yml', methods=['DELETE'])
def delete_city(city_id):
"""
Deletes a city based on id provided
"""
city = storage.get(City, city_id)
if not city:
abort(404)
storage.delete(city)
storage.save()
return make_response(jsonify({}), 200)
@app_views.route('/states/<state_id>/cities', methods=['POST'],
strict_slashes=False)
@swag_from('documentation/city/post_city.yml', methods=['POST'])
def post_city(state_id):
"""
Creates a City
"""
state = storage.get(State, state_id)
if not state:
abort(404)
if not request.get_json():
abort(400, description="Not a JSON")
if 'name' not in request.get_json():
abort(400, description="Missing name")
data = request.get_json()
instance = City(**data)
instance.state_id = state.id
instance.save()
return make_response(jsonify(instance.to_dict()), 201)
@app_views.route('/cities/<city_id>', methods=['PUT'], strict_slashes=False)
@swag_from('documentation/city/put_city.yml', methods=['PUT'])
def put_city(city_id):
"""
Updates a City
"""
city = storage.get(City, city_id)
if not city:
abort(404)
if not request.get_json():
abort(400, description="Not a JSON")
ignore = ['id', 'state_id', 'created_at', 'updated_at']
data = request.get_json()
for key, value in data.items():
if key not in ignore:
setattr(city, key, value)
storage.save()
return make_response(jsonify(city.to_dict()), 200)