xppl/import_csv.py

51 lines
1.8 KiB
Python
Raw Normal View History

2018-05-23 15:58:16 +02:00
#import click
#from flask import Flask
from app import app, db
2018-05-31 18:04:05 +02:00
from app.models import Book, Author, Stack
2018-05-23 15:58:16 +02:00
from csv import DictReader
import argparse
2018-05-23 18:10:25 +02:00
from app.cover import get_cover
import os
2018-05-23 15:58:16 +02:00
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()
2018-05-23 17:03:47 +02:00
with open(args.csv) as f:
for row in DictReader(f):
2018-05-23 18:10:25 +02:00
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)
2018-06-11 17:24:30 +02:00
book = Book(row['Title'], row['Filename'], cover, row['Format'], row['Category'], None, None, None, None, None, None)
2018-05-23 18:10:25 +02:00
2018-05-23 17:03:47 +02:00
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)
2018-05-31 18:04:05 +02:00
stacks = row['Stack']
stacks = row['Stack'].split(',')
stacks = [x.strip() for x in stacks]
for stack in stacks:
if stack:
b = db.session.query(Stack).filter_by(stack_name=stack).first()
if b == None:
2018-06-11 12:19:49 +02:00
b = Stack(stack_name=stack, stack_description=None, stack_author=None)
2018-05-31 18:04:05 +02:00
db.session.add(b)
book.stacks.append(b)
2018-05-23 17:03:47 +02:00
db.session.commit()
2018-05-23 15:58:16 +02:00
2018-05-23 17:53:30 +02:00
#books = db.session.query(Book).all()