【发布时间】:2021-03-17 14:09:29
【问题描述】:
我是 gcp 新手,我对 firebase 和 gcp 之间的集成感到非常困惑。
我有一个带有一些数据的 firestore 数据库和一个需要在那里读写数据的 python 云函数。
这是我的云功能之一的main.py 文件:
import traceback
import firebase
import firebase_admin
from firebase_admin import credentials, firestore
#@firestore.transactional
def _run(data):
print("Starting transaction. Input data=%s" % data)
db = firestore.client()
doc_ref = db.collection(u'users').document(data['username']).collection(u'groups').document(data['group'])
group_ref = db.collection(u'groups').document(data['group'])
user_ref = db.collection(u'users').document(data['username'])
doc = doc_ref.get()
if doc.exists:
print("user: ", data['username'], ' is already member of the group: ', data['group'])
return
else:
if data['rating'] == "":
data['rating'] = 50
x = {'rating': data['rating'],
'n_games': 0,
'subscription_time_secs': time.time(),
'group_ref': group_ref}
doc_ref.set(x,
merge=True)
group_ref.collection(u'users').document(data['username']).set({'user_ref': user_ref})
return
def run(request):
"""This endpoint is called as:
curl http://0.0.0.0:8080/post -d '{"username": "luca", "group": "padel_roma", "rating": None}' -H 'Content-Type: application/json'
"""
data = request.get_json()
print("Cloud function called with input ", data)
try:
firebase_admin.initialize_app()
_run(data)
return {'success': True}
except Exception as e:
err = traceback.format_exc()
return {'success': False, 'error': str(err)}
这只是一个 http 触发函数,可以读取和写入一些数据到我的 firestore db。如您所见,它调用firebase_admin.initialize_app()。
我对此感到非常困惑。
如果我删除该行,我会得到:
ValueError(\nValueError: The default Firebase app does not exist. Make sure to initialize the SDK by calling initialize_app()
如果我保留该行,则该函数在我第一次调用它时工作,但在第二次尝试时失败,因为它说它已经存在。
- 如果我只访问数据库,为什么需要初始化应用程序?
- 从谷歌云功能访问 Firestore 的正确方法是什么?我感觉这个
initialize_app调用很慢。
【问题讨论】:
标签: python firebase google-cloud-platform google-cloud-firestore google-cloud-functions