【问题标题】:Modifying Google Calendar API to accept environment variables rather than a JSON file for Heroku修改 Google Calendar API 以接受环境变量而不是 Heroku 的 JSON 文件
【发布时间】:2017-12-16 11:55:09
【问题描述】:

我正在将一个 Django 站点 (python 2.7) 推送到 Heroku,但是我收到了错误:

raise InvalidClientSecretsError('File not found: "%s"' % filename)
oauth2client.clientsecrets.InvalidClientSecretsError: File not found: "calendar_secret.json"

运行 cron 作业时,这是因为我的文件 calendar_secret.json 不在我的仓库中。我故意没有推送它,以便出于安全原因不知道数据。

我的问题是关于如何修改此处找到的 Google 的默认代码:https://developers.google.com/google-apps/calendar/quickstart/python,特别是 get_credentials 方法,以便在 JSON 或方法中直接使用环境变量,这样我就不必上传我的日历秘密。

这是 Google 的代码:

def get_credentials(self):
 """Gets valid user credentials from storage.

 If nothing has been stored, or if the stored credentials are invalid,
 the OAuth2 flow is completed to obtain the new credentials.

 Returns:
    Credentials, the obtained credential.
 """
 home_dir = os.path.expanduser('~')
 credential_dir = os.path.join(home_dir, '.credentials')
 if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
 credential_path = os.path.join(credential_dir, 'json-file.json')

 store = Storage(credential_path)
 credentials = store.get()
 if not credentials or credentials.invalid:
     flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
     flow.user_agent = APPLICATION_NAME
     if flags:
         credentials = tools.run_flow(flow, store, flags)
     else:  # Needed only for compatibility with Python 2.6
         credentials = tools.run(flow, store)
     print('Storing credentials to ' + credential_path)
 return credentials

效果很好。但我很想修改此方法以在 JSON 中使用环境变量。

这是对这个问题的另一种看法:Environment Variables in Json file,但答案在这里没有意义。

提前致谢!

【问题讨论】:

    标签: python json django heroku environment-variables


    【解决方案1】:

    想通了!您所要做的就是将流程代码替换为以下内容:

    flow = client.OAuth2WebServerFlow(client_id=YOUR-SAVED-ENV-ID-HERE,
                                      client_secret=YOUR-SAVED-ENV-SECRET-HERE,
                                      scope='https://www.googleapis.com/auth/calendar',
                                      redirect_uris='YOUR-URIS-HERE')
    

    更多信息在这里:https://developers.google.com/api-client-library/python/guide/aaa_oauth

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 2018-03-23
      • 2015-06-12
      • 2021-09-04
      • 2023-03-18
      • 2018-07-29
      • 2020-11-24
      • 2016-06-25
      • 1970-01-01
      相关资源
      最近更新 更多