我目前正在制作一个Web构建器,它将基于GIPHY API生成随机gif。我遇到一个问题,我在api返回0结果时测试一个案例。
def get_image_link(link):
global flag
set_count = 0
r = requests.get(link)
api_response = json.loads(r.text)
response = api_response['data']
if not response:
print('GIPHY API returned no results... finding another word...')
pass
elif response:
for set in response:
set_count += 1
random_gif_num = random.randint(0, set_count) - 1
try:
flag = True
return response[random_gif_num]['images']['original']['url']
except TypeError:
print(TypeError + '... rerunning application...')
pass
while not flag:
get_image_link(get_random_query())
基本上,如果结果返回结果中没有数据,我希望它重试该函数以获取另一个单词。该程序在带有结果的单词返回时有效,但当它返回0结果时,我得到TypeError
并且它不会返回到循环中。我确信这样做是因为它没有突破函数而是返回[]
类型。如何突破函数并返回while循环,以便生成另一个结果?谢谢。
答案 0 :(得分:2)
你可以在函数之外移动捕获异常,即:
while not flag:
try:
get_image_link(get_random_query())
except TypeError:
flag = False
print('TypeError... rerunning application...')
pass
答案 1 :(得分:2)
将标志重置为false!
try:
flag = True
return response[random_gif_num]['images']['original']['url']
except TypeError:
flag = false
print(TypeError + '... rerunning application...')
pass