You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Edamam API的Python食谱应用运行报错求助

解决Recipe.init()意外参数'cuisineType'的报错

问题原因

报错核心是你使用的py_edamam库版本过旧,Edamam API返回的响应中新增了cuisineType字段,但旧版本库的Recipe类构造函数未处理该额外参数,导致类型错误。

解决方案

方案1:升级py_edamam库到最新版本

打开终端执行以下命令,更新库至兼容新API字段的版本:

pip install --upgrade py_edamam

这是最简便的解决方式,升级后库会自动适配API返回的新字段。

方案2:修改py_edamam库的Recipe类(仅当升级无效时使用)

找到Python安装目录下的site-packages/py_edamam/__init__.py文件,定位到Recipe类的__init__方法,在参数列表末尾添加**kwargs,让它接收并忽略所有未定义的额外参数:

def __init__(self, edamam, label, url, image, source, shareAs, yield_, dietLabels, healthLabels, cautions, ingredientLines, ingredients, calories, totalWeight, totalTime, cuisineType=None, mealType=None, dishType=None, **kwargs):
    # 原初始化代码保持不变

修改后保存文件,重新运行应用即可。

方案3:绕过py_edamam库,直接调用Edamam API(更灵活)

若不想依赖第三方库,可直接用requests模块调用API并自行解析数据。修改__get_recipe方法如下:

def __get_recipe(self, query):
    base_url = "https://api.edamam.com/api/recipes/v2"
    params = {
        "type": "public",
        "q": query,
        "app_id": self.recipe_app_id,
        "app_key": self.recipe_app_key
    }
    response = requests.get(base_url, params=params)
    if response.status_code != 200:
        return None
    data = response.json()
    hits = data.get("hits", [])
    if not hits:
        return None
    return hits[0]["recipe"]

同时修改依赖recipe对象的方法:

def __run_search_query(self):
    query = self.search_entry.get()
    recipe_data = self.__get_recipe(query)

    if recipe_data:
        recipe_image = recipe_data["image"]
        recipe_url = recipe_data["url"]
    else:
        recipe_image = "https://www.mageworx.com/blog/wp-content/uploads/2012/06/Page-Not-Found-13.jpg"
        recipe_url = ""

    self.__show_image(recipe_image)
    self.__get_ingredients(recipe_data)

    def __open_link():
        webbrowser.open(recipe_url)

    self.recipe_button = tk.Button(self.window, text="recipe link", highlightbackground="#ea86b6",
                                  command=__open_link)
    self.recipe_button.grid(column=1, row=7, pady=10)

def __get_ingredients(self, recipe_data):
    ingredients = tk.Text(master=self.window, height=15, width=50, bg="#ffdada")
    ingredients.grid(column=1, row=4, pady=10)
    ingredients.delete("1.0", tk.END)

    if not recipe_data:
        ingredients.insert(tk.END, "No Recipe found for search criteria")
        return

    ingredients.insert(tk.END, "\n" + recipe_data["label"] + "\n")
    for ingredient in recipe_data["ingredientLines"]:
        ingredients.insert(tk.END, "\n- " + ingredient)

这种方式完全自主控制请求与解析,不受第三方库版本限制。

内容的提问来源于stack exchange,提问作者llllllll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:49:58