Reputation: 1133
I use the following to access bouth Google Drive and Google Sheets in my Google Colab Notebook:
# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')
# Google Sheets
from google.colab import auth
auth.authenticate_user()
import gspread
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
from gspread_dataframe import get_as_dataframe, set_with_dataframe
My problem with this is that it asks for the user to confirm the authentication in a pop-up and I want to use colabctl (https://github.com/bitnom/colabctl) to automate the execution of some scripts, so I need to execute the authentication part without user interaction.
Upvotes: 4
Views: 9121
Reputation: 491
As a possible solution, I may suggest using Service Account
.
Go to GCP Console
Select your current project (or create a new one):
Once the project is selected, go to IAM and Admin
-> Service accounts
-> + Create service account
:
Next, you'll see a create service account prompt, which consists of 3 form steps. Fill in step 1 with any data you want. Skip steps 2 and 3.
You'll be redirected to the new service account page. Note an Email
field there. You may share any Google Drive content for that email address (same as you do for users' personal email addresses).
Now you need to create a service account key, so you could use it to authenticate your script (select JSON
key type):
After step 6, you should get your JSON
key file downloaded. Put it into your Google Colab
files. You may do something like that to initialize your google client (gc
) :
import gspread
gc = gspread.service_account(filename='/content/credentials.json')
Important: gspread
version should be >=3.6.0
to support service_account()
method.
Note: See my example to list all shared Google Sheets
using gspread
:
Upvotes: 4