我之前发布了有关此代码的问题,并得到了解决一个问题的答案,但现在我收到了一个新错误,并且我不理解该错误或错误。我还使用 Mac 在 PyCharm 上进行编码🖥,如果这会改变什么的话。该代码来自讲座 333,100 天的代码 作者:余安琪博士。感谢@Tim Roberts 对我上一个问题的帮助!
#------------New_code------------#
import requests
from datetime import datetime
GENDER = "male"
WEIGHT_KG = 58.740212
HEIGHT_CM = 177.8
AGE = 13
APP_ID = "be2*****"
API_KEY = "4fa82da*************************"
exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheet_endpoint = "https://api.sheety.co/0a5644021c9c3815973ccd3f25595467/myWorkouts/sheet1"
exercise_text = input("Tell me which exercises you did: ")
headers = {
"x-app-id": APP_ID,
"x-app-key": API_KEY,
}
parameters = {
"query": exercise_text,
"gender": GENDER,
"weight_kg": WEIGHT_KG,
"height_cm": HEIGHT_CM,
"age": AGE
}
response = requests.post(exercise_endpoint, json=parameters, headers=headers)
result = response.json()
today_date = datetime.now().strftime("%d/%m/%Y")
now_time = datetime.now().strftime("%X")
bearer_headers = {
"Authorization": f"Bearer {'TOKEN'}"
}
for exercise in result["exercises"]:
sheet_inputs = {
"workout": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}
sheet_response = requests.post(sheet_endpoint, json=sheet_inputs, headers=bearer_headers)
print(sheet_response.text)
#------------New_output------------#
Tell me which exercises you did: (I entered: run 3 miles)
{
"errors": [
{
"detail": "Bad Request. The JSON payload should be inside a root property called 'sheet1'. Check https://sheety.co/docs for more details."
}
]
}
Process finished with exit code 0
您应该使用“sheet1”而不是“锻炼”
在此部分中,您指定/sheet1
sheet_endpoint = "https://api.sheety.co/0a5644021c9c3815973ccd3f25595467/myWorkouts/sheet1"
但是你尝试在不存在的表“workout”中添加数据
for exercise in result["exercises"]:
sheet_inputs = {
"workout": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}
这个解决方案对我有用。 确保在运行sheety request.post方法之前sheet1中已经存在所需的列。
仅举个例子。 {'sheet1': {'日期': '15/04/2023', '时间': '17:38:36', '锻炼': '步行', '持续时间': 120, '卡路里': 588} } 这是我想使用sheety添加到sheet1中的数据,然后确保在运行request.post()之前sheet1中存在日期时间锻炼持续时间卡路里列。
同样对于有效负载,无需提及上面建议的sheet1。 sheet_response = requests.post( 工作表端点, json=sheet_inputs ) 这能够成功在谷歌工作表中添加行(无需任何身份验证。如果您有身份验证,请相应地添加参数)。 希望这有帮助。
您可以将 Google 表格中的 Sheet1 重命名为“锻炼”。 或者在代码中您可以进行此更改
for exercise in result["exercises"]:
sheet_inputs = {
"workout": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}
将其重命名为sheet1,如下所示
for exercise in result["exercises"]:
sheet_inputs = {
"sheet1": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}