Created
July 25, 2017 22:41
-
-
Save knorwood/b185596cc356d8ba5f1512e02550caf8 to your computer and use it in GitHub Desktop.
Sending events to Amplitude concurrently (Example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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