python - pygsheets - 从字典而不是文件加载凭据

标签 python python-3.x gspread pygsheets

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

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 加载它们? docs不要给出任何关于如何使用它的说明,除了“这个选项将忽略任何其他参数”。以下代码:

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)

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

最佳答案

刚刚做到了!所以我们最终做的是写一个 tempfile然后加载授权。下面的工作示例:

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)

关于python - pygsheets - 从字典而不是文件加载凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56817195/

相关文章:

python - 提取 pandas 中特定列名的值

python - 获取 Python Tkinter 对象类型

python - Selenium click() - 选择按钮但不单击

Python SSL错误解密失败或坏记录mac

python - gspread 错误 : SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] in python

python - 通过 itertools.product 在列表中使用列表

App Engine 上的 Python 2.7,simplejson 与原生 json,谁更快?

python - Python 3 C API 中的文件 I/O

python - 无法通过简单地返回原生异步协程来链接它们

python-2.7 - gspread 之类的 : help me get cell coordinates (not value)