How to authenticate Google account via Python - python

This following snippet authenticates user account on Colab:
from google.colab import auth
auth.authenticate_user()
However, I am writing a script to run this on a desktop so I can't use this feature. How can I authenticate a Google account in Python?
This is my full code:
import gspread, json
import pandas as pd
from google.auth import default
from google.colab import auth
auth.authenticate_user()
creds, _ = default()
gc = gspread.authorize(creds)
SCOPE = ["https://docs.google.com/forms/d/aBCdefGHJ/edit"]
SECRETS_FILE = "client_secret.json"
SPREADSHEET = "GForm doc"
json_key = json.load(open(SECRETS_FILE))
gc = gspread.authorize(creds)
workbook = gc.open(SPREADSHEET)
sheet = workbook.sheet1
data = pd.DataFrame(sheet.get_all_records())
print(data['Email Address'])
print(list(data['Links']))
As you can see, I am using the Colab library so it makes this code useless as a standalone Python script. I want to authenticate without logging in with my email and password since I don't want to expose those. Is there a way to authenticate Google credentials?

Related

Is there a way to authenticate gspread with the default service account?

If I want to create/read/update spreadsheets using gspread, I know first have to authenticate like so:
import gspread
gc = gspread.service_account()
Where I can also specify the filename to point to a service account json key, but is there a way I can tell gspread to use the default service account credentials without pointing to a json?
My use-case is that I want to run gspread in a vm (or cloud function) that already comes with an IAM role and I can't seem to figure out where to get the json file from. I also don't want to copy the json to the vm unnecessarily.
You can use google.auth to get the credentials of the default service account.
Then you can use gspread.authorize() with these credentials:
import google.auth
import gspread
credentials, project_id = google.auth.default(
scopes=[
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
)
gc = gspread.authorize(credentials)
As per the use case, Cloud function has Runtime service account feature which allows you to use default service account or you can attach any service account to the cloud function.
Using this library you can do the thing without json file.
import google.auth
credentials, project_id = google.auth.default()

Error 403 google spreadsheets gspread when open in console

I'm trying to repeat the guide (https://www.youtube.com/watch?v=vISRn5qFrkM) - generated client_secrets.json, put it in the DAGs folder (because then I will run the script from airflow)
But despite the client secret-still gives the error 403-not enough rights , how can I fix it?
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',scope)
client = gspread.authorize(creds)
sheet = client.open('Data base').sheet4
result = sheet.get_all_records()
print(result)
self solved - apparently when you use the file name it refers to the disk API to find this file
therefore, you must also log in to drive. to do this, you need to add it to the scope
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint
scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/spreadsheets.readonly", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json',scope)
client = gspread.authorize(creds)
sheet = client.open('Data base').worksheet("Sum Data")
result = sheet.get_all_records()
print(result)

When to login into gspread while executing an endless python script

I dont know when it is optimal to login into gspread while exectuing my python script endlessly.
def openSheet(sheetName):
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
client = gspread.authorize(creds)
sheet = client.open(sheetName).sheet1
return sheet
As of right now I am executing the openSheet method every time I am requesting a file from gspread.
But to optimize performance of my script I thought I can define scope, creds and client at the top of my script so that it gets defined only once and not every time the endless loop gets executed.
When should I execute the login?
That is what I have done. I have scope, creds, and client immediately below my import statements, so that when I get to the functions in my script that are called repeatedly, I only have to include the portion that defines the sheet (random_variable_name = gc.open('my_spreadsheet') when I want to call a file.
For example, mine looks something like this;
import gspread
from google.colab import auth
auth.authenticate_user()
from google.colab import drive
import gspread
from oauth2client.client import GoogleCredentials
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
json_file = 'myfilepath/uberimportantstuff.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scope)
gc = gspread.authorize(credentials)
At this point, all I have to do is below to create the object.
sh = gc.open(spreadsheet_name)

How to properly connect to Google Spreadsheets API?

I want to connect to the Google Spreadsheets API with Python.
So I do:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope=['https://www.googleapis.com/auth/spreadsheets',
'https://wwww.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('cred.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('datatest').Sheet1
print(wks.get_all_records)
But I get this error
HttpAccessTokenRefreshError: invalid_scope: https://www.googleapis.com/auth/spreadsheets is not a valid audience string.
How can I use Google-auth instead of gspread with this data?
you input 4w !!!!
X 'https://wwww.googleapis.com/auth/drive'
O 'https://www.googleapis.com/auth/drive'
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('CredentialsFile.json', scope)
ss_app = gspread.authorize(credentials=credentials) # make sure your Google Sheets API is enabled
sht = ss_app.open('sheet_name_xxxx') # In your spreadsheet, click the Share button and paste the client email as same as CredentialsFile.json.client_email, and make sure your Google Drive API is enabled
wks = sht.worksheet('worksheet_name_xxxx')
print(wks.acell('A1').value)
hope that it helps.

Accessing google spreadsheet using shared link

I am building a python app where user can provide 'Anyone can edit' link to their spreadsheet and data can be read from there. I am using python's gspread module but it throws SpreadSheetNotFound error.
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('myauth.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_url(urls_given_by_user_having_edit_permission)
Above code is not working. Is there any way to achieve this?
wks.share('', perm_type='anyone', role='reader')
Read permission for all people with link. reference https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Spreadsheet.share

Categories