首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pygsheets从字典而不是文件加载凭据

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

Stack Overflow用户
提问于 2019-06-29 19:30:09
回答 3查看 1.2K关注 0票数 1

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

代码语言:javascript
复制
import pygsheets
gc = pygsheets.authorize(service_file='client_secret.json')

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

代码语言:javascript
复制
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没有给出任何关于如何使用它的说明,除了“这个选项将忽略任何其他参数”。以下代码:

代码语言:javascript
复制
import pygsheets
gc = pygsheets.authorize(custom_credentials=secret)

抛出以下错误:

代码语言:javascript
复制
AttributeError: 'dict' object has no attribute 'before_request'

有没有其他方法可以做到这一点?例如,在gspread中,有以下选项:

代码语言:javascript
复制
ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scope)

有什么建议吗?谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-07-01 04:47:22

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

authorization.py中有一个名为service_account_env_var的新选项。我刚试过,这个效果很好。

票数 1
EN

Stack Overflow用户

发布于 2019-06-30 14:14:14

就这么做了!因此,我们最终要做的是编写一个tempfile,然后加载它以进行授权。工作示例如下:

代码语言:javascript
复制
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)
票数 3
EN

Stack Overflow用户

发布于 2020-03-08 05:31:25

正如前面提到的here,custom_credentials应该是一个凭证对象。如果不想创建tmp文件,可以直接从json创建对象。

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56817195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档