Skip to content

Instantly share code, notes, and snippets.

@XronTrix10
Created July 15, 2023 16:38
Show Gist options
  • Save XronTrix10/e107e91e040df0ea1aeac017afc50e8e to your computer and use it in GitHub Desktop.
Save XronTrix10/e107e91e040df0ea1aeac017afc50e8e to your computer and use it in GitHub Desktop.
A Python Snippet To Generate Google token.pickle From credentials.json
import os
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib import flow as google_auth_flow
# Set the path to your client_secret.json file
client_secret_file = "<PATH_TO_CREDENTIALS.JSON>"
# Check if token.pickle file exists. If not, create one.
if not os.path.exists('token.pickle'):
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is created automatically when the authorization flow completes for the first time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = google_auth_flow.InstalledAppFlow.from_client_secrets_file(
client_secret_file, ['https://www.googleapis.com/auth/drive'])
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
@XronTrix10
Copy link
Author

๐Ÿ’ข HOW TO USE

โš™๏ธ Prerequisites :

๐Ÿ“ƒ Run These Below commands in Terminal

  • pip install google-auth
  • pip install google-auth-oauthlib
  • pip install google-auth-httplib2

โš ๏ธ NOTE : Assumed Python already Installed in Machine

โœ’๏ธ Manage The Code

  • Create a python file ( file_name.py ) in your machine, wherever you want. Now copy and paste the code in your file.
  • Replace <PATH_TO_CREDENTIALS.JSON> with the path to your credentials.json file downloaded from google cloud console. [ It's on line 7 ]

๐Ÿœ Run The Code

  • After Running the code, it will prompt a sign in page in the browser.
  • Login with your Google Account and Allow the code to get access of your Google Drive.
  • ๐Ÿ’ฅ Boom You successfully generated the token.pickle file.

โš ๏ธ NOTE : You will find it within the same directory where You Saved The Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment