Reputation: 367
from google.oauth2 import service_account
import pygsheets
creds = service_account.Credentials.from_service_account_file(
'my/path/to/credentials.json',
scopes=('https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'),
subject='[email protected]'
)
pg = pygsheets.authorize(custom_credentials=creds)
pg.open_by_url('https://docs.google.com/spreadsheets/d/my_spreadsheet_id/edit#gid=my_sheet_id')
Fails on the last line with Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
The last line provides an object for Google Sheets access.
subject
account is on the domainsubject
accountsubject
and share the sheet with the service account directly, it worksEnvironment
python==3.6.9
pygsheets==2.0.3.1
google-auth==1.6.3
Upvotes: 2
Views: 1756
Reputation: 26796
The domain-wide delegation is not enabled by default. To allow it you need to follow the steps described in the documentation.
Enable G Suite Domain-wide Delegation
for each service account you want to use for such purpose
To you use the service account to impersonate a user, you need to give the necessary permissions in the Admin consoleMain menu menu> Security > API controls.
Client ID
, provide it all the scopes it needs and authorizeUpvotes: 2