1

是否可以从 dict 而不是文件加载凭据?这将使在云函数中使用短脚本变得更容易,因为这样就不需要上传文件了。通常授权是这样的:

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

如果凭据存储在 a 变量中,如下所示:

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"
}

是否可以使用custom_credentials而不是加载它们service_file?除了“此选项将忽略任何其他参数”之外,文档没有提供有关如何使用它的任何说明。以下代码:

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

引发以下错误:

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

还有另一种方法可以做到这一点吗?gspread例如,在中,有以下选项:

ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scope)

有什么建议么?谢谢!!!

4

3 回答 3

3

刚做了这个!所以我们最终做的是编写一个临时文件,然后加载它以进行授权。下面的工作示例:

import tempfile

def _google_creds_as_file():
    temp = tempfile.NamedTemporaryFile()
    temp.write(json.dumps({
        "type": "service_account",
        "project_id": "xxxx-yyy",
        "private_key_id": "xxxxxxx",
        "private_key": "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n",
        "client_email": "xxx@yyyy.iam.gserviceaccount.com",
        "client_id": "xxxxx",
        "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": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxx%40xxxx.iam.gserviceaccount.com"
    }))
    temp.flush()
    return temp

creds_file = _google_creds_as_file()
gc = pygsheets.authorize(service_account_file=creds_file.name)
于 2019-06-30T06:14:14.073 回答
1

感谢@kontinuity 的建议。经过一番挖掘,我发现实际上已经有一个拉取请求: https ://github.com/nithinmurali/pygsheets/pull/345

authorization.py中有一个名为service_account_env_var. 刚刚试了一下,效果很好。

于 2019-06-30T20:47:21.983 回答
1

custom_credentials 应该是这里提到的凭证对象。如果不想创建 tmp 文件,可以直接从 json 创建对象。

SCOPES = ('https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive')
service_account_info = json.loads(secret)
my_credentials = service_account.Credentials.from_service_account_info(service_account_info, scopes=SCOPES)
于 2020-03-07T21:31:24.530 回答