Search code examples
pythonpython-3.xgspreadpygsheets

pygsheets - Load credentials from dict instead of file


Is it possible to load credentials from dict instead of file? This would make it easier to use short scripts in cloud functions, because then there is no need for uploading files. Normally authorization goes like this:

import pygsheets
gc = pygsheets.authorize(service_file='client_secret.json')

If credentials are stored in the a variable like this:

secret = {
  "type": "service_account",
  "project_id": "XXXXXXXXXX",
  "private_key_id": "XXXXXXXXXX",
  "private_key": "XXXXXXXXXX"
  "client_email": "XXXXXXXXXX",
  "client_id": "XXXXXXXXXX",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "XXXXXXXXXX"
}

Would it be possible to load them with custom_credentials instead of service_file? The docs don't give any instructions on how to use it, except "this option will ignore any other parameters". The following code:

import pygsheets
gc = pygsheets.authorize(custom_credentials=secret)

Throws the following error:

AttributeError: 'dict' object has no attribute 'before_request'

Is there another way to do this? In gspread, for example, there is the following option:

ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scope)

Any suggestions? Thanks!!!


Solution

  • Thanks for the suggestion @kontinuity. After some digging I found out there is actually already a pull request for this: https://github.com/nithinmurali/pygsheets/pull/345

    In the authorization.py there is a new option called service_account_env_var. Just tried it and this works perfect.