-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimports.py
More file actions
42 lines (34 loc) · 1.27 KB
/
Copy pathimports.py
File metadata and controls
42 lines (34 loc) · 1.27 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
import os
import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
print("Connecting to database... ")
def main():
db.execute(
"CREATE TABLE users (id SERIAL PRIMARY KEY, username VARCHAR NOT NULL, password VARCHAR NOT NULL)"
)
db.execute(
"CREATE TABLE reviews (user_id VARCHAR NOT NULL, book_id INTEGER NOT NULL, comment VARCHAR NOT NULL, rating INTEGER NOT NULL)"
)
db.execute(
"CREATE TABLE books (isbn VARCHAR PRIMARY KEY,title VARCHAR NOT NULL,author VARCHAR NOT NULL,year VARCHAR NOT NULL)"
)
f = open("books.csv")
reader = csv.reader(f)
for isbn, title, author, year in reader:
if year == "year":
print("skipped first line")
else:
db.execute(
"INSERT INTO books (isbn, title, author, year) VALUES (:isbn,:title,:author,:year)",
{"isbn": isbn, "title": title, "author": author, "year": year},
)
print(f"Added book {title} to database.")
print("Done")
db.commit()
if __name__ == "__main__":
main()