forked from alexaorrico/AirBnB_clone_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcities.py
executable file
·88 lines (69 loc) · 2.16 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
#!/usr/bin/python3
""" View for City objects """
from flask import abort, jsonify, make_response, request
from api.v1.views import app_views
from models import storage
from models.city import City
from models.state import State
@app_views.route("/cities/<city_id>", methods=["GET"], strict_slashes=False)
def one_City(city_id):
"""
Retrieves a City object
"""
city_dict = storage.get(City, city_id)
if city_dict is None:
abort(404)
return jsonify(city_dict.to_dict())
@app_views.route("/states/<sid>/cities", methods=["GET"], strict_slashes=False)
def all_cities(sid):
"""
Retrieves the list of all City objects:
"""
states = storage.get(State, sid)
if not states:
abort(404)
cities_list = [city.to_dict() for city in states.cities]
return jsonify(cities_list)
@app_views.route("/cities/<city_id>", methods=["DELETE"])
def delete_City(city_id):
"""
Deletes a City object
"""
city = storage.get(City, city_id)
if city is None:
abort(404)
storage.delete(city)
storage.save()
return jsonify({}), 200
# use id instead of state_id in route
@app_views.route("/states/<id>/cities", methods=["POST"], strict_slashes=False)
def create_City(id):
"""
create new City object
id: state id
"""
if not request.get_json():
abort(400, description="Not a json")
data = request.get_json()
if data.get("name", None) is None:
abort(400, description="Missing name")
state = storage.get(State, id)
if not state:
abort(404)
city = City(**data)
city.state_id = state.id
city.save()
return make_response(jsonify(city.to_dict()), 201)
@app_views.route("/cities/<city_id>", methods=["PUT"], strict_slashes=False)
def update_City(city_id):
"""update City object"""
city = storage.get(City, city_id)
if not city:
abort(404)
if not request.get_json():
abort(400, description="Not a JSON")
for k, v in request.get_json().items():
if k not in ["id", "created_at", "updated_at", "state_id"]:
setattr(city, k, v)
storage.save()
return make_response(jsonify(city.to_dict()), 200)