如何减少 JSON 中的请求时间或用默认键替换字典键?

Arn*_*ues 3 python google-api flask google-books-api

我有一个字典列表,我在搜索 JSON url 时正在填写它。问题是 JSON(由 Google Books API 提供)并不总是完整的。这是对书籍的搜索,据我所知,所有书籍都有 id、标题和作者,但并非所有书籍都有图像链接。以 JSON 链接为例:搜索哈利波特

请注意,它始终返回 10 个结果,在此示例中,有 10 个 ID、10 个标题、10 个作者,但只有 4 个图像链接。

@app.route('/search', methods=["GET", "POST"])
@login_required
def search():
    if request.method == "POST":
        while True:
            try:
                seek = request.form.get("seek")
                url = f'https://www.googleapis.com/books/v1/volumes?q={seek}'
                response = requests.get(url)
                response.raise_for_status()
                search = response.json()
                seek = search['items']
                infobooks = []
                for i in range(len(seek)):
                    infobooks.append({
                        "book_id": seek[i]['id'],
                        "thumbnail": seek[i]['volumeInfo']['imageLinks']['thumbnail'],
                        "title": seek[i]['volumeInfo']['title'],
                        "authors": seek[i]['volumeInfo']['authors']
                    })
                return render_template("index.html", infobooks=infobooks)
            except (requests.RequestException, KeyError, TypeError, ValueError):
                continue
    else:
        return render_template("index.html")
Run Code Online (Sandbox Code Playgroud)

我使用的方法和我在上面演示的方法,我可以找到 10 个图像链接(缩略图),但需要很长时间!任何人对这个请求有什么建议不需要这么长时间?或者当我找不到图像链接时,我可以通过某种方式插入“没有封面的书”图像?(不是我想要的,但总比等待结果要好)

ARR*_*ARR 5

首先,您的函数永远不会产生 10 个图像链接,因为 api 将始终返回相同的结果。因此,如果您第一次检索到 4 个 imageLink,则第二次将相同。除非谷歌更新数据集,但这是你无法控制的。

Google Books Api 允许最多 40 个结果,默认最多 10 个结果。要增加它,您可以添加查询参数maxResults=40,其中 40 可以是等于或小于 40 的任何所需数字。然后您可以决定以编程方式过滤掉所有没有 imageLinks 的结果,或者保留它们并向它们添加无结果图像 url。此外,并非每个结果都返回作者列表,这在本示例中也已修复。不要冒险使用第三方 api 总是检查空/空结果,因为它可能会破坏您的代码。我使用 .get 来避免在处理 json 时发生任何异常。

虽然我没有在这个例子中添加它,你也可以使用谷歌图书提供的分页来分页以获得更多结果。

例子:

@app.route('/search', methods=["GET", "POST"])
@login_required
def search():
    if request.method == "POST":
        seek = request.form.get("seek")
        url = f'https://www.googleapis.com/books/v1/volumes?q={seek}&maxResults=40'
        response = requests.get(url)
        response.raise_for_status()
        results = response.json().get('items', [])
        infobooks = []
        no_image = {'smallThumbnail': 'http://no-image-link/image-small.jpeg', 'thumbnail': 'http://no-image-link/image.jpeg'}
        for result in results:
            info = result.get('volumeInfo', {})
            imageLinks = info.get("imageLinks")
            infobooks.append({
                "book_id": result.get('id'),
                "thumbnail": imageLinks if imageLinks else no_image,
                "title": info.get('title'),
                "authors": info.get('authors')
            })
        return render_template("index.html", infobooks=infobooks)
    else:
        return render_template("index.html")
Run Code Online (Sandbox Code Playgroud)

谷歌图书 Api 文档:https : //developers.google.com/books/docs/v1/using