current position:Home>[tool] integrated use of firebase push function in Python project

[tool] integrated use of firebase push function in Python project

2022-02-01 12:47:09 Cheng Xuyuan Xiaozhuang

This is my participation 11 The fourth of the yuegengwen challenge 27 God , Check out the activity details :2021 One last more challenge

Background introduction

  • at present ,App Push function is already very common , Almost all App All have push function .
  • Push function can be realized by yourself , You can also use push services provided by third parties ( There are free and charged ).
  • This paper mainly introduces the use of Firebase Push service provided Firebase Cloud Messaging( abbreviation FCM).
  • This paper mainly introduces FCM working principle 、 Back end integration process , But it doesn't include the content of client integration .

FCM Use

  • Official website :firebase.google.com/docs/cloud-…

  • brief introduction :Firebase Cloud Messaging (FCM) Is a cross platform messaging solution , For you to deliver messages reliably , At no cost . Use FCM, You can notify the client App There are new emails or other data waiting to be synchronized . You can send notification messages to interact with users and retain them .

  • The main function : Send notification message or data message

  • working principle :

    • FCM The implementation includes two main components for sending and receiving :

    • A trusted environment , for example Cloud Functions for Firebase Or to build 、 An application server that locates and sends messages .

    • A method of receiving messages through corresponding transmission services for specific platforms Apple、Android or Web (JavaScript) Client applications .

    • You can Firebase Admin SDK or FCM Server protocol Send a message .

image.png

  • Schematic illustration of working principle

    • First , Through the back end api perhaps Console GUI Create a request to send a push message , The request will be submitted to FCM backend
    • then , from FCM backend Help us push the message to the user's mobile phone , And support cross platform push
    • The premise that users can receive messages on their mobile phones : Integrated... Is installed FCM SDK Of App
    • Be careful 1: Backend pass api The push request is created using FCM Admin SDK, Client development uses FCM SDK
    • Be careful 2: Backend pass api To create a push request, you can directly use FCM Admin SDK, Or in accordance with FCM Server protocol Realize it by yourself
  • How to send a message :

    • There are two ways to send messages : Register by device token、 By theme

    • Each is equipped with an integrated FCM SDK The client of , Can generate unique register_token, This register_token Will be App The client gives App Server side . The server gets this register_token, You can just push messages to this device .

    • Each device can also subscribe to topics , After subscribing to a topic , You can push messages directly to this topic . In this way, all devices that have subscribed to this topic can receive push messages .

FCM Integrated into the server (Python)

  • at present ,FCM Admin SDK Support five server programming languages :Node.js、Java、Python、Go、C#

  • Prerequisite :

    • Make sure you own the application server .
    • Make sure your server is running Admin Python SDK — Python 3.6+
  • Set up Firebase Project and service account number

    • If you want to use Firebase Admin SDK, You need to have the following :
    • Firebase project
    • Used with Firebase Service account for communication
    • Configuration file containing service account credentials
  • establish Firebase project

# Firebase Console :https://console.firebase.google.com

#  Create a process 
1.  stay  Firebase  Console , Click Add Item 
2.  If appear  Firebase  Term tips , Please review and accept .
3.  Click to continue .
4.  Set up... For your project  Google Analytics( Optional )
5.  Click create project ( If you use the existing  Google Cloud  project , Click Add  Firebase)
 Copy code 
  • Create a profile containing service account credentials
1.  stay  Firebase  Console , Open Settings  >  Service account number .
2.  Click generate new private key , Then click generate key to confirm .
3.  Store the key properly  JSON  file .
 Copy code 
  • add to SDK

Firebase Admin Python SDK It can be done by pip get .

pip3 install firebase-admin
 Copy code 
  • initialization SDK

When authorizing through the service account , There are two ways to provide credentials for your application .

The way 1( recommend )

(1) Put the environment variable GOOGLE_APPLICATION_CREDENTIALS Set to include the service account key JSON The file path of the file

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
 Copy code 

(2) After completing the above steps , Apply default credentials (ADC) Ability to implicitly determine your credentials

import firebase_admin


default_app = firebase_admin.initialize_app()
 Copy code 

The way 2: Write dead directly in the code JSON File path


import firebase_admin
from firebase_admin import credentials


cred = credentials.Certificate("path/to/service_account.json")
default_app = firebase_admin.initialize_app(credential=cred)
 Copy code 
  • Send a message to the specified device
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)
 Copy code 
  • Send a message to the subject

After creating a theme , Use the server API Send a message to the subject , Devices that have subscribed to this topic will receive messages .

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)

 Copy code 
  • Send messages in bulk
# 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))

 Copy code 
  • The server subscribes to the topic

client SDK You can help users subscribe to topics , The server can help users subscribe to topics through the interface .

You can subscribe to any existing topic for the client application instance , You can also create new themes . When you use API Subscribe to new topics for client applications ( Your Firebase Topics that do not yet exist in the project ) when , The system will be in FCM Create a new theme with that name in , Any client can then subscribe to the topic .

#  You can pass the registration token list to  Firebase Admin SDK  Subscription method , To subscribe to the topic for the corresponding device 

# 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')
 Copy code 

Be careful : In a single request , You can at most 1000 Devices subscribe to or unsubscribe from topics .

  • The server pushes the theme

utilize Admin FCM API, You can also pass the registration token to the corresponding method , To unsubscribe the theme for the device

# 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')
 Copy code 

summary

  • Use Firebase Message push can be realized quickly , Cross-platform support , And use it for free .
  • By means of Firebase Admin SDK Realize message promotion and topic management , You can also follow FCM Server protocol Implement the interface yourself .
  • Firebase Admin SDK advantage : Easy to use , There is everything .
  • Firebase Admin SDK shortcoming : The bag is too big to be light ( The push function only uses FCM), I won't support it asyncio Asynchronous operations .

Conclusion

The article begins with the official account of WeChat Cheng Xuyuan Village , Synchronize on Nuggets .

It's not easy to code words , Reprint please explain the source , Let's go after passing by with our lovely little fingers (╹▽╹)

copyright notice
author[Cheng Xuyuan Xiaozhuang],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011247063163.html

Random recommended