Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple script to sync templates across two mandrill accounts.
import optparse
from mandrill import Mandrill
from mandrill import UnknownTemplateError
def sync_templates(source_key, destination_key, update_existing=True, dry_run=False):
def perform_action(action):
'''Simple wrapper to skip actaully doing anything if dry run is enabled.
'''
if not dry_run:
action()
else:
print 'dry-run, action not performed'
# Initialize Mandrill sdk
source = Mandrill(source_key)
destination = Mandrill(destination_key)
for template in source.templates.list():
# Get rid of attributes that mandrill computes.
non_required_args = ('publish_name', 'publish_from_name', 'created_at',
'updated_at', 'publish_code', 'published_at',
'publish_subject', 'publish_from_email',
'draft_updated_at', 'slug', 'publish_text')
[template.pop(arg, None) for arg in non_required_args]
try:
# Check if the template is present on the destination.
destination.templates.info(name=template['name'])
except UnknownTemplateError:
# Destination does not have the template, create it.
print "Template %s does not exists, creating." % template['name']
perform_action(lambda: destination.templates.add(**template))
else:
# Looks like the template is present, check if we should update or
# not.
if update_existing:
print "Template %s exists, updating." % template['name']
perform_action(lambda: destination.templates.update(**template))
else:
print "Template %s exists, skipping." % template['name']
if __name__=='__main__':
usage = "usage: %prog [options] source-key destination-key"
parser = optparse.OptionParser(usage=usage)
parser.add_option("-s", "--skip-existing", default=True,
action="store_false", dest="update_existing",
help="Don't update template if it exists in the destination account.")
parser.add_option("-d", "--dry-run", default=False,
action="store_true", dest="dry_run",
help="Don't actually migrate, simulate what would happen.")
(options, args) = parser.parse_args()
if len(args) != 2:
parser.error("incorrect number of arguments")
sync_templates(
args[0],
args[1],
update_existing=options.update_existing,
dry_run=options.dry_run
)
mandrill>=1.0.57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.