def __save(data): """ 保存到数据库 :param data: :return: """ if 'books' not in data.keys(): data['books'] = [data] if data['books']: for item in data['books']: # 已存在的不需要插入 count = Book.query.filter_by(isbn=item['isbn']).count() if count == 0: book = Book() book.title = item['title'] book.author = '、'.join(item['author']) book.binding = item['binding'] book.publisher = item['publisher'] book.price = item['price'] book.pages = item['pages'] book.pubdate = item['pubdate'] book.isbn = item['isbn'] book.summary = item['summary'] book.image = item['image'] db.session.add(book) db.session.commit()
def save_book(books): for b in books: try: book = Book() book.title = b.title book.author = b.author book.binding = b.binding book.publisher = b.publisher book.image = b.image book.price = b.price book.isbn = b.isbn book.pubdate = b.pubdate book.summary = b.summary book.pages = b.pages db.session.add(book) db.session.commit() except IntegrityError as e: db.session.rollback() current_app.logger.exception('%r' % e) raise e
from app.models.base import db from app.models.users import User from app.models.book import Book app = create_app() # with app.app_context(): # with db.auto_commit(): # # 创建一个超级管理员 # user = User() # user.nickname = 'Super' # user.password = '******' # user.email = '*****@*****.**' # user.auth = 2 # db.session.add(user) with app.app_context(): with db.auto_commit(): book = Book() book.id = 2 book.title = "flask进阶" book.author = "SHI" book.binding = "32开" book.publisher = "北京xx大学出版社" book.price = 180 book.pages = 900 book.pubdate = "2018-12-31" book.isbn = "2345678" book.summary = "关于flask的进阶知识" book.image = "http://baidu.image.com" db.session.add(book)