首页 > 解决方案 > 如何将范围搜索条件添加到 API 调用?

问题描述

我想问客户每餐有多少卡路里,然后使用该标准进行搜索。我不确定如何将输入集成到范围搜索中。

import requests

def recipe_search(ingredient):
    recipes_appid = '0f89098e'
    recipes_appkey = '80a8b7c8361daa22182bc3b3eb9f277e'
    url = 'https://api.edamam.com/search?q={}&app_id={}&app_key={}&calories={}'.format(ingredient, recipes_appid,
                                                                                       recipes_appkey, calories)
    response = requests.get(url)
    data = response.json()

    return (data['hits'])

def run():
    ingredient = input('What ingredient is used by date first?')
    calories = input('Do you have a desired estimated calorie intake per meal?')

    results = recipe_search(ingredient) and recipe_search(calories_band)


run()

标签: pythonapi

解决方案


您可以recipe_search使用默认值添加第二个参数,因此您不必将其提供给方法

def recipe_search(ingredient, calories=500):
    recipes_appid = '0f89098e'
    recipes_appkey = '80a8b7c8361daa22182bc3b3eb9f277e'
    url = 'https://...={}'.format(ingredient, recipes_appid, recipes_appkey, calories)

然后调用results = recipe_search(ingredient, calories_band)


简化一点边界检查,你可以有

def run():
    ingredient = input('What ingredient is used by date first?')
    calories = input('Do you have a desired estimated calorie intake per meal?') or 200
    lower_bound = 100
    upper_bound = 300
    calories = min(max(int(calories), lower_bound), upper_bound)
    results = recipe_search(ingredient, calories)
    for result in results:
        recipe = result['recipe']
        ...

推荐阅读