-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathmodels.py
263 lines (215 loc) · 8.44 KB
/
models.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
# Copyright 2016, 2024 John Rofrano. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Models for Pet Demo Service
All of the models are stored in this module
Models
------
Pet - A Pet used in the Pet Store
Attributes:
-----------
name (string) - the name of the pet
category (string) - the category the pet belongs to (i.e., dog, cat)
available (boolean) - True for pets that are available for adoption
gender (enum) - the gender of the pet
birthday (date) - the day the pet was born
"""
import os
import logging
from datetime import date
from enum import Enum
from retry import retry
from flask_sqlalchemy import SQLAlchemy
# global variables for retry (must be int)
RETRY_COUNT = int(os.environ.get("RETRY_COUNT", 5))
RETRY_DELAY = int(os.environ.get("RETRY_DELAY", 1))
RETRY_BACKOFF = int(os.environ.get("RETRY_BACKOFF", 2))
logger = logging.getLogger("flask.app")
# Create the SQLAlchemy object to be initialized later in init_db()
db = SQLAlchemy()
@retry(Exception, delay=RETRY_DELAY, backoff=RETRY_BACKOFF, tries=RETRY_COUNT, logger=logger)
def init_db() -> None:
"""Initialize Tables"""
db.create_all()
class DataValidationError(Exception):
"""Used for an data validation errors when deserializing"""
class Gender(Enum):
"""Enumeration of valid Pet Genders"""
MALE = 0
FEMALE = 1
UNKNOWN = 3
class Pet(db.Model):
"""
Class that represents a Pet
This version uses a relational database for persistence which is hidden
from us by SQLAlchemy's object relational mappings (ORM)
"""
##################################################
# Table Schema
##################################################
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(63), nullable=False)
category = db.Column(db.String(63), nullable=False)
available = db.Column(db.Boolean(), nullable=False, default=False)
gender = db.Column(
db.Enum(Gender), nullable=False, server_default=(Gender.UNKNOWN.name)
)
birthday = db.Column(db.Date(), nullable=False, default=date.today())
# Database auditing fields
created_at = db.Column(db.DateTime, default=db.func.now(), nullable=False)
last_updated = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now(), nullable=False)
##################################################
# INSTANCE METHODS
##################################################
def __repr__(self):
return f"<Pet {self.name} id=[{self.id}]>"
def create(self) -> None:
"""
Saves a Pet to the database
"""
logger.info("Creating %s", self.name)
# id must be none to generate next primary key
self.id = None # pylint: disable=invalid-name
try:
db.session.add(self)
db.session.commit()
except Exception as e:
db.session.rollback()
logger.error("Error creating record: %s", self)
raise DataValidationError(e) from e
def update(self) -> None:
"""
Updates a Pet to the database
"""
logger.info("Saving %s", self.name)
if not self.id:
raise DataValidationError("Update called with empty ID field")
try:
db.session.commit()
except Exception as e:
db.session.rollback()
logger.error("Error updating record: %s", self)
raise DataValidationError(e) from e
def delete(self) -> None:
"""
Removes a Pet from the database
"""
logger.info("Deleting %s", self.name)
try:
db.session.delete(self)
db.session.commit()
except Exception as e:
db.session.rollback()
logger.error("Error deleting record: %s", self)
raise DataValidationError(e) from e
def serialize(self) -> dict:
"""Serializes a Pet into a dictionary"""
return {
"id": self.id,
"name": self.name,
"category": self.category,
"available": self.available,
"gender": self.gender.name, # convert enum to string
"birthday": self.birthday.isoformat()
}
def deserialize(self, data: dict):
"""
Deserializes a Pet from a dictionary
Args:
data (dict): A dictionary containing the Pet data
"""
try:
self.name = data["name"]
self.category = data["category"]
if isinstance(data["available"], bool):
self.available = data["available"]
else:
raise DataValidationError(
"Invalid type for boolean [available]: "
+ str(type(data["available"]))
)
# self.gender = getattr(Gender, data["gender"]) # create enum from string
self.gender = Gender[data["gender"].upper()] # create enum from string
self.birthday = date.fromisoformat(data["birthday"])
except AttributeError as error:
raise DataValidationError("Invalid attribute: " + error.args[0]) from error
except KeyError as error:
raise DataValidationError("Invalid pet: missing " + error.args[0]) from error
except TypeError as error:
raise DataValidationError(
"Invalid pet: body of request contained bad or no data " + str(error)
) from error
return self
##################################################
# CLASS METHODS
##################################################
@classmethod
def all(cls) -> list:
"""Returns all of the Pets in the database"""
logger.info("Processing all Pets")
return cls.query.all()
@classmethod
def find(cls, pet_id: int):
"""Finds a Pet by it's ID
:param pet_id: the id of the Pet to find
:type pet_id: int
:return: an instance with the pet_id, or None if not found
:rtype: Pet
"""
logger.info("Processing lookup for id %s ...", pet_id)
return cls.query.session.get(cls, pet_id)
@classmethod
def find_by_name(cls, name: str) -> list:
"""Returns all Pets with the given name
:param name: the name of the Pets you want to match
:type name: str
:return: a collection of Pets with that name
:rtype: list
"""
logger.info("Processing name query for %s ...", name)
return cls.query.filter(cls.name == name)
@classmethod
def find_by_category(cls, category: str) -> list:
"""Returns all of the Pets in a category
:param category: the category of the Pets you want to match
:type category: str
:return: a collection of Pets in that category
:rtype: list
"""
logger.info("Processing category query for %s ...", category)
return cls.query.filter(cls.category == category)
@classmethod
def find_by_availability(cls, available: bool = True) -> list:
"""Returns all Pets by their availability
:param available: True for pets that are available
:type available: str
:return: a collection of Pets that are available
:rtype: list
"""
if not isinstance(available, bool):
raise TypeError("Invalid availability, must be of type boolean")
logger.info("Processing available query for %s ...", available)
return cls.query.filter(cls.available == available)
@classmethod
def find_by_gender(cls, gender: Gender = Gender.UNKNOWN) -> list:
"""Returns all Pets by their Gender
:param gender: values are ['MALE', 'FEMALE', 'UNKNOWN']
:type available: enum
:return: a collection of Pets that are available
:rtype: list
"""
if not isinstance(gender, Gender):
raise TypeError("Invalid gender, must be type Gender")
logger.info("Processing gender query for %s ...", gender.name)
return cls.query.filter(cls.gender == gender)