-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathplaces.py
More file actions
executable file
·79 lines (68 loc) · 2.21 KB
/
Copy pathplaces.py
File metadata and controls
executable file
·79 lines (68 loc) · 2.21 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
#!/usr/bin/python3
""" Places """
from api.v1.views import app_views
from flask import jsonify, request, abort
from models import storage
from models.city import City
from models.place import Place
from models.user import User
@app_views.route('/cities/<city_id>/places',
methods=['GET'], strict_slashes=False)
def get_places(city_id):
"""Retrieve all places of a city"""
city = storage.get(City, city_id)
if not city:
abort(404)
places = [place.to_dict() for place in city.places]
return jsonify(places)
@app_views.route('/places/<place_id>', methods=['GET'], strict_slashes=False)
def get_place(place_id):
"""Retrieve a place"""
place = storage.get(Place, place_id)
if not place:
abort(404)
return jsonify(place.to_dict())
@app_views.route('/places/<place_id>',
methods=['DELETE'], strict_slashes=False)
def delete_place(place_id):
"""Deletes a place"""
place = storage.get(Place, place_id)
if not place:
abort(404)
storage.delete(place)
storage.save()
return jsonify({}), 200
@app_views.route('/cities/<city_id>/places',
methods=['POST'], strict_slashes=False)
def create_place(city_id):
"""Create a Place"""
payload = request.get_json()
if not payload:
abort(400, "Not a JSON")
city = storage.get(City, city_id)
if not city:
abort(404)
if 'user_id' not in payload:
abort(400, "Missing user_id")
user = storage.get(User, payload['user_id'])
if not user:
abort(404)
if 'name' not in payload:
abort(400, "Missing name")
place = Place(city_id=city_id, **payload)
place.save()
return jsonify(place.to_dict()), 201
@app_views.route('/places/<place_id>', methods=['PUT'], strict_slashes=False)
def update_place(place_id):
"""Updates a Place object"""
payload = request.get_json()
if not payload:
abort(400, "Not a JSON")
place = storage.get(Place, place_id)
if not place:
abort(404)
for key, value in payload.items():
if key not in ['id', 'user_id', 'city_id', 'created_at', 'updated_at']:
setattr(place, key, value)
place.save()
return jsonify(place.to_dict()), 200