在Heroku中访问Google API环境变量时遇到问题

时间:2019-02-21 01:27:10

标签: python heroku

我正在尝试使用Heroku上部署的某些Python代码授权Google表格。我的Google服务帐户授权已作为环境变量存储在Heroku中。

credentials = environ['GOOGLE_APPLICATION_CREDENTIALS']
gc = pygsheets.authorize(service_file=credentials)

但是,当我在Heroku上运行脚本时,出现错误。

FileNotFoundError: [Errno 2] No such file or directory:

接着是我的GOOGLE_APPLICATION_CREDENTIALS变量的整个JSON转储。

'{\n  "type": "service_account", [...] gserviceaccount.com"\n}'

当项目文件夹中有JSON文件时,这在我的计算机上本地可以正常工作。

这是导致FileNotFoundError的完整回溯:

  

回溯(最近一次通话最后一次):文件“ code.py”,第27行,   在       gc = pygsheets.authorize(service_file = credentials)文件“ /app/.heroku/python/lib/python3.7/site-packages/pygsheets/authorization.py”,   第111行,授权       凭证= service_account.Credentials.from_service_account_file(service_account_file,   scopes = scopes)文件   “ /app/.heroku/python/lib/python3.7/site-packages/google/oauth2/service_account.py”,   第209行,位于from_service_account_file中       文件名,require = ['client_email','token_uri'])文件“ /app/.heroku/python/lib/python3.7/site-packages/google/auth/_service_account_info.py”,   第71行,位于from_filename中       io.open(filename,'r',encoding ='utf-8')作为json_file:

2 个答案:

答案 0 :(得分:1)

最后弄清楚了。

需要使用json.loads将环境变量转换为JSON,然后使用json.dump将其写入JSON文件。这是因为pydrive仅接受服务凭据作为JSON文件,并且Heroku env var实际上并不存储为JSON,即使它们是从JSON文件创建的。

#AUTHENTICATE
gauth = GoogleAuth()
scope = ['https://www.googleapis.com/auth/drive']
creds = json.loads(os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'))
with open('gcreds.json', 'w') as fp:
    json.dump(creds, fp)
gauth.credentials = 
ServiceAccountCredentials.from_json_keyfile_name('gcreds.json', scope)
drive = GoogleDrive(gauth)

答案 1 :(得分:1)

@ 24hourbreakfast时,我刚刚在pygsheets库中添加了通过via-env-var的凭据:

https://github.com/nithinmurali/pygsheets/pull/345

不确定他何时发布下一个版本,希望很快发布。