Skip to content

Instantly share code, notes, and snippets.

@nyergler
Created October 30, 2018 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyergler/f6304e01969117ac6282f92dd64c3671 to your computer and use it in GitHub Desktop.
Save nyergler/f6304e01969117ac6282f92dd64c3671 to your computer and use it in GitHub Desktop.
Multithreading with Lob's Python client & Python 3
import concurrent.futures
import urllib.request
import lob
lob.api_key = 'XXX'
MAX_CONCURRENCY = 5
FROM_ADDRESS = {
'name': 'Larry Lobster',
'address_line1': '185 Berry St #6100',
'address_city': 'San Francisco',
'address_state': 'CA',
'address_zip': '94107',
'address_country': 'US',
}
TEMPLATE = """
<html>
<body>
<h1>Hello, {{name}}!</h1>
</body>
</html>
"""
RECIPIENTS = [
{
'name': 'Joe Smith',
'address_line1': '185 Berry St #6100',
'address_city': 'San Francisco',
'address_state': 'CA',
'address_zip': '94107',
'address_country': 'US',
},
{
'name': 'Harry Zhang',
'address_line1': '185 Berry St #6100',
'address_city': 'San Francisco',
'address_state': 'CA',
'address_zip': '94107',
'address_country': 'US',
},
{
'name': 'Leore',
'address_line1': '185 Berry St #6100',
'address_city': 'San Francisco',
'address_state': 'CA',
'address_zip': '94107',
'address_country': 'US',
},
{
'name': 'Betty',
'address_line1': '185 Berry St #6100',
'address_city': 'San Francisco',
'address_state': 'CA',
'address_zip': '94107',
'address_country': 'US',
},
]
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_CONCURRENCY) as executor:
# Start the create operations in the same order that they are listed,
# mapping the future object (which we'll get back from the executor)
# to its original index so we can look up the original data
futures_to_indices = {
executor.submit(lob.Letter.create,
description='Letter to %s' % (recipient['name']),
to_address=recipient,
from_address=FROM_ADDRESS,
file=TEMPLATE,
merge_variables=recipient,
color=False,
): i
for i, recipient in enumerate(RECIPIENTS)
}
for future in concurrent.futures.as_completed(futures_to_indices):
index = futures_to_indices[future]
try:
data = future.result()
except Exception as exc:
print('Recipient %r (%r) generated an exception: %s' % (index, RECIPIENTS[index], exc))
else:
print('Letter %r queued for %r' % (data.id, RECIPIENTS[index]['name']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment