CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyfcm

Python client for FCM - Firebase Cloud Messaging (Android, iOS and Web)

Pending
Overview
Eval results
Files

async-operations.mddocs/

Asynchronous Operations

PyFCM provides asynchronous capabilities for batch messaging operations, enabling efficient delivery of notifications to multiple devices concurrently. The async functionality uses asyncio and aiohttp for improved performance in high-throughput scenarios.

Capabilities

Batch Messaging

Send personalized notifications to multiple devices simultaneously using asynchronous HTTP requests for improved performance and throughput.

def async_notify_multiple_devices(
    self,
    params_list: Optional[list] = None,
    timeout: int = 5
) -> list:
    """
    Send push notifications to multiple devices with personalized templates.
    
    Parameters:
    - params_list (list, optional): List of parameter dictionaries, each containing
      the same parameters as notify() method for individual messages
    - timeout (int, optional): Request timeout in seconds (default: 5)
    
    Returns:
    list: List of response dictionaries, one for each message sent
    
    Notes:
    - Each params_list item should be a dict with notify() parameters
    - Executes requests concurrently using asyncio and aiohttp
    - Returns results in same order as input parameters
    """

Async Implementation Functions

Internal asynchronous functions that power the batch messaging functionality.

async def fetch_tasks(
    end_point: str,
    headers: dict,
    payloads: list,
    timeout: int
) -> list:
    """
    Execute multiple FCM requests concurrently.
    
    Parameters:
    - end_point (str): FCM API endpoint URL
    - headers (dict): HTTP request headers with authorization
    - payloads (list): List of JSON message payloads (bytes)
    - timeout (int): Request timeout in seconds
    
    Returns:
    list: List of response results from all requests
    """

async def send_request(
    end_point: str,
    headers: dict,
    payload: bytes,
    timeout: int = 5
) -> dict:
    """
    Send single asynchronous FCM request.
    
    Parameters:
    - end_point (str): FCM API endpoint URL
    - headers (dict): HTTP request headers
    - payload (bytes): JSON message payload  
    - timeout (int, optional): Request timeout (default: 5)
    
    Returns:
    dict: Parsed JSON response from FCM server
    """

Usage Examples

Basic Batch Messaging

from pyfcm import FCMNotification

fcm = FCMNotification(
    service_account_file="service-account.json",
    project_id="your-project-id"
)

# Prepare parameters for multiple personalized messages
params_list = [
    {
        "fcm_token": "device_token_1",
        "notification_title": "Hello John",
        "notification_body": "You have 3 new messages",
        "data_payload": {"user_id": "123", "message_count": "3"}
    },
    {
        "fcm_token": "device_token_2", 
        "notification_title": "Hello Sarah",
        "notification_body": "Your order has shipped",
        "data_payload": {"user_id": "456", "order_id": "789"}
    },
    {
        "fcm_token": "device_token_3",
        "notification_title": "Hello Mike",
        "notification_body": "Meeting reminder in 30 minutes",
        "data_payload": {"user_id": "789", "meeting_id": "abc123"}
    }
]

# Send all messages concurrently
responses = fcm.async_notify_multiple_devices(
    params_list=params_list,
    timeout=10
)

# Process responses
for i, response in enumerate(responses):
    print(f"Message {i+1} result: {response}")

Platform-Specific Batch Messages

# Batch messages with different platform configurations
android_config = {
    "notification": {"color": "#ff0000"},
    "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK"}
}

ios_config = {
    "headers": {"apns-priority": "10"},
    "payload": {"aps": {"badge": 1}}
}

params_list = [
    {
        "fcm_token": "android_token",
        "notification_title": "Android Message",
        "android_config": android_config
    },
    {
        "fcm_token": "ios_token", 
        "notification_title": "iOS Message",
        "apns_config": ios_config
    }
]

responses = fcm.async_notify_multiple_devices(params_list, timeout=15)

Error Handling in Batch Operations

from pyfcm.errors import FCMServerError, InvalidDataError

try:
    responses = fcm.async_notify_multiple_devices(params_list)
    
    # Check individual response success
    for i, response in enumerate(responses):
        if 'error' in response:
            print(f"Message {i+1} failed: {response['error']}")
        else:
            print(f"Message {i+1} sent successfully: {response['name']}")
            
except FCMServerError as e:
    print(f"FCM service error: {e}")
except InvalidDataError as e:
    print(f"Invalid data in batch: {e}")

Performance Considerations

Timeout Management

  • Default timeout is 5 seconds for async operations (vs 120 for sync)
  • Consider network latency when setting timeout for large batches
  • Failed requests due to timeout will be included in response list

Batch Size Recommendations

  • Optimal batch size depends on network conditions and server capacity
  • Consider breaking very large batches (>1000 messages) into smaller chunks
  • Monitor response times and adjust batch sizes accordingly

Resource Management

# For high-volume applications, consider connection pooling
import asyncio

async def send_large_batch(fcm, all_params, batch_size=100):
    """Send large batches in chunks to manage resources"""
    results = []
    
    for i in range(0, len(all_params), batch_size):
        batch = all_params[i:i + batch_size]
        batch_results = fcm.async_notify_multiple_devices(batch)
        results.extend(batch_results)
        
        # Optional: Add delay between batches
        await asyncio.sleep(0.1)
    
    return results

Types

from typing import Optional

# Parameter list for batch operations
ParamsList = list[dict]  # List of notify() parameter dictionaries

# Async function return types
ResponseList = list[dict]  # List of response dictionaries from FCM

Install with Tessl CLI

npx tessl i tessl/pypi-pyfcm

docs

async-operations.md

core-messaging.md

error-handling.md

index.md

tile.json