我正在使用请求模块在Nutritionix API中发出POST请求.在其中一个为https://trackapi.nutritionix.com/v2/natural/nutrients的API路径中,如果我们将json作为{"query": <any_name>}传递,将Header作为x-app-idx-app-key传递,它将返回任何食品的所有必要详细信息.

它在Postman中运行良好,但在Python中,如果我从.cfg文件中获取x-app-id和x-app-key,它将显示401未授权状态.

CFG文件格式为

[nutritionix]
API_ID=<api-id>
API_KEY=<api-key>

我正在使用配置解析器模块获取所有这些密钥,我可以在终端中打印这些密钥,但它显示401错误.但如果我直接将这些键直接粘贴到代码中(不推荐),它将显示200状态.

我粘贴以下代码以供参考:

import requests
from configparser import ConfigParser

config = ConfigParser()
config.read('./secrets.cfg')

x_app_id = config['nutritionix']['API_ID']
x_app_key = config['nutritionix']['API_KEY']

headers = {
    'Accept':'application/json',
    'Content-Type': 'application/json',
    "x-app-id": x_app_id,
    "x-app-key": x_app_key,
}


url = 'https://trackapi.nutritionix.com/v2/natural/nutrients/'

def get_details(prompt: str):
    food_details = requests.post(url, headers=headers, json={"query": prompt})
    print(food_details)

我不知道为什么API密钥和ID不能从CFG文件中获取,而在其他文件中,它可以正确地获取.

我希望从CFG获取API密钥,并显示API所需的结果.

推荐答案

此代码将起作用

import requests
from configparser import ConfigParser
import json

config = ConfigParser()
config.read('./secrets.cfg')

x_app_id = config['nutritionix']['API_ID']
x_app_key = config['nutritionix']['API_KEY']

headers = {
    'Accept':'application/json',
    'Content-Type': 'application/json',
    "x-app-id": x_app_id,
    "x-app-key": x_app_key,
}


url = 'https://trackapi.nutritionix.com/v2/natural/nutrients/'

def get_details(prompt: str):
    food_details = requests.post(url, headers=headers, json={"query": prompt})
    print(json.dumps(food_details.json(), indent=2))

get_details('for breakfast i ate 2 eggs, bacon, and french toast')

secrets.cfg文件中不带"或"的凭据.

[nutritionix]
API_ID=xxxxxxxx
API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

结果

$ python3 get-nutrients.py 
Status Code 200
JSON Response  {
  "foods": [
    {
      "food_name": "eggs",
      "brand_name": null,
      "serving_qty": 2,
      "serving_unit": "large",
      "serving_weight_grams": 100,
      "nf_calories": 143,
      "nf_total_fat": 9.51,
      "nf_saturated_fat": 3.13,
      "nf_cholesterol": 372,
      "nf_sodium": 142,
      "nf_total_carbohydrate": 0.72,
      "nf_dietary_fiber": 0,
      "nf_sugars": 0.37,
      "nf_protein": 12.56,
      "nf_potassium": 138,
      "nf_p": 198,
      "full_nutrients": [
        {
          "attr_id": 203,
          "value": 12.56
        },
...

enter image description here

Python相关问答推荐

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

按列分区,按另一列排序

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

在Python中动态计算范围

关于Python异步编程的问题和使用await/await def关键字

driver. find_element无法通过class_name找到元素'""

Python Pandas获取层次路径直到顶层管理

使用Python和文件进行模糊输出

matplotlib + python foor loop

pandas:对多级列框架的列进行排序/重新排序

查看pandas字符列是否在字符串列中

如何在GEKKO中使用复共轭物

为用户输入的整数查找根/幂整数对的Python练习

如何使用Azure Function将xlsb转换为xlsx?

按条件添加小计列

来自Airflow Connection的额外参数

极柱内丢失类型信息""

为什么Visual Studio Code说我的代码在使用Pandas concat函数后无法访问?

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

是否将Pandas 数据帧标题/标题以纯文本格式转换为字符串输出?