xppl/import_csv.py
2018-05-23 17:53:30 +02:00

30 lines
960 B
Python

#import click
#from flask import Flask
from app import app, db
from app.models import Book, Author
from csv import DictReader
import argparse
ap = argparse.ArgumentParser("import csv into flask")
ap.add_argument("csv", help = "csv file to import")
ap.add_argument("--limit", type=int, default = None, help = "limit to x number of x")
args = ap.parse_args()
with open(args.csv) as f:
for row in DictReader(f):
book = Book(row['Title'], '', '', row['Format'], row['Shelf'])
db.session.add(book)
authors = row['Author'].split(',')
authors = [x.strip() for x in authors]
for author in authors:
if author:
a = db.session.query(Author).filter_by(author_name=author).first()
if a == None:
a = Author(author_name=author)
db.session.add(a)
book.authors.append(a)
db.session.commit()
#books = db.session.query(Book).all()