-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
104 lines (84 loc) · 2.7 KB
/
database.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
from peewee import *
DATABASE = './app.db'
database = SqliteDatabase(DATABASE)
class BaseModel(Model):
class Meta:
database = database
class Contact(BaseModel):
id = AutoField()
fname = CharField()
lname = CharField()
dob = DateField()
def serialize(self):
return {
'id': self.id,
'fname': self.fname,
'lname': self.lname,
'dob': self.dob,
'emails': [ {'id': em.id, 'email': em.email } for em in self.emails ],
'phones': [ {'id': ph.id, 'phone': ph.phone } for ph in self.phones ]
}
class Address(BaseModel):
id = AutoField()
contact = ForeignKeyField(Contact, backref='addresses')
full_address = CharField()
# address1 = CharField()
# address2 = CharField()
# city = CharField()
# state = CharField()
# zip = CharField()
# country = CharField()
def serialize(self):
return {
'id': self.id,
'contact_id': self.contact_id,
'full_address': self.full_address
}
class Email(BaseModel):
id = AutoField()
contact = ForeignKeyField(Contact, backref='emails')
email = CharField()
def serialize(self):
return {
'id': self.id,
'contact_id': self.contact_id,
'email': self.email
}
class Phone(BaseModel):
id = AutoField()
contact = ForeignKeyField(Contact, backref='phones')
phone = CharField()
def serialize(self):
return {
'id': self.id,
'contact_id': self.contact_id,
'phone': self.phone
}
if __name__ == '__main__':
import sys
import csv
if '--create' in sys.argv:
with database:
database.create_tables([Contact, Email, Phone, Address])
elif '--drop' in sys.argv:
with database:
database.drop_tables([Contact, Email, Phone, Address])
elif '--seed' in sys.argv:
def seed(fileName, obj):
print(fileName)
with open(fileName) as file:
reader = csv.reader(file, delimiter=',')
fields = next(reader)
for row in reader:
d = dict(zip(fields, row))
obj.create(**d)
for fname in [ ['seedData/contacts.csv', Contact],
['seedData/emails-1.csv', Email],
['seedData/emails-2.csv', Email],
['seedData/emails-3.csv', Email]
]:
seed(*fname)
else:
print('--create: creates database tables')
print('--drop: drop all database tables')
print('--seed: seed database tables')