[Tool] python项目中集成使用Firebase推送功能

这是我参与11月更文挑战的第27天,活动详情查看:2021最后一次更文挑战

背景介绍

  • 目前,App推送功能已经非常普遍,几乎所有App都有推送功能。
  • 推送功能可以自己实现,也可以使用第三方提供的推送服务(免费的收费的都有)。
  • 本文主要介绍使用Firebase提供的推送服务Firebase Cloud Messaging(简称FCM)。
  • 本文主要介绍FCM工作原理、后端集成流程,但不包括客户端集成方面的内容。

FCM使用

  • 官网:firebase.google.com/docs/cloud-…

  • 简介:Firebase Cloud Messaging (FCM) 是一种跨平台消息传递解决方案,可供您可靠地传递消息,且无需任何费用。使用 FCM,您可以通知客户端App有新的电子邮件或其他数据等待同步。您可以发送通知消息与用户互动并留住他们。

  • 主要功能:发送通知消息或数据消息

  • 工作原理:

    • FCM 实现包括用于发送和接收的两个主要组件:

    • 一个受信任的环境,例如 Cloud Functions for Firebase 或用于构建、定位和发送消息的应用服务器。

    • 一个通过针对具体平台的相应传输服务接收消息的 Apple、Android 或 Web (JavaScript) 客户端应用。

    • 您可以通过 Firebase Admin SDKFCM 服务器协议发送消息。

image.png

  • 工作原理图解说明

    • 首先,可以通过后端api或者Console GUI创建发推送消息的请求,该请求会交给FCM backend
    • 然后,由FCM backend帮我们把消息推送到用户手机上,并且支持跨平台推送
    • 用户手机上能收到消息的前提:安装了集成FCM SDK的App
    • 注意1:后端通过api创建推送请求使用的是FCM Admin SDK,客户端开发使用的是FCM SDK
    • 注意2:后端通过api创建推送请求可以直接使用FCM Admin SDK, 或者按照FCM 服务器协议自己实现
  • 发送消息的方式:

    • 发送消息的方式有两种:按设备注册token、按主题

    • 每个安装了集成FCM SDK的客户端,都可以生成唯一的register_token,这个register_token会由App客户端给到App服务端。服务端拿到这个register_token,就可以只给这个设备推送消息。

    • 每个设备也可以订阅主题,订阅主题后,可以直接给这个主题推送消息。这样所有订阅过该主题的设备都可以收到推送消息。

FCM集成到服务器(Python)

  • 目前,FCM Admin SDK支持五种服务端编程语言:Node.js、Java、Python、Go、C#

  • 前提条件:

    • 确保您拥有服务器应用。
    • 确保您的服务器运行 Admin Python SDK — Python 3.6+
  • 设置Firebase项目和服务账号

    • 如需使用 Firebase Admin SDK,您需要具备以下项:
    • Firebase 项目
    • 用于与 Firebase 通信的服务帐号
    • 包含服务帐号凭据的配置文件
  • 创建Firebase项目

# Firebase控制台:https://console.firebase.google.com

# 创建流程
1. 在 Firebase 控制台中,点击添加项目
2. 如果出现 Firebase 条款提示,请查看并接受。
3. 点击继续。
4. 为您的项目设置 Google Analytics(可选)
5. 点击创建项目(如果使用现有的 Google Cloud 项目,则点击添加 Firebase)
复制代码
  • 创建包含服务帐号凭据的配置文件
1. 在 Firebase 控制台中,打开设置 > 服务帐号。
2. 点击生成新的私钥,然后点击生成密钥进行确认。
3. 妥善存储包含密钥的 JSON 文件.
复制代码
  • 添加SDK

Firebase Admin Python SDK 可通过 pip 获得。

pip3 install firebase-admin
复制代码
  • 初始化SDK

通过服务帐号进行授权时,有两种方式可为您的应用提供凭据。

方式1(推荐)

(1)将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含服务帐号密钥的 JSON 文件的文件路径

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
复制代码

(2)完成上述步骤后,应用默认凭据 (ADC) 能够隐式确定您的凭据

import firebase_admin


default_app = firebase_admin.initialize_app()
复制代码

方式2:直接在代码中写死JSON文件路径


import firebase_admin
from firebase_admin import credentials


cred = credentials.Certificate("path/to/service_account.json")
default_app = firebase_admin.initialize_app(credential=cred)
复制代码
  • 向指定设备发送消息
from firebase_admin import messaging

# This registration token comes from the client FCM SDKs.
registration_token = 'YOUR_REGISTRATION_TOKEN'

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='your_titme',
        body='your_body',
        image='your_img',
    ),
    token=registration_token,
)

# Send a message to the device corresponding to the provided registration token.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
复制代码
  • 向主题发送消息

创建主题后,使用服务器 API向主题发送消息,则订阅过该主题的设备都会受到消息。

from firebase_admin import messaging

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='your_titme',
        body='your_body',
        image='your_img',
    ),
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

复制代码
  • 批量发送消息
# Create a list containing up to 500 messages.
messages = [
    messaging.Message(
        notification=messaging.Notification('Price drop', '5% off all electronics'),
        token=registration_token,
    ),
    # ...
    messaging.Message(
        notification=messaging.Notification('Price drop', '2% off all books'),
        topic='readers-club',
    ),
]

response = messaging.send_all(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))

复制代码
  • 服务端订阅主题

客户端SDK可以帮用户订阅主题,服务端可以通过接口帮用户订阅主题。

您可以为客户端应用实例订阅任何现有主题,也可创建新主题。当您使用 API 为客户端应用订阅新主题(您的 Firebase 项目中尚不存在的主题)时,系统会在 FCM 中创建一个使用该名称的新主题,随后任何客户端都可订阅该主题。

# 您可以将注册令牌列表传递给 Firebase Admin SDK 订阅方法,以便为相应的设备订阅主题

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Subscribe the devices corresponding to the registration tokens to the
# topic.
response = messaging.subscribe_to_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were subscribed successfully')
复制代码

注意:在单次请求中,您最多可以为 1000 台设备订阅或退订主题。

  • 服务端推订主题

利用 Admin FCM API,您还可以将注册令牌传递给相应的方法,来为设备退订主题

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Unubscribe the devices corresponding to the registration tokens from the
# topic.
response = messaging.unsubscribe_from_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were unsubscribed successfully')
复制代码

总结

  • 使用Firebase可以快速实现消息推送,支持跨平台,并且免费使用。
  • 可以通过借助 Firebase Admin SDK实现消息推动和主题管理,也可以按照FCM 服务器协议自己实现接口。
  • Firebase Admin SDK优点:使用方便,啥都有。
  • Firebase Admin SDK缺点:包太大不轻便(推送功能仅使用FCM),不支持asyncio异步操作。

结语

文章首发于微信公众号程序媛小庄,同步于掘金

码字不易,转载请说明出处,走过路过的小伙伴们伸出可爱的小指头点个赞再走吧(╹▽╹)

Guess you like

Origin juejin.im/post/7035073571051274248