broken csv loading
unknown
python
10 months ago
2.5 kB
14
Indexable
from src.swen344_db_utils import connect, exec_commit
import csv
def seed_users():
"""Seed default users into db"""
users = [
(
"Ada Lovelace",
"[email protected]",
),
(
"Mary Shelley",
"[email protected]",
),
(
"Jackie Gleason",
"[email protected]",
),
(
"Art Garfunkel",
"[email protected]",
),
]
for user in users:
exec_commit(
"""
INSERT INTO library_users (name, email)
VALUES (%s, %s)
ON CONFLICT (email) DO NOTHING
""",
user
)
def seed_inventory(path_to_csv):
"""Given a CSV file, add each book and it's data into the csv one row at a time."""
conn = connect()
cur = conn.cursor()
# Clear inventory table
cur.execute("TRUNCATE TABLE library_inventory RESTART IDENTITY CASCADE;")
# Read from csv file and populate the inventory
with open(path_to_csv) as inventory:
reader = csv.DictReader(inventory)
for row in reader:
cur.execute(
"INSERT INTO library_inventory (Title, Comment, Category, Subcategory, Copies) VALUES (%s, %s, %s, %s, %s)"
"RETURNING InventoryID",
(
row["Title"],
row["Comments"],
row["Category"],
row["Sub-category"],
row["Copies"],
),
)
author = row["author(s)"]
authors = [a.strip() for a in author.split(',')]
inventory_id = cur.fetchone()[0]
for author in authors:
cur.execute(
"INSERT INTO library_authors (Name) VALUES (%s)"
"ON CONFLICT (name) DO UPDATE SET NAME = EXCLUDED.Name RETURNING AuthorID",
(author, )
)
author_id = cur.fetchone()[0]
cur.execute(
"INSERT INTO library_book_authors (InventoryID, AuthorID) VALUES (%s, %s)"
"ON CONFLICT DO NOTHING",
(inventory_id, author_id)
)
conn.commit()
cur.close()
conn.close()
def main():
seed_users()
seed_inventory("db/Library.csv")
if __name__ == "__main__":
main()
Editor is loading...
Leave a Comment