xppl/import_csv.py

40 lines
1.3 KiB
Python

#import click
#from flask import Flask
from app import app, db
from app.models import Book, Author
from csv import DictReader
import argparse
from app.cover import get_cover
import os
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):
cover = ''
if row['Filename']:
fullpath = os.path.join(app.config['UPLOAD_FOLDER'], row['Filename'])
name, file_extension = os.path.splitext(row['Filename'])
print ('get_cover', fullpath, name)
cover = get_cover(fullpath, name)
book = Book(row['Title'], row['Filename'], cover, 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()