how to catch an error using the python ISBNLIB meta method and continue

402 views Asked by At

I have a simple application using FLASK and the ISBNLIB library the application obtains barcode and isbn numbers, searches for the ISBN and inserts the information into a DB.

The isbnlib meta method searches for the ISBN and then inserts it into my sqlite db.

The problem I have is when that book is not found I receive an error:

isbnlib.dev._exceptions.NoDataForSelectorError

What I want to achieve is for the application to catch this error and still insert my barcode and isbn into the DB and enter null values into the other fields.

I am not sure how to go about solving this problem.

Any suggestions would be much appreciated.

Here is the code:

else:
    # Assign meta dictionary to book_lib for value calling.
    book_lib = (isbnlib.meta(isbn, service='goob', cache='default'))

    # Display meta data to user.
    flash(isbnlib.meta(isbn, service='goob', cache='default'))

    # Assign meta dictionary values to variables for insertion to DB.
    author = str(book_lib['Authors'])
    lang = book_lib['Language']
    publisher = book_lib['Publisher']
    title = book_lib['Title']
    publYear = book_lib['Year']

    db.execute(
        'INSERT INTO new_book (barcode, isbn, invoice, author_id, author, lang, publisher, title, publYear)'
        ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
        (barcode, isbn, invoice, g.user['id'], author, lang, publisher, title, publYear)
    )
    db.commit()
    return redirect(url_for('book.newbook'))
2

There are 2 answers

0
Joost On BEST ANSWER

Something along the lines of this should work for you:

from isbnlib.dev._exceptions import NoDataForSelectorError


else:
    # Assign meta dictionary to book_lib for value calling.
    author = None
    lang = None
    publisher = None
    title = None
    publYear = None

    try:
        book_lib = isbnlib.meta(isbn, service='goob', cache='default')
        # Display meta data to user.
        flash(book_lib)

        # Assign meta dictionary values to variables for insertion to DB.
        author = str(book_lib['Authors'])
        lang = book_lib['Language']
        publisher = book_lib['Publisher']
        title = book_lib['Title']
        publYear = book_lib['Year']

    except NoDataForSelectorError:
        pass

    db.execute(
        'INSERT INTO new_book (barcode, isbn, invoice, author_id, author, lang, publisher, title, publYear)'
        ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
        (barcode, isbn, invoice, g.user['id'], author, lang, publisher, title, publYear)
    )
    db.commit()
    return redirect(url_for('book.newbook'))
0
AlexAtStack On

This works (for now) but is not advisable since it uses a non-supported api!

Use instead the catch-all isbnlib exception

from isbnlib import ISBNLibException

or the specific

from isbnlib.dev import NoDataForSelectorError