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 .
-
-
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
The sidebar is recommended
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values(python)
- leetcode 1433. Check If a String Can Break Another String(python)
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
guess what you like
-
Python crawler series - network requests
-
Python thread 01 understanding thread
-
Analysis of earthquake distribution in the past 10 years with Python~
-
You need to master these before learning Python crawlers
-
After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
-
Python uses redis
-
Python crawler - ETF fund acquisition
-
Detailed tutorial on Python operation Tencent object storage (COS)
-
[Python] comparison of list, tuple, array and bidirectional queue methods
-
Go Python 3 usage and pit Prevention Guide
Random recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
- Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
- Python -- datetime (timedelta class)
- Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
- [Python] comparison of dictionary dict, defaultdict and orderdict
- Test driven development using Django
- Face recognition practice: face recognition using Python opencv and deep learning
- leetcode 1610. Maximum Number of Visible Points(python)
- Python thread 03 thread synchronization
- Introduction and internal principles of Python's widely used concurrent processing Library Futures
- Python - progress bar artifact tqdm usage
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)