我正在使用 Google Calendar API 制作一个应用,并计划在 Heroku 上构建它。
我有一个关于身份验证的问题。通常我为此使用凭据 json 文件,但这次出于安全原因我不想将其上传到 Heroku。
如何在 Heroku 上进行身份验证?
现在,我将我的 json 放到一个环境变量中,并使用 oauth2client
的 from_json
方法。
def get_credentials():
credentials_json = os.environ['GOOGLE_APPLICATION_CREDENTIALS']
credentials = GoogleCredentials.from_json(credentials_json)
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
但是这段代码并不完美。如果凭据无效,我希望代码将新凭据写入环境变量,而不是新文件。
有没有更好的办法?
最佳答案
我花了一整天的时间来寻找解决方案,因为它很棘手。 无论您使用何种语言,解决方案都是一样的。
1 - 在 Heroku 仪表板中声明您的环境变量,例如:
GOOGLE_CREDENTIALS 变量是服务帐户凭证 JSON 文件的内容。 字符串“google-credentials.json”中的 GOOGLE_APPLICATION_CREDENTIALS 环境变量
2 - 声明变量后,从命令行添加 builpack:
$ heroku buildpacks:add https://github.com/elishaterada/heroku-google-application-credentials-buildpack
3 - 插入。更新一个小东西然后推送。
4 - buildpack 会自动生成一个 google-credentials.json 并用 google 凭据内容填充它。
如果你在某件事上失败了,它就不会成功。使用 Heroku bash 检查 google-credentials.json 的内容。
关于python - 如何在 Heroku 上使用 Google API 凭据 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446480/