100 Days of Code: Day 38
Notes of 100 Days of Code: The Complete Python Pro Bootcamp.
Day 38 Workout Tracking Using Google Sheets
Build a workout tracking using Google Sheets.
With Sheety to access Google Sheets.
Use API to update rows in sheet.
Authorization
Three ways to authorize.
With username and password:
sheety_response = requests.post(
url=sheety_url, json=data, auth=(username,password))
With basic authentication:
sheety_response = requests.post(
url=sheety_url, json=data, headers={"Authorization": f"Basic {basic token}"})
With bearer authentication:
sheety_response = requests.post(
url=sheety_url, json=data, headers={"Authorization": f"Bearer {bearer token}"})
1,2 is based on username and password, 3 is a bearer token (anyone with this token can access).
Set environment variables for multiple tokens in Python
With os and python-dotenv .
pip install python-dotenv
Create a .env file:
TOKEN_1=abc123
TOKEN_2=def456
TOKEN_3=ghi789
Notice that in .env file, all value is plain text. No need to set type for values.
Load and use the environment variables in script:
from dotenv import load_dotenv
import os
load_dotenv()
token_1 = os.getenv('TOKEN_1')
token_2 = os.getenv('TOKEN_2')
token_3 = os.getenv('TOKEN_3')
print(f'Token 1: {token_1}')
print(f'Token 2: {token_2}')
print(f'Token 3: {token_3}')
Notice
Don’t use username as variable in python script especially on Windows. There probably has been a system-level username variable.
System Environment Variable Conflict:
- Some systems, especially Windows, might have a predefined
usernameenvironment variable that reflects the current user’s name on the machine. If this is the case,os.getenv("username")might be picking up the system’s environment variable instead of the one from your.envfile.
Solution:
- Use a different variable name in your
.envfile that doesn’t conflict with system variables, likemy_usernameorapp_username.
And read more:
https://oauth.net/2/