-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstates.py
executable file
·92 lines (71 loc) · 2.46 KB
/
states.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
#!/usr/bin/python3
""" objects that handle all default RestFul API actions for States """
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', methods=['GET'], strict_slashes=False)
@swag_from('documentation/state/get_state.yml', methods=['GET'])
def get_states():
"""
Retrieves the list of all State objects
"""
all_states = storage.all(State).values()
list_states = []
for state in all_states:
list_states.append(state.to_dict())
return jsonify(list_states)
@app_views.route('/states/<state_id>', methods=['GET'], strict_slashes=False)
@swag_from('documentation/state/get_id_state.yml', methods=['get'])
def get_state(state_id):
""" Retrieves a specific State """
state = storage.get(State, state_id)
if not state:
abort(404)
return jsonify(state.to_dict())
@app_views.route('/states/<state_id>', methods=['DELETE'],
strict_slashes=False)
@swag_from('documentation/state/delete_state.yml', methods=['DELETE'])
def delete_state(state_id):
"""
Deletes a State Object
"""
state = storage.get(State, state_id)
if not state:
abort(404)
storage.delete(state)
storage.save()
return make_response(jsonify({}), 200)
@app_views.route('/states', methods=['POST'], strict_slashes=False)
@swag_from('documentation/state/post_state.yml', methods=['POST'])
def post_state():
"""
Creates a State
"""
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 = State(**data)
instance.save()
return make_response(jsonify(instance.to_dict()), 201)
@app_views.route('/states/<state_id>', methods=['PUT'], strict_slashes=False)
@swag_from('documentation/state/put_state.yml', methods=['PUT'])
def put_state(state_id):
"""
Updates a State
"""
state = storage.get(State, state_id)
if not state:
abort(404)
if not request.get_json():
abort(400, description="Not a JSON")
ignore = ['id', 'created_at', 'updated_at']
data = request.get_json()
for key, value in data.items():
if key not in ignore:
setattr(state, key, value)
storage.save()
return make_response(jsonify(state.to_dict()), 200)