通过python向许多用户发送推送通知

时间:2020-03-19 10:05:13

标签: python firebase push-notification firebase-cloud-messaging

对于我的项目,使用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)

2 个答案:

答案 0 :(得分:3)

当然,您可以使用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])

答案 1 :(得分:1)

如果要将同一消息发送给所有令牌,则可以将单个API调用与multicast message一起使用。 Github仓库在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]