【问题标题】:How to use JSON string as credentials instead of filepath for Python with Google API如何使用 JSON 字符串作为凭据,而不是使用 Google API 的 Python 文件路径
【发布时间】:2018-07-11 21:04:43
【问题描述】:

我正在寻找一种方法来构建 Google Credentials 对象并访问我的 Google 表格电子表格,而无需引用包含我的 client_secret.json 数据的另一个文件。这感觉应该很容易做到,我只想能够将 JSON 复制到我的 python 脚本中并以这种方式访问​​它,但我一直无法找到一种方法来做到这一点。

根据https://oauth2client.readthedocs.io/en/latest/source/oauth2client.file.html,似乎使用当前方法的唯一方法是使用文件路径,但如果文件实际上只包含 JSON,似乎应该有一种方法将 JSON 放入我的 python脚本并从那里使用它。

下面列出的是我目前如何从我的 json 文件中获取值。

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

SPREADSHEET_ID = ID
RANGE_NAME = sheetName + '!A2:D'
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                             range=RANGE_NAME).execute()

【问题讨论】:

标签: python google-api google-oauth google-api-python-client oauth2client


【解决方案1】:

将我的代码更改为:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('credentials.json')

flow = client.OAuth2WebServerFlow(client_id='619103408544-qbpfk38g9jk4tkc5gshvds9hs8g5ur9o.apps.googleusercontent.com',
                                    client_secret='faJQr2Wd3x25_yKYIWslxR4s',
                                    scope=SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

使用不同的函数来创建流程,事实证明您不需要实际使用商店来制作凭据,所以我只是删除了 store.get() 行。

【讨论】:

  • 感谢您的提示,我会更新我的帖子,绝对是本网站的新内容。
猜你喜欢
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
相关资源
最近更新 更多