-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathinit_database.py
More file actions
93 lines (82 loc) · 2.4 KB
/
Copy pathinit_database.py
File metadata and controls
93 lines (82 loc) · 2.4 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
from datetime import datetime
from config import app, db
from models import Note, Person
from sqlalchemy.exc import OperationalError
PEOPLE_NOTES = [
{
"lname": "Fairy",
"fname": "Tooth",
"notes": [
("I brush my teeth after each meal.", "2022-01-06 17:10:24"),
(
"The other day a friend said, I have big teeth.",
"2022-03-05 22:17:54",
),
("Do you pay per gram?", "2022-03-05 22:18:10"),
],
},
{
"lname": "Ruprecht",
"fname": "Knecht",
"notes": [
(
"I swear, I'll do better this year.",
"2022-01-01 09:15:03",
),
(
"Really! Only good deeds from now on!",
"2022-02-06 13:09:21",
),
],
},
{
"lname": "Bunny",
"fname": "Easter",
"notes": [
(
"Please keep the current inflation rate in mind!",
"2022-01-07 22:47:54",
),
("No need to hide the eggs this time.", "2022-04-06 13:03:17"),
],
},
]
def get_data_from_table(model):
try:
data = db.session.query(model).all()
db.session.close()
return data
except OperationalError:
return []
def create_database(db):
db.create_all()
for data in PEOPLE_NOTES:
new_person = Person(lname=data.get("lname"), fname=data.get("fname"))
for content, timestamp in data.get("notes", []):
new_person.notes.append(
Note(
content=content,
timestamp=datetime.strptime(
timestamp, "%Y-%m-%d %H:%M:%S"
),
)
)
db.session.add(new_person)
db.session.commit()
print("Created new database")
def update_database(db, existing_people, existing_notes):
db.drop_all()
db.create_all()
for person in existing_people:
db.session.merge(person)
for note in existing_notes:
db.session.merge(note)
db.session.commit()
print("Updated existing database")
with app.app_context():
existing_people = get_data_from_table(Person)
existing_notes = get_data_from_table(Note)
if not existing_people:
create_database(db)
else:
update_database(db, existing_people, existing_notes)