-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.py
252 lines (207 loc) · 8.81 KB
/
event.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""Defines the event-related endpoints."""
from logging import getLogger
from datetime import date
from backend import db
from models.models import Event
from flask import request
from flask_restful import Resource, reqparse
from sqlalchemy.exc import SQLAlchemyError, InvalidRequestError, NoResultFound
import json
logger = getLogger()
# Initialize a parser for the request parameters
parser = reqparse.RequestParser(trim=True)
class EventCollectionApi(Resource):
"""
Endpoint: /api/v1/all_events
Methods: GET
"""
@staticmethod
def get() -> json:
"""Return all events from the database"""
logger.debug("Start of EventCollectionAPI.GET")
logger.debug(request)
# Retrieve all events from the db, sorted by id
try:
events = Event.query.order_by(Event.id).all()
logger.info("Events retrieved successfully!")
except SQLAlchemyError as e:
error_msg = f"SQLAlchemyError retrieving data: {e}"
logger.info(error_msg)
logger.debug("End of EventCollectionAPI.GET")
return error_msg, 500
except BaseException as e:
error_msg = f"BaseException retrieving data: {e}"
logger.info(error_msg)
logger.debug("End of EventCollectionAPI.GET")
return error_msg, 500
# Compile these data into a list
try:
output = []
for event in events:
output.append(event.to_dict())
logger.debug("End of EventAPI.GET")
return output, 200
except BaseException as e:
error_msg = f"Error compiling data into a list of `dict` to return: {e}"
logger.info(error_msg)
logger.debug("End of EventCollectionAPI.GET")
return error_msg, 500
class EventApi(Resource):
"""
Endpoint: /api/v1/event
Methods: GET, POST, PUT, DELETE
"""
@staticmethod
def get() -> json:
"""Return data for the specified event id"""
logger.debug(f"Start of EventAPI.GET")
logger.debug(request)
# Define the parameters used by this endpoint
parser.add_argument("id", type=int, nullable=False, store_missing=False,
required=True)
# Parse the provided arguments
args = parser.parse_args()
logger.debug(f"Args parsed successfully: {args.__str__()}")
# Validate that an event id was provided
try:
event_id = args["id"]
logger.debug(f"Event id={event_id} was read successfully")
except KeyError as e:
error_msg = f"Error parsing event id: no value was provided. {e}"
logger.info(error_msg)
return error_msg, 400
# Retrieve the selected record
try:
event = Event.query.get(event_id)
if event:
# Record successfully returned from the db
logger.info(f"Found the requested event: {event.to_dict()}")
logger.debug("End of EventAPI.GET")
return event.to_dict(), 200
else:
# No record with this id exists in the db
error_msg = f"No records found for event id={event_id}."
logger.debug(error_msg)
logger.debug("End of EventAPI.GET")
return error_msg, 404
except (InvalidRequestError, NoResultFound, AttributeError) as e:
error_msg = f"No records found for event id={event_id}.\n{e}"
logger.debug(error_msg)
logger.debug(f"End of EventAPI.GET")
return error_msg, 404
@staticmethod
def post() -> json:
"""Add a new event record to the database"""
logger.debug(f"Start of EventAPI.POST")
logger.debug(request)
# Define the parameters used by this endpoint
parser.add_argument("name", type=str)
parser.add_argument("date", type=str)
parser.add_argument("year", type=int)
parser.add_argument("is_archived", type=str)
parser.add_argument("notes", type=str)
# Parse the arguments provided
args = parser.parse_args()
logger.debug(f"Args parsed successfully: {args.__str__()}")
# Create a new Event record using the provided data
try:
logger.debug(f"Attempting to create a Event from the args.")
new_event = Event(**args.__str__())
logger.info(f"New record successfully created: {new_event.to_dict()}")
# Commit this new record so the db generates an id
logger.debug("Attempting to commit data")
db.session.commit()
logger.debug("Commit completed")
# Return the event id to the requester
logger.debug("End of EventAPI.POST")
return new_event.id, 201
except SQLAlchemyError as e:
error_msg = f"Unable to create a new Event record.\n{e}"
logger.debug(error_msg)
logger.debug("End of EventAPI.POST")
return error_msg, 500
@staticmethod
def put() -> json:
"""Update an existing record by event id"""
logger.debug(f"Start of EventAPI.PUT")
logger.debug(request)
# Define the parameters used by this endpoint
parser.add_argument("name", type=str)
parser.add_argument("date", type=date)
parser.add_argument("year", type=int)
parser.add_argument("is_archived", type=str)
parser.add_argument("notes", type=str)
# Parse the arguments provided
args = parser.parse_args()
logger.debug(f"Args parsed successfully: {args.__str__()}")
# Validate that an event_id was provided
try:
event_id = args["id"]
logger.debug(f"Event id={event_id} was read successfully")
except KeyError as e:
logger.info(f"Error parsing event id: no value was provided. {e}")
return f"Must provide a value for event id.", 400
try:
# Retrieve the specified event record
event = Event.query.get(event_id)
# Update this record with the provided data
event.name = args["name"]
event.date = args["date"]
event.year = args["year"]
event.is_archived = args["is_archived"]
event.notes = args["notes"]
# Commit these changes to the db
logger.debug("Attempting to commit db changes")
db.session.commit()
logger.info("Changes saved to the database")
logger.debug("End of EventAPI.PUT")
return event.id, 200
except SQLAlchemyError as e:
error_msg = f"Unable to update Event record.\n{e}"
logger.debug(error_msg)
logger.debug("End of EventAPI.PUT")
return error_msg, 500
@staticmethod
def delete() -> json:
"""Delete the specified record by event id"""
logger.debug(f"Start of EventAPI.DELETE")
logger.debug(request)
# Define the parameters used by this endpoint
parser.add_argument("id", type=int, nullable=False, store_missing=False,
required=True)
# Parse the provided arguments
args = parser.parse_args()
logger.debug(f"Args parsed successfully: {args.__str__()}")
# Validate that an event id was provided
try:
event_id = args["id"]
logger.debug(f"Event id={event_id} was read successfully")
except KeyError as e:
error_msg = f"Error parsing event id: no value was provided. {e}"
logger.info(error_msg)
logger.debug(f"End of EventAPI.DELETE")
return error_msg, 400
try:
# Retrieve the selected record
event = Event.query.get(event_id)
if event:
# Record successfully returned from the db
logger.debug(f"Event record found. Attempting to delete it.")
event.delete()
logger.debug("About to commit this delete to the db.")
db.session.commit()
logger.debug("Commit completed.")
logger.info("Event record successfully deleted.")
logger.debug("End of EventAPI.GET")
return event.to_dict(), 200
else:
# No record with this id exists in the db
error_msg = f"No record found for event id={event_id}."
logger.debug(error_msg)
logger.debug("End of EventAPI.GET")
return error_msg, 404
except (InvalidRequestError, NoResultFound, AttributeError) as e:
error_msg = f"No record found for event id={event_id}.\n{e}"
logger.debug(error_msg)
logger.debug(f"End of EventAPI.GET")
return error_msg, 404