mailchimp_id.py 1.59 KB
Newer Older
1 2 3 4
"""
mailchimp_id: Returns whether or not a given mailchimp key represents
a valid list.
"""
5 6 7 8 9 10 11 12 13
import sys
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

from mailsnake import MailSnake


class Command(BaseCommand):
14 15 16 17
    """
    Given a mailchimp key, validates that a list with that key
    exists in mailchimp.
    """
18 19 20 21 22 23 24 25 26 27
    args = '<mailchimp_key web_id>'
    help = 'Get the list id from a web_id'

    option_list = BaseCommand.option_list + (
        make_option('--key', action='store', help='mailchimp api key'),
        make_option('--webid', action='store', dest='web_id', type=int,
                    help='mailchimp list web id'),
    )

    def parse_options(self, options):
28
        """Parses `options` of the command."""
29 30 31 32 33 34 35 36 37
        if not options['key']:
            raise CommandError('missing key')

        if not options['web_id']:
            raise CommandError('missing list web id')

        return options['key'], options['web_id']

    def handle(self, *args, **options):
38 39 40
        """
        Validates that the id passed in exists in mailchimp.
        """
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
        key, web_id = self.parse_options(options)

        mailchimp = MailSnake(key)

        lists = mailchimp.lists()['data']
        by_web_id = {l['web_id']: l for l in lists}

        list_with_id = by_web_id.get(web_id, None)

        if list_with_id:
            print "id: {} for web_id: {}".format(list_with_id['id'], web_id)
            print "list name: {}".format(list_with_id['name'])
        else:
            print "list with web_id: {} not found.".format(web_id)
            sys.exit(1)