示例#1
0
def putBookInDb(bookKey):
    debugList = []
    authorsList = []

    # get the book json & create the Book record
    ### Book ###
    bookJson = getItemJson(bookKey)
    bookUID = getUIDfromBookKey(bookKey)
    b = Book(_bookId=bookUID, _bookJson=json.dumps(bookJson))
    if 'title' in bookJson:
        b._title = bookJson['title']
    if 'subtitle' in bookJson:
        b._subtitle = bookJson['subtitle']
    db.session.add(b)
    db.session.commit()  # commit to get the ID
    pb = PhysicalBook(_bookId=b._id)
    db.session.add(pb)

    # list of authors from book record
    authors = getAuthorsFromBook(bookJson)
    if (authors != 0):
        for item in authors:
            authorsList.append(item)
    else:
        debugList.append("No Authors from Book " + bookUID)

    # get the works record - may give more authors - only taking the first work
    works = getWorksFromBook(bookJson)
    if (works != 0):
        #		workUID = works[0][7:]
        workJson = getItemJson(works[0])
        b._workJson = json.dumps(workJson)
        # list of authors from work record
        authors = getAuthorsFromWork(workJson)
        if (authors != 0):
            for item in authors:
                authorsList.append(item)
        else:
            debugList.append("No Author from Work for Book " + bookUID)
    else:
        debugList.append("No Works from Book " + bookUID)

    # go through the authors list, remove duplicates, and add the Author and BookAuthor records
    authorsNoDup = list(dict.fromkeys(authorsList))
    for item in authorsNoDup:
        authorUID = item[
            9:]  # the portion of the openlibrary key to use for the db key
        authorJson = getItemJson(item)
        # create the author record if it doesn't already exist
        ### Author ###
        authorRecord = Author.query.filter_by(_authorId=authorUID).first()
        if not authorRecord:
            a = Author(_authorId=authorUID, _json=json.dumps(authorJson))
            if 'name' in authorJson:
                a._name = authorJson['name']
            db.session.add(a)
            db.session.commit()  # commit to get the ID
            debugList.append("Added a record for Author " + authorUID)
        ### BookAuthor ###
        ba = BookAuthor(_authorId=a._id, _bookId=b._id)
        db.session.add(ba)
        debugList.append("Added a BookAuthor record " + authorUID + "," +
                         bookUID)

    db.session.commit()  # final commit
    return 0