【问题标题】:Send push notification to many users via python通过 python 向许多用户发送推送通知
【发布时间】:2020-03-19 10:05:13
【问题描述】:
对于我使用 Firebase 消息发送推送通知的项目。我将用户的 firebase 令牌存储在数据库中。使用它们,我向每个用户发送了推送。 100 个用户的总发送时间约为 100 秒。有没有办法异步发送推送(我的意思是一次发送多个推送通知)
# Code works synchronously
for user in users:
message = messaging.Message(
notification=messaging.Notification(
title="Push title",
body="Push body"
),
token = user['fcmToken']
)
response = messaging.send(message)
【问题讨论】:
标签:
python
firebase
push-notification
firebase-cloud-messaging
【解决方案1】:
当然,您可以使用其中一个 python 并发库。这是一种选择:
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
def send_message(user):
message = messaging.Message(
notification=messaging.Notification(
title="Push title",
body="Push body"),
token = user['fcmToken'])
return messaging.send(message)
with ThreadPoolExecutor(max_workers=10) as executor: # may want to try more workers
future_list = []
for u in users:
future_list.append(executor.submit(send_message, u))
wait(future_list, return_when=ALL_COMPLETED)
# note: we must use the returned self to get the test count
print([future.result() for future in future_list])
【解决方案2】:
如果您想向所有令牌发送相同的消息,您可以使用带有 multicast message 的单个 API 调用。 Github repo 在 Python 中有这个sample of sending a multicast message:
def send_multicast():
# [START send_multicast]
# Create a list containing up to 500 registration tokens.
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_N',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
tokens=registration_tokens,
)
response = messaging.send_multicast(message)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))
# [END send_multicast]