Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save knorwood/b185596cc356d8ba5f1512e02550caf8 to your computer and use it in GitHub Desktop.
Save knorwood/b185596cc356d8ba5f1512e02550caf8 to your computer and use it in GitHub Desktop.
Sending events to Amplitude concurrently (Example)
from concurrent.futures import ThreadPoolExecutor
import json
import logging
import requests
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.INFO)
def send_event_batch(api_key, event_batch):
logging.info("Started sending a request")
r = requests.post(
'https://api.amplitude.com/httpapi',
data={
'api_key': api_key,
'event': json.dumps(event_batch)
},
)
logging.info("Finished sending a request")
return r
def send_events_to_amplitude(executor, api_key, events_batches):
futures = []
for event_batch in events_batches:
futures.append(executor.submit(send_event_batch, api_key, event_batch))
for f in futures:
response = f.result()
logging.info('%s %s', response.status_code, response.content)
if __name__ == '__main__':
# Increase number of workers for more parallelism
e = ThreadPoolExecutor(max_workers=10)
api_key = 'YOU_API_KEY'
event_batches = [
[
{"user_id": "Alice", "event_type": "test_event"},
],
[
{"user_id": "Bob", "event_type": "test_event"},
],
[
{"user_id": "Chuck", "event_type": "test_event"},
],
[
{"user_id": "Dorothy", "event_type": "test_event"},
],
]
send_events_to_amplitude(e, api_key, event_batches)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment