-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathcities.py
More file actions
executable file
·103 lines (83 loc) · 2.47 KB
/
Copy pathcities.py
File metadata and controls
executable file
·103 lines (83 loc) · 2.47 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
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
100
101
102
103
#!/usr/bin/python3
"""
Cities API view for handling RESTful actions
"""
from flask import jsonify, request, abort
from api.v1.views import app_views
from models import storage
from models.city import City
from models.state import State
@app_views.route(
'/states/<state_id>/cities',
methods=['GET'],
strict_slashes=False
)
def get_cities(state_id):
"""
Retrieve all cities of a given state
"""
state = storage.get(State, state_id)
if not state:
abort(404)
return jsonify([city.to_dict() for city in state.cities])
@app_views.route('/cities/<city_id>', methods=['GET'], strict_slashes=False)
def get_city(city_id):
"""
Retrieve a single city identified by ID
"""
city = storage.get(City, city_id)
if not city:
abort(404)
return jsonify(city.to_dict())
@app_views.route(
'/states/<state_id>/cities',
methods=['POST'],
strict_slashes=False
)
def create_city(state_id):
"""
Create a new City in a given State
"""
state = storage.get(State, state_id)
if not state:
abort(404)
if request.content_type != 'application/json':
return jsonify({"error": "Not a JSON"}), 400
data = request.get_json()
if not data:
abort(400, description="Not a JSON")
if 'name' not in data:
abort(400, description="Missing name")
new_city = City(name=request.json['name'], state_id=state_id)
new_city.save()
return jsonify(new_city.to_dict()), 201
@app_views.route('/cities/<city_id>', methods=['PUT'], strict_slashes=False)
def update_city(city_id):
"""
Update a City object idenfified by valid city id
"""
city = storage.get(City, city_id)
if not city:
abort(404)
if request.content_type != 'application/json':
return jsonify({"error": "Not a JSON"}), 400
data = request.get_json()
if not data:
return jsonify({"error": "Not a JSON"}), 400
ignored_keys = ["id", "created_at", "updated_at"]
for key, value in data.items():
if key not in ignored_keys:
setattr(city, key, value)
city.save()
return jsonify(city.to_dict()), 200
@app_views.route('/cities/<city_id>', methods=['DELETE'], strict_slashes=False)
def delete_city(city_id):
"""
Delete a City object identified by city id
"""
city = storage.get(City, city_id)
if not city:
abort(404)
storage.delete(city)
storage.save()
return jsonify({}), 200