如果 Python 中的字典为空,则刷新 api 查询

Refresh an api query if the dict is empy in Python

我正在尝试创建一个提供以下功能的方法: 该函数接收 2 个参数:type 和 effort。 type 必须是集合 ["education", "recreational", "social", "diy", "charity", "cooking", "relaxation", "music", "busywork"] type 中的字符串。 如果传递了另一个字符串,则将抛出 ValueError 类型的异常。 "effort" 定义 activity 应该付出多少努力(在 0 和 1 之间浮动,0 是最少的努力)。 这个数字范围不需要检查。 然后该函数应使用 Brd API 来查询具有给定类型(参数“type”)和工作量(参数“accessibility”)的随机 activity。为此,查询必须包含传递的值“type”和“effort”。 重复查询,直到找到activity包含一个link(字段“link”)并且这个值不为空。 该方法的 return 值是一个元组,包括:activity 的名称 ("activity")、类型 ("type")、link (" link") 和努力(“可访问性”)完全按照这个顺序。

我现在的问题是,如果查询“link”为空,则该方法不会重新加载。该方法需要 运行 直到“link”不再为空。

import requests

def vorschlagen(typ,aufwand):
    url=f"http://www.boredapi.com/api/activity?type={typ}&?accessiblity={aufwand}"
    data=requests.get(url).json()
    print(url)
    print (len(data["link"]))
    while len(data["link"])==0:
        data=requests.get(url).json()
        link=(data["link"])
        name=(data["activity"])
        typ=(data["type"])
        if typ!=["education", "recreational", "social", "diy", "charity", "cooking", "relaxation", "music", "busywork"]:
            ValueError
        aufwand=(data["accessibility"])
        print("Aktivität :",name)
        print("Art der Aktivität (TYP) :",typ)
        print("Link :",link)
        print("Aufwand :",aufwand)
        return (name),(typ),(link),(aufwand)```

return 语句必须放在 while 循环之外:

import requests

def vorschlagen(typ,aufwand):
    url=f"http://www.boredapi.com/api/activity?type={typ}&?accessiblity={aufwand}"
    data=requests.get(url).json()
    print(url)
    print (len(data["link"]))
    while len(data["link"])==0:
        data=requests.get(url).json()
        link=(data["link"])
        name=(data["activity"])
        typ=(data["type"])
        if typ!=["education", "recreational", "social", "diy", "charity", "cooking", "relaxation", "music", "busywork"]:
            ValueError
        aufwand=(data["accessibility"])
        print("Aktivität :",name)
        print("Art der Aktivität (TYP) :",typ)
        print("Link :",link)
        print("Aufwand :",aufwand)
    return (name),(typ),(link),(aufwand)

更新

回答您的评论:

import requests

def vorschlagen(typ,aufwand):
    if typ not in ["education", "recreational", "social", "diy", "charity", "cooking", "relaxation", "music", "busywork"]:
        raise ValueError("invalid argument typ")

    url=f"http://www.boredapi.com/api/activity?type={typ}&?accessiblity={aufwand}"

    while True:
        
        data=requests.get(url).json()
        link=(data["link"])
        name=(data["activity"])
        typ=(data["type"])
        aufwand=(data["accessibility"])
        
        print("Aktivität :",name)
        print("Art der Aktivität (TYP) :",typ)
        print("Link :",link)
        print("len data[link]:", len(link))
        print("Aufwand :",aufwand)
        
        if len(data["link"]) > 0:
            return (name),(typ),(link),(aufwand)