forked from learn-co-curriculum/python-p3-freebie-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
212 lines (173 loc) · 7.62 KB
/
models.py
File metadata and controls
212 lines (173 loc) · 7.62 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
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
from sqlalchemy import ForeignKey, Column, Integer, String, MetaData, Table, create_engine
from sqlalchemy.orm import relationship, backref, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
convention = {
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
}
metadata = MetaData(naming_convention=convention)
engine = create_engine('sqlite:///freebies.db')
Base = declarative_base(metadata=metadata)
Session = sessionmaker(bind=engine)
session = Session()
companies_devs = Table('companies_devs',
Base.metadata,
Column('company_id',
ForeignKey('companies.id'),
primary_key=True),
Column('dev_id',
ForeignKey('devs.id'),
primary_key=True),
extend_existing=True)
class Company(Base):
__tablename__ = 'companies'
id = Column(Integer(), primary_key=True)
name = Column(String())
founding_year = Column(Integer())
# Python mapping of relationships
freebies = relationship('Freebie', backref="company")
devs = relationship('Dev',
secondary=companies_devs,
back_populates='companies')
def __repr__(self):
"""Return a string representation of Company object."""
return f'<Company {self.name}>'
@classmethod
def oldest_company(cls):
"""Return the oldest company in the database."""
return session.query(cls).order_by(cls.founding_year).first()
def give_freebie(self, dev, freebie):
"""Associates the freebie with the dev."""
if not isinstance(dev, Dev):
raise TypeError('dev argument is not of type Dev.')
if not isinstance(freebie, Freebie):
raise TypeError('freebie argument is not of type freebie.')
@classmethod
def oldest_company(cls):
"""
Return the oldest company in the database.
The oldest company is determined by the founding year of the company.
"""
return session.query(cls).order_by(cls.founding_year).first()
def give_freebie(self, dev, freebie):
"""
Associate a freebie with a dev.
:param dev: the dev to associate the freebie with
:type dev: models.Dev
:param freebie: the freebie to associate with the dev
:type freebie: models.Freebie
:raises TypeError: if dev is not of type models.Dev or freebie is not of type models.Freebie
:raises FreebieAlreadyGivenError: if the freebie has already been given to another dev
:raises FreebieNotMineToGiveError: if the freebie does not belong to the company
"""
if not isinstance(dev, Dev):
raise TypeError('dev argument is not of type models.Dev.')
if not isinstance(freebie, Freebie):
raise TypeError('freebie argument is not of type models.Freebie.')
if freebie.dev_id:
raise FreebieAlreadyGivenError
if freebie not in self.freebies:
raise FreebieNotMineToGiveError
else:
# Add the freebie to the dev's freebies
dev.freebies.append(freebie)
class Dev(Base):
__tablename__ = 'devs'
id = Column(Integer(), primary_key=True)
name = Column(String())
# Python mapping of relationships
freebies = relationship('Freebie', backref="dev")
companies = relationship('Company',
secondary=companies_devs,
back_populates="devs")
def __repr__(self):
"""
Return a string representation of the Dev object.
"""
return f'<Dev {self.name}>'
def received_one(self, item_name):
"""
Returns True if any of the freebies associated with the dev has the given
item_name, otherwise returns False.
:param item_name: the item_name to look for in the freebies
:type item_name: str
:return: whether the item_name was found in the freebies
:rtype: bool
"""
return any(freebie.item_name == item_name for freebie in self.freebies)
def give_away(self, dev, freebie):
"""
Changes the freebie's dev to be the given dev; your code should only
make the change if the freebie belongs to the dev who's giving it away.
:param dev: the dev to associate the freebie with
:type dev: models.Dev
:param freebie: the freebie to associate with the dev
:type freebie: models.Freebie
:raises TypeError: if dev is not of type models.Dev or freebie is not of type models.Freebie
:raises FreebieNotMineToGiveError: if the freebie does not belong to the dev
"""
if not isinstance(dev, Dev):
raise TypeError("dev argument must be of type Dev")
if not isinstance(freebie, Freebie):
raise TypeError("freebie argument must be of type Freebie")
if freebie not in self.freebies:
raise FreebieNotMineToGiveError
def received_one(self, item_name):
"""
Returns True if any of the freebies associated with the dev has the given
item_name, otherwise returns False.
:param item_name: the item_name to look for in the freebies
:type item_name: str
:return: whether the item_name was found in the freebies
:rtype: bool
"""
return any(freebie.item_name == item_name for freebie in self.freebies)
def give_away(self, dev, freebie):
"""
Changes the freebie's dev to be the given dev; your code should only
make the change if the freebie belongs to the dev who's giving it away.
:param dev: the dev to associate the freebie with
:type dev: models.Dev
:param freebie: the freebie to associate with the dev
:type freebie: models.Freebie
:raises TypeError: if dev is not of type models.Dev or freebie is not of type models.Freebie
:raises FreebieNotMineToGiveError: if the freebie does not belong to the dev
"""
# Check the type of the arguments
if not isinstance(dev, Dev):
raise TypeError("dev argument must be of type Dev")
if not isinstance(freebie, Freebie):
raise TypeError("freebie argument must be of type Freebie")
# Check if the freebie is in the dev's freebies
if freebie not in self.freebies:
raise FreebieNotMineToGiveError
else:
# Change the freebie's dev to the given dev
freebie.dev = dev
# Commit the changes to the database
session.commit()
class Freebie(Base):
# Mapped table name at the database level
__tablename__ = 'freebies'
# Column definitions
id = Column(Integer(), primary_key=True)
item_name = Column(String(), nullable=False)
value = Column(Integer(), nullable=False)
# Foreign Keys definitions (relationships at the database level)
dev_id = Column(Integer(), ForeignKey('devs.id'))
company_id = Column(Integer(), ForeignKey('companies.id'), nullable=False)
def __repr__(self):
"""Return a string representation of Freebie object."""
return f"Freebie(item-name={self.item_name}, " + \
f"value={self.value})"
def print_details(self):
"""
Prints a nicely formatted string with details about the freebie.
:return: None
"""
# Print the freebie details
print(f"{self.dev} owns a {self.item_name} "
f"from {self.company.name}")
class FreebieAlreadyGivenError(Exception):
pass
class FreebieNotMineToGiveError(Exception):
pass