【问题标题】:calling firestore from python cloud function and app_initialization从 python 云函数和 app_initialization 调用 firestore
【发布时间】: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()

如果我保留该行,则该函数在我第一次调用它时工作,但在第二次尝试时失败,因为它说它已经存在。

  1. 如果我只访问数据库,为什么需要初始化应用程序?
  2. 从谷歌云功能访问 Firestore 的正确方法是什么?我感觉这个initialize_app 调用很慢。

【问题讨论】:

    标签: python firebase google-cloud-platform google-cloud-firestore google-cloud-functions


    【解决方案1】:

    每个进程只需要初始化一次 Firebase Admin SDK。 Cloud Functions 可能会在同一进程中按顺序处理函数的多次调用,因此您应确保该进程仅在全局范围内调用 initialze_app 一次。因此,最简单的做法实际上就是在全局范围内初始化一次。

    from firebase_admin import credentials, firestore
    firebase_admin.initialize_app()
    

    现在您可以在您的函数中使用它,而无需再次担心 init。

    【讨论】:

    • 如果我有 2 个独立的云功能怎么办?他们会在这个initialize_app 上发生冲突吗?
    • 每个函数在其自己的一组服务器实例中独立于所有其他函数运行。我建议阅读文档以了解更多信息。 cloud.google.com/functions/docs/concepts/exec
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2021-09-25
    • 2021-02-09
    相关资源
    最近更新 更多