Day 038

AWESOMee·2022년 3월 10일
0

Udemy Python Bootcamp

목록 보기
38/64
post-thumbnail

Udemy Python Bootcamp Day 038

Workout Tracking Using Google Spreadsheet

Setup API Credentials and Google Spreadsheet

Get Exercise Stats with Natural Language Queries

import requests

GENDER = MY GENDER
WEIGHT_KG = MY WEIGHT
HEIGHT_CM = MY HEIGHT
AGE = MY AGE

APP_ID = MY APP ID
API_KEY = MY API KEY

exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"

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()
print(result)

Setup My Google Sheet with Sheety

Saving Data into Google

import requests
from datetime import datetime

...

exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheet_endpoint = MY SHEETY ENDPOINT

...

################### Start of Step 4 Solution ######################

today_date = datetime.now().strftime("%d/%m/%Y")
now_time = datetime.now().strftime("%X")

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)

    print(sheet_response.text)

MY SHEETY ENDPOINT를 못찾아서 드롭했어....
근데 사실 찾았어도 많이 헤맸을거 같음..

Authenticate MY Sheety API

# No Authentication  
sheet_response = requests.post(sheet_endpoint, json=sheet_inputs)
  
# Basic Authentication
sheet_response = requests.post(
  sheet_endpoint, 
  json=sheet_inputs, 
  auth=(
      MY USERNAME, 
      MY PASSWORD,
  )
)

# Bearer Token Authentication
bearer_headers = {
"Authorization": "Bearer YOUR_TOKEN"
}
sheet_response = requests.post(
    sheet_endpoint, 
    json=sheet_inputs, 
    headers=bearer_headers
)

Bearer authentication
Bearer authentication (also known as token authentication) is an HTTP authentication scheme that involves security tokens. The name “Bearer authentication” basically means “give access to the bearer of this token.” The security token or “bearer token” is just a cryptic string. An example of a bearer token would be a string that could look something like this:

"AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F"

The idea is that whoever has the secret token, has permission to interact with the spreadsheet. A client - like your browser or mobile app - would then send this security token in the Authorization header when making requests to Sheety's server.

Environment Variables

import os 
  • Here's how you would set environment variables
APP_ID = os.environ["APP_ID"]
API_KEY = os.environ["API_KEY"]
  • and here is how you would get an environment variable
APP_ID = os.environ.get("APP_ID")
API_KEY = os.environ.get("API_KEY")

FINAL

import requests
from datetime import datetime
import os

GENDER = MY GENDER
WEIGHT_KG = MY WEIGHT
HEIGHT_CM = MY HEIGHT
AGE = MY AGE

APP_ID = os.environ["NT_APP_ID"]
API_KEY = os.environ["NT_API_KEY"]

exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheet_endpoint = os.environ["SHEET_ENDPOINT"]

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 {os.environ['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)

와 오늘 첫영상 제외 전부 글로만 되어있고 솔루션 코드만 있고 영상 없는데
또 자꾸 막혀서 개멘붕이었음...
내일도 모레도 이런 식인데 진짜 망했다 ㅠㅠ
내 영어..가 문제인거니..?

profile
개발을 배우는 듯 하면서도

0개의 댓글