Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Google spreadsheet with Python for server-to-server use

I am trying to update a Google spreadsheet from a server that some target users can see on a daily basis. Here is what I tried:

Created a project in "console.developers.google.com" then selected "drive API" -> "credentials" -> "add credentials" -> "service accounts" -> "create Json file"

Now with this JSON file (project name-e4sdfsdsdf0c.json) I tried to access Spreadsheets.

import gdata.spreadsheet.service
import gdata.service
import urlparse
import httplib2
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
spreadsheet_key = '13jQtgSUXKBExMvZjECf6sdfsfgLfmRFVmZw6t7hYyX3g0'
storage = Storage("creds.dat")
credentials = storage.get() 
if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow_from_clientsecrets("project name-e4sdfsdsdf0c.json", scope=["https://spreadsheets.google.com/feeds"]), storage)
if credentials.access_token_expired:
    credentials.refresh(httplib2.Http())

spr_client = gdata.spreadsheet.service.SpreadsheetsService(
    additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

worksheets = spr_client.GetSpreadsheetsFeed(spreadsheet_key)
print worksheets.title

But I am getting this error:

Invalid file format. See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets Expected a JSON object with a single property for a "web" or "installed" application"

like image 324
Vikas Avatar asked Jun 15 '26 03:06

Vikas


1 Answers

You created a service account but it looks like you're trying to access it using a client flow.

Have a look at the service account documentation here: https://developers.google.com/identity/protocols/OAuth2ServiceAccount

The first step would be to go back to the developer console and generate a p12 key. Then the basic flow for Python looks like this:

from oauth2client.client import SignedJwtAssertionCredentials

scope = 'https://www.googleapis.com/auth/drive.readonly https://spreadsheets.google.com/feeds'

client_email = '<your service account email address>'
with open("MyProject.p12") as f:
  private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key, scope)
http_auth = credentials.authorize(Http())
like image 176
Carl Avatar answered Jun 17 '26 16:06

Carl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!