如何使用 python ISBNLIB 元方法捕获错误并继续

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

我有一个使用 FLASK 和 ISBNLIB 库的简单应用程序,该应用程序获取条形码和 isbn 编号,搜索 ISBN 并将信息插入数据库。

isbnlib 元方法搜索 ISBN,然后将其插入到我的 sqlite 数据库中。

我遇到的问题是当找不到那本书时我收到一条错误消息:

isbnlib.dev._exceptions.NoDataForSelectorError

我想要实现的是让应用程序捕获此错误并仍然将我的条形码和 isbn 插入数据库并在其他字段中输入空值。

我不确定如何解决这个问题。

如有任何建议,我们将不胜感激。

代码如下:

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'))

与此类似的内容应该适合您:

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'))

这可行(目前)但不可取,因为它使用了不受支持的 api!

改为使用 catch-all isbnlib 异常

from isbnlib import ISBNLibException

或特定的

from isbnlib.dev import NoDataForSelectorError