or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcore-messaging.mderror-handling.mdindex.md

async-operations.mddocs/

0

# Asynchronous Operations

1

2

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.

3

4

## Capabilities

5

6

### Batch Messaging

7

8

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

9

10

```python { .api }

11

def async_notify_multiple_devices(

12

self,

13

params_list: Optional[list] = None,

14

timeout: int = 5

15

) -> list:

16

"""

17

Send push notifications to multiple devices with personalized templates.

18

19

Parameters:

20

- params_list (list, optional): List of parameter dictionaries, each containing

21

the same parameters as notify() method for individual messages

22

- timeout (int, optional): Request timeout in seconds (default: 5)

23

24

Returns:

25

list: List of response dictionaries, one for each message sent

26

27

Notes:

28

- Each params_list item should be a dict with notify() parameters

29

- Executes requests concurrently using asyncio and aiohttp

30

- Returns results in same order as input parameters

31

"""

32

```

33

34

### Async Implementation Functions

35

36

Internal asynchronous functions that power the batch messaging functionality.

37

38

```python { .api }

39

async def fetch_tasks(

40

end_point: str,

41

headers: dict,

42

payloads: list,

43

timeout: int

44

) -> list:

45

"""

46

Execute multiple FCM requests concurrently.

47

48

Parameters:

49

- end_point (str): FCM API endpoint URL

50

- headers (dict): HTTP request headers with authorization

51

- payloads (list): List of JSON message payloads (bytes)

52

- timeout (int): Request timeout in seconds

53

54

Returns:

55

list: List of response results from all requests

56

"""

57

58

async def send_request(

59

end_point: str,

60

headers: dict,

61

payload: bytes,

62

timeout: int = 5

63

) -> dict:

64

"""

65

Send single asynchronous FCM request.

66

67

Parameters:

68

- end_point (str): FCM API endpoint URL

69

- headers (dict): HTTP request headers

70

- payload (bytes): JSON message payload

71

- timeout (int, optional): Request timeout (default: 5)

72

73

Returns:

74

dict: Parsed JSON response from FCM server

75

"""

76

```

77

78

## Usage Examples

79

80

### Basic Batch Messaging

81

82

```python

83

from pyfcm import FCMNotification

84

85

fcm = FCMNotification(

86

service_account_file="service-account.json",

87

project_id="your-project-id"

88

)

89

90

# Prepare parameters for multiple personalized messages

91

params_list = [

92

{

93

"fcm_token": "device_token_1",

94

"notification_title": "Hello John",

95

"notification_body": "You have 3 new messages",

96

"data_payload": {"user_id": "123", "message_count": "3"}

97

},

98

{

99

"fcm_token": "device_token_2",

100

"notification_title": "Hello Sarah",

101

"notification_body": "Your order has shipped",

102

"data_payload": {"user_id": "456", "order_id": "789"}

103

},

104

{

105

"fcm_token": "device_token_3",

106

"notification_title": "Hello Mike",

107

"notification_body": "Meeting reminder in 30 minutes",

108

"data_payload": {"user_id": "789", "meeting_id": "abc123"}

109

}

110

]

111

112

# Send all messages concurrently

113

responses = fcm.async_notify_multiple_devices(

114

params_list=params_list,

115

timeout=10

116

)

117

118

# Process responses

119

for i, response in enumerate(responses):

120

print(f"Message {i+1} result: {response}")

121

```

122

123

### Platform-Specific Batch Messages

124

125

```python

126

# Batch messages with different platform configurations

127

android_config = {

128

"notification": {"color": "#ff0000"},

129

"data": {"click_action": "FLUTTER_NOTIFICATION_CLICK"}

130

}

131

132

ios_config = {

133

"headers": {"apns-priority": "10"},

134

"payload": {"aps": {"badge": 1}}

135

}

136

137

params_list = [

138

{

139

"fcm_token": "android_token",

140

"notification_title": "Android Message",

141

"android_config": android_config

142

},

143

{

144

"fcm_token": "ios_token",

145

"notification_title": "iOS Message",

146

"apns_config": ios_config

147

}

148

]

149

150

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

151

```

152

153

### Error Handling in Batch Operations

154

155

```python

156

from pyfcm.errors import FCMServerError, InvalidDataError

157

158

try:

159

responses = fcm.async_notify_multiple_devices(params_list)

160

161

# Check individual response success

162

for i, response in enumerate(responses):

163

if 'error' in response:

164

print(f"Message {i+1} failed: {response['error']}")

165

else:

166

print(f"Message {i+1} sent successfully: {response['name']}")

167

168

except FCMServerError as e:

169

print(f"FCM service error: {e}")

170

except InvalidDataError as e:

171

print(f"Invalid data in batch: {e}")

172

```

173

174

## Performance Considerations

175

176

### Timeout Management

177

178

- Default timeout is 5 seconds for async operations (vs 120 for sync)

179

- Consider network latency when setting timeout for large batches

180

- Failed requests due to timeout will be included in response list

181

182

### Batch Size Recommendations

183

184

- Optimal batch size depends on network conditions and server capacity

185

- Consider breaking very large batches (>1000 messages) into smaller chunks

186

- Monitor response times and adjust batch sizes accordingly

187

188

### Resource Management

189

190

```python

191

# For high-volume applications, consider connection pooling

192

import asyncio

193

194

async def send_large_batch(fcm, all_params, batch_size=100):

195

"""Send large batches in chunks to manage resources"""

196

results = []

197

198

for i in range(0, len(all_params), batch_size):

199

batch = all_params[i:i + batch_size]

200

batch_results = fcm.async_notify_multiple_devices(batch)

201

results.extend(batch_results)

202

203

# Optional: Add delay between batches

204

await asyncio.sleep(0.1)

205

206

return results

207

```

208

209

## Types

210

211

```python { .api }

212

from typing import Optional

213

214

# Parameter list for batch operations

215

ParamsList = list[dict] # List of notify() parameter dictionaries

216

217

# Async function return types

218

ResponseList = list[dict] # List of response dictionaries from FCM

219

```