forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_temp_data_sqlite.py
More file actions
78 lines (60 loc) · 2.16 KB
/
Copy pathbuild_temp_data_sqlite.py
File metadata and controls
78 lines (60 loc) · 2.16 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
"""
This program gathers information from the temp_data.db file about temperature
"""
import os
import csv
from pkg_resources import resource_filename
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, Date, Float
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class TemperatureData(Base):
__tablename__ = "temperature_data"
temperature_data_id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
date = Column(Date, nullable=False)
value = Column(Float, nullable=False)
def get_temperature_data(filepath):
"""
This function gets the temperature data from the csv file
"""
with open(filepath) as csvfile:
csv_reader = csv.DictReader(csvfile)
data = {row["name"]: row for row in csv_reader}
for value in data.values():
value.pop("name")
return data
def populate_database(session, temperature_data):
# insert the data
for student, data in temperature_data.items():
for date, value in data.items():
temp_data = TemperatureData(
name=student,
date=datetime.strptime(date, "%Y-%m-%d").date(),
value=value,
)
session.add(temp_data)
session.commit()
session.close()
def main():
print("starting")
# get the temperature data into a dictionary structure
csv_filepath = resource_filename("project.data", "temp_data.csv")
temperature_data = get_temperature_data(csv_filepath)
# get the filepath to the database file
sqlite_filepath = resource_filename("project.data", "temp_data.db")
# does the database exist?
if os.path.exists(sqlite_filepath):
os.remove(sqlite_filepath)
# create and populate the sqlite database
engine = create_engine(f"sqlite:///{sqlite_filepath}")
Base.metadata.create_all(engine)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
populate_database(session, temperature_data)
print("finished")
if __name__ == "__main__":
main()