You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何指定Firebase Admin实例发送多应用推送消息

问题

我拥有两个不同的Firebase应用,分别对应不同的credentials,因此已两次初始化firebase_admin。

Firebase导入代码

from firebase_admin import credentials, messaging

初始化两个Firebase Admin实例并配置JSON凭证

# initialize firebase 1
json_file_first = "第一个json文件路径"
credentials_first = credentials.Certificate(json_file_first)
first_app = firebase_admin.initialize_app(credentials_first, name="first")


# initialize firebase 2
json_file_second = "第二个json文件路径"
credentials_second = credentials.Certificate(json_file_second)
second_app = firebase_admin.initialize_app(credentials_second, name="second")

消息创建与发送代码

def sendPushNotificationTest(title, msg, registration_token):
    message = messaging.MulticastMessage(    # 这里默认使用firebase_admin的默认实例
        notification=messaging.Notification(
        title=title,
        body=msg),
        tokens=registration_token

        )
    response = messaging.send_multicast(message)

在创建/发送推送消息时,需要选择使用firebase_admin的"first"或"second"实例,请问应在哪里指定对应的已初始化实例?


解决方案

你需要在调用messaging.send_multicast()方法时,通过app参数指定要使用的Firebase Admin实例,消息创建阶段不需要绑定实例,实例是在发送动作时关联的。

动态切换实例的实现方式

可以给发送函数新增一个参数接收目标实例,实现动态切换:

def sendPushNotificationTest(title, msg, registration_token, target_app):
    message = messaging.MulticastMessage(
        notification=messaging.Notification(
            title=title,
            body=msg
        ),
        tokens=registration_token
    )
    # 通过app参数指定要使用的Firebase实例
    response = messaging.send_multicast(message, app=target_app)
    return response

调用时直接传入初始化好的实例即可:

# 使用first实例发送推送
sendPushNotificationTest("测试标题1", "测试内容1", ["设备token1"], first_app)
# 使用second实例发送推送
sendPushNotificationTest("测试标题2", "测试内容2", ["设备token2"], second_app)

固定使用某一个实例的实现方式

如果不需要动态切换,也可以在函数内部直接指定固定实例:

def sendPushNotificationTest(title, msg, registration_token):
    message = messaging.MulticastMessage(
        notification=messaging.Notification(
            title=title,
            body=msg
        ),
        tokens=registration_token
    )
    # 固定使用first实例
    response = messaging.send_multicast(message, app=first_app)
    return response

内容的提问来源于stack exchange,提问作者saro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:15:45