我需要使“google-credentials.json”文件在heroku上工作,它通过将本地路径放在我的笔记本电脑上在本地工作,但在heroku中我不知道该怎么做。
我搜索了很多,我找到了这个解决方案 How to use Google API credentials json on Heroku? 但我无法让它工作,也许解决方案是旧的,或者我做错了,解决方案是:
1 - Declare your env variables from in Heroku dashboard The GOOGLE_CREDENTIALS variable is the content of service account credential JSON file as is. The GOOGLE_APPLICATION_CREDENTIALS env variable in the string "google-credentials.json"
2 - Once variables are declared, add the builpack from command line :
$ heroku buildpacks:add https://github.com/elishaterada/heroku-google-application-credentials-buildpack
3 - Make a push. Update a tiny thing and push.
这是错误日志:
2022-03-11T09:22:57.866153+00:00 app[worker.1]: Traceback (most recent call last):
2022-03-11T09:22:57.866234+00:00 app[worker.1]: File "/app/Professor_Bot.py", line 102, in <module>
2022-03-11T09:22:57.866678+00:00 app[worker.1]: cred_obj = firebase_admin.credentials.Certificate(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])
2022-03-11T09:22:57.866696+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/firebase_admin/credentials.py", line 83, in __init__
2022-03-11T09:22:57.866909+00:00 app[worker.1]: with open(cert) as json_file:
2022-03-11T09:22:57.866987+00:00 app[worker.1]: FileNotFoundError: [Errno 2] No such file or directory: "'google-credentials.json'"
2022-03-11T09:22:58.491014+00:00 heroku[worker.1]: Process exited with status 1
2022-03-11T09:22:58.644442+00:00 heroku[worker.1]: State changed from up to crashed
这是Python代码:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
import json
import os
cred_obj = firebase_admin.credentials.Certificate(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])
default_app = firebase_admin.initialize_app(cred_obj, {
'databaseURL': 'https://professorbot-325702-default-rtdb.firebaseio.com/'})
ref = db.reference("/")
ref.set({
'boxes':
{
'box001': {
'color': 'red',
'width': 1,
'height': 3,
'length': 2
},
'box002': {
'color': 'green',
'width': 1,
'height': 2,
'length': 3
},
'box003': {
'color': 'yellow',
'width': 3,
'height': 2,
'length': 1
}
}
})
我希望有人能帮助我,非常感谢
最佳答案
您可以将每个键值对手动放入这些配置变量中,然后使用os.environ.get(key, default)
在Python程序中访问它们,而不是在配置变量中粘贴整个凭证json文件。 .
例如。如果您的配置 Var 如下:name: abc
, os.environ.get(name, "Not Available")
将返回abc
如果名称键存在,否则“不可用”。
您可以做的其他事情是,公开您的 json 文件,使用“运行”部分中的curl 命令在您的 Heroku 机器上手动下载该文件,然后它就可以在本地机器上使用,但我不推荐这种方式。配置变量很好。
关于python - 在 Heroku 上使用环境变量作为凭证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71436662/