“ initialize_app'默认的Firebase应用程序已存在。” 云功能发布子

Lan*_*n G 1 python python-3.x firebase google-cloud-pubsub google-cloud-functions

我在Google Cloud(云函数内联编辑器)上编写了一个pub子函数,该函数将每半小时触发一次,并且使用firestore。由于某种原因,该函数在首次运行时会触发正常,但此后不断弹出以下错误:

in initialize_app 'The default Firebase app already exists. This means you 
called ' ValueError: The default Firebase app already exists. This means you 
called initialize_app() more than once without providing an app name as the 
second argument. In most cases you only need to call initialize_app() once. 
But if you do want to initialize multiple apps, pass a second argument to 
initialize_app() to give each app a unique name.
Run Code Online (Sandbox Code Playgroud)

使用两个应用程序之前,我曾遇到此错误,但是此功能仅使用一个Firebase应用程序。这是我的代码部分,我怀疑这是问题所在:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

def hello_pubsub(event, context):
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    fire = {<My firebase credentials>}
    cred = credentials.Certificate(fire)
    default_app = firebase_admin.initialize_app(cred)
    db = firestore.client()
    ........
Run Code Online (Sandbox Code Playgroud)

我发现问题恰恰是错误所说的,我还没有声明应用程序的名称,所以我尝试了这个(以及其他尝试):

default_app = firebase_admin.initialize_app(cred,'App')
# other attempt
default_app = firebase_admin.initialize_app()
Run Code Online (Sandbox Code Playgroud)

而且这仍然行不通。再次,这在第一次触发该功能时有效,但是此后它不断崩溃。

有什么建议么?

谢谢您的帮助!

Rac*_*acu 5

由于这是一个cloud-function,您不需要使用凭据,因此该功能将从环境中获取凭据。我建议为此更改您的功能:

import firebase_admin
from firebase_admin import firestore

firebase_admin.initialize_app()
db = firestore.client()


def hello_pubsub(event, context):
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    # Do your things
Run Code Online (Sandbox Code Playgroud)

在部署前使用功能时,请使用凭据,然后在部署时删除不需要的凭据部分。

另外,如果您不需要firebase_admin导入Firestore,则可以跳过初始化,firebase_app而单独使用Firestore,如下所示:

import base64

from google.cloud import firestore

db = firestore.Client()


def hello_pubsub(event, context):
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    # Do your things
Run Code Online (Sandbox Code Playgroud)

请注意,Firebase firestore客户端和google-cloud firestore客户端之间的区别是“大写C”,您必须在计算机上安装firestore python库才能进行开发,测试和修改requirements.txt