0

I'm looking for a way to build a Google Credentials object and access my Google Sheets spreadsheet without having to reference another file containing my client_secret.json data. This feels like it should be quite easy to do, I just want to be able to copy the JSON into my python script and access it that way, but I haven't been able to find a way to do it.

According to https://oauth2client.readthedocs.io/en/latest/source/oauth2client.file.html it seems like the only way to use the current method is with a filepath, but again if the file literally only contains JSON, it seems like there should be a way of just putting the JSON in my python script and using it from there.

Listed below is how I currently get the values from my json file.

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

SPREADSHEET_ID = ID
RANGE_NAME = sheetName + '!A2:D'
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                             range=RANGE_NAME).execute()
tehhowch
  • 9,645
  • 4
  • 24
  • 42
  • I'm a little confused, but if you want to keep your creds in the script, you can probably just make a dict with them in there. – SuperStew Jul 11 '18 at 21:06
  • If you switch away from the [deprecated `oauth2client`](https://google-auth.readthedocs.io/en/latest/oauth2client-deprecation.html) package and move to the [`google-auth`](https://google-auth.readthedocs.io/en/latest/index.html) / [`google-auth-oauth`](https://google-auth-oauthlib.readthedocs.io/en/latest/) packages, you can use the [`Flow.from_client_config`](https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html) method with your dict of the information from the `client_secrets` file. – tehhowch Jul 11 '18 at 21:25

1 Answers1

0

Changed my code to this:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('credentials.json')

flow = client.OAuth2WebServerFlow(client_id='619103408544-qbpfk38g9jk4tkc5gshvds9hs8g5ur9o.apps.googleusercontent.com',
                                    client_secret='faJQr2Wd3x25_yKYIWslxR4s',
                                    scope=SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

Used a different function to create the flow, turns out you don't need to actually use the store to make the credentials so I just deleted the store.get() line.

  • 1
    Thanks for the tip, I'll update my post definitely new to this site. –  Jul 12 '18 at 18:20