gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:58:04 26 4
gpt4 key购买 nike

我有一个字典列表,我在搜索 JSON url 时正在填写它。问题是 JSON(由 Google Books API 提供)并不总是完整的。这是对书籍的搜索,据我所见,它们都有 ID、标题和作者,但并非所有书籍都有 imageLinks。下面以 JSON 链接为例:Search for Harry Potter .

请注意,它总是返回 10 个结果,在此示例中,有 10 个 ID、10 个标题、10 个作者,但只有 4 个 imageLink。

@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")

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

最佳答案

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

Google Books Api 最多允许 40 个结果,默认最多 10 个结果。要增加它,您可以添加查询参数 maxResults=40 其中 40 可以是等于或小于 40 的任何所需数字。然后您可以决定以编程方式过滤掉所有没有 imageLinks 的结果,或者保留它们并向他们添加一个没有结果的图片网址。此外,并非每个结果都返回作者列表,这在此示例中也已修复。第三方 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")

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

关于python - 如何减少 JSON 中的请求时间或将字典键替换为默认键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67851037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com