-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddress.py
265 lines (218 loc) · 9.83 KB
/
address.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
253
254
255
256
257
258
259
260
261
262
263
264
265
"""Defines the address-related endpoints."""
from logging import getLogger
from datetime import datetime, timezone
from backend import db
from models.models import Address
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 AddressCollectionApi(Resource):
"""
Endpoint: /api/v1/all_addresses
Methods: GET
"""
@staticmethod
def get() -> json:
"""Return all addresses from the database"""
logger.debug("Start of AddressCollectionAPI.GET")
logger.debug(request)
# Retrieve all addresses from the db, sorted by id
try:
addresses = Address.query.order_by(Address.id).all()
logger.info("Addresses retrieved successfully!")
except SQLAlchemyError as e:
error_msg = f"SQLAlchemyError retrieving data: {e}"
logger.info(error_msg)
logger.debug("End of AddressCollectionAPI.GET")
return error_msg, 500
except BaseException as e:
error_msg = f"BaseException retrieving data: {e}"
logger.info(error_msg)
logger.debug("End of AddressCollectionAPI.GET")
return error_msg, 500
# Compile these data into a list
try:
output = []
for address in addresses:
output.append(address.to_dict())
logger.debug("End of AddressCollectionAPI.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 AddressCollectionAPI.GET")
return error_msg, 500
class AddressApi(Resource):
"""
Endpoint: /api/v1/address
Methods: GET, POST, PUT, DELETE
"""
@staticmethod
def get() -> json:
"""Return data for the specified address id"""
logger.debug(f"Start of AddressAPI.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__()}")
address_id = args["id"]
# Retrieve the selected record
try:
address = Address.query.get(address_id)
if address:
# Record successfully returned from the db
logger.info(f"Address found!")
logger.debug("End of AddressAPI.GET")
return address.to_dict(), 200
else:
# No record with this id exists in the db
error_msg = f"No records found for address id={address_id}."
logger.info(error_msg)
logger.debug("End of AddressAPI.GET")
return error_msg, 404
except (InvalidRequestError, NoResultFound, AttributeError) as e:
error_msg = f"No records found for address id={address_id}.\n{e}"
logger.info(error_msg)
logger.debug(f"End of AddressAPI.GET")
return error_msg, 404
@staticmethod
def post() -> json:
"""Add a new address to the database"""
logger.debug(f"Start of AddressAPI.POST")
logger.debug(request)
# Define the parameters used by this endpoint
parser.add_argument("id", type=int, nullable=False, required=True)
parser.add_argument("line_1", type=str)
parser.add_argument("line_2", type=str)
parser.add_argument("city", type=str)
parser.add_argument("state", type=str)
parser.add_argument("zip", type=str)
parser.add_argument("country", type=str, default="United States")
parser.add_argument("is_current", type=str, default="True")
parser.add_argument("is_likely_to_change", type=str, default="False")
# Parse the arguments provided
args = parser.parse_args()
logger.debug(f"Args parsed successfully: {args.__str__()}")
# Create a new Address record using the provided data
try:
logger.debug(f"Attempting to create an Address from the args.")
new_address = Address(**args.__str__())
logger.info(f"New record successfully created: {new_address.to_dict()}")
# Set metadata for this new record
new_address.date_created = datetime.now(timezone.utc)
new_address.last_modified = new_address.date_created
# 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 newly created id to the requester
logger.debug("End of AddressAPI.POST")
return new_address.id, 201
except SQLAlchemyError as e:
error_msg = f"Unable to create a new Address record.\n{e}"
logger.debug(error_msg)
logger.debug("End of AddressAPI.POST")
return error_msg, 500
@staticmethod
def put() -> json:
"""Update an existing record by address_id"""
logger.debug(f"Start of AddressAPI.PUT")
logger.debug(request)
# Define the parameters used by this endpoint
parser.add_argument("id", type=int, nullable=False, store_missing=False)
parser.add_argument("household_id", type=int, nullable=False, required=True)
parser.add_argument("line_1", type=str)
parser.add_argument("line_2", type=str)
parser.add_argument("city", type=str)
parser.add_argument("state", type=str)
parser.add_argument("zip", type=str)
parser.add_argument("country", type=str, default="United States")
parser.add_argument("is_current", type=str, default="True")
parser.add_argument("is_likely_to_change", type=str, default="False")
parser.add_argument("notes", type=str)
# Parse the arguments provided
args = parser.parse_args()
logger.debug(f"Args parsed successfully: {args.__str__()}")
try:
# Retrieve the specified address record
address = Address.query.get(args["id"])
# Update this record with the provided data
address.households = args["households"]
address.line_1 = args["line_1"]
address.line_2 = args["line_2"]
address.city = args["city"]
address.state = args["state"]
address.zip = args["zip"]
address.country = args["country"]
address.is_current = args["is_current"]
address.is_likely_to_change = args["is_likely_to_change"]
address.notes = args["notes"]
# Update last_modified to the current timestamp
address.last_modified = datetime.now(timezone.utc)
# 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 AddressAPI.PUT")
return address.id, 200
except SQLAlchemyError as e:
error_msg = f"Unable to update Address record.\n{e}"
logger.debug(error_msg)
logger.debug("End of AddressAPI.PUT")
return error_msg, 500
@staticmethod
def delete() -> json:
"""Delete the specified record by address id"""
logger.debug(f"Start of AddressAPI.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 address id was provided
try:
address_id = args["id"]
logger.debug(f"Address id={address_id} was read successfully")
except KeyError as e:
error_msg = f"Error parsing `id`: no value was provided. {e}"
logger.info(error_msg)
logger.debug(f"End of AddressAPI.DELETE")
return error_msg, 400
# Retrieve the selected record
try:
address = Address.query.get(address_id)
if address:
# Record successfully returned from the db
logger.debug(f"Address record found, attempting to delete it.")
address.delete()
logger.debug("About to commit this DELETE to the db.")
db.session.commit()
logger.debug("Commit completed.")
logger.info("Address record successfully deleted.")
logger.debug(f"End of AddressAPI.DELETE")
return address.to_dict(), 200
else:
# No record with this id exists in the db
error_msg = f"No record found for address id={address_id}."
logger.info(error_msg)
logger.debug(f"End of AddressAPI.DELETE")
return error_msg, 404
except (InvalidRequestError, NoResultFound, AttributeError) as e:
error_msg = f"No record found for address id={address_id}.\n{e}"
logger.info(error_msg)
logger.debug(f"End of AddressAPI.DELETE")
return error_msg, 404
except SQLAlchemyError as e:
error_msg = f"SQLAlchemy error when attempting to delete address id={address_id}.\n{e}"
logger.info(error_msg)
logger.debug(f"End of AddressAPI.DELETE")
return error_msg, 500