Python django.conf.settings.MAILCHIMP_API_KEY Examples

The following are 8 code examples of django.conf.settings.MAILCHIMP_API_KEY(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: queue_processors.py    From zulip with Apache License 2.0 6 votes vote down vote up
def consume(self, data: Dict[str, Any]) -> None:
        # TODO: This is the only implementation with Dict cf Mapping; should we simplify?
        user_profile = get_user_profile_by_id(data['user_id'])
        logging.info(
            "Processing signup for user %s in realm %s",
            user_profile.id, user_profile.realm.string_id,
        )
        if settings.MAILCHIMP_API_KEY and settings.PRODUCTION:
            endpoint = "https://{}.api.mailchimp.com/3.0/lists/{}/members".format(
                settings.MAILCHIMP_API_KEY.split('-')[1], settings.ZULIP_FRIENDS_LIST_ID,
            )
            params = dict(data)
            del params['user_id']
            params['list_id'] = settings.ZULIP_FRIENDS_LIST_ID
            params['status'] = 'subscribed'
            r = requests.post(endpoint, auth=('apikey', settings.MAILCHIMP_API_KEY), json=params, timeout=10)
            if r.status_code == 400 and ujson.loads(r.text)['title'] == 'Member Exists':
                logging.warning("Attempted to sign up already existing email to list: %s",
                                data['email_address'])
            elif r.status_code == 400:
                retry_event(self.queue_name, data, lambda e: r.raise_for_status())
            else:
                r.raise_for_status() 
Example #2
Source File: add_users_to_mailing_list.py    From zulip with Apache License 2.0 5 votes vote down vote up
def handle(self, *args: Any, **options: Optional[str]) -> None:
        api_key = options['api_key']
        if api_key is None:
            try:
                if settings.MAILCHIMP_API_KEY is None:
                    raise CommandError('MAILCHIMP_API_KEY is None. Check your server settings file.')
                api_key = settings.MAILCHIMP_API_KEY
            except AttributeError:
                raise CommandError('Please supply a MailChimp API key to --api-key, or add a '
                                   'MAILCHIMP_API_KEY to your server settings file.')

        if options['list_id'] is None:
            try:
                if settings.ZULIP_FRIENDS_LIST_ID is None:
                    raise CommandError('ZULIP_FRIENDS_LIST_ID is None. Check your server settings file.')
                options['list_id'] = settings.ZULIP_FRIENDS_LIST_ID
            except AttributeError:
                raise CommandError('Please supply a MailChimp List ID to --list-id, or add a '
                                   'ZULIP_FRIENDS_LIST_ID to your server settings file.')

        endpoint = "https://{}.api.mailchimp.com/3.0/lists/{}/members".format(
            api_key.split('-')[1], options['list_id'],
        )

        for user in UserProfile.objects.filter(is_bot=False, is_active=True) \
                                       .values('email', 'full_name', 'realm_id'):
            data = {
                'email_address': user['email'],
                'list_id': options['list_id'],
                'status': 'subscribed',
                'merge_fields': {
                    'NAME': user['full_name'],
                    'REALM_ID': user['realm_id'],
                    'OPTIN_TIME': options['optin_time'],
                },
            }
            r = requests.post(endpoint, auth=('apikey', api_key), json=data, timeout=10)
            if r.status_code == 400 and ujson.loads(r.text)['title'] == 'Member Exists':
                print("{} is already a part of the list.".format(data['email_address']))
            elif r.status_code >= 400:
                print(r.text) 
Example #3
Source File: mailchimp_api.py    From approval_frame with GNU General Public License v3.0 5 votes vote down vote up
def get_mailchimp_api():
    if hasattr(settings, 'MAILCHIMP_API_KEY'):
        key = settings.MAILCHIMP_API_KEY
    else:
        key = '00000000000000000000000000000000-us1'
    return mailchimp.Mailchimp(key) 
Example #4
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def form_valid(self, form):
        mailchimp_enabled = settings.MAILCHIMP_API_KEY and settings.MAILCHIMP_LIST_ID

        dummy_key = 'a' * 32

        client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY or dummy_key, timeout=5.0, enabled=mailchimp_enabled)

        data = form.cleaned_data.copy()
        email = data.pop('email')
        data = {
            k.upper(): v
            for k, v in data.items()
        }
        try:
            client.lists.members.create(settings.MAILCHIMP_LIST_ID, {
                'email_address': email,
                'status': 'pending',
                'merge_fields': data,
            })
        except Exception as e:
            self.warning(e)
        else:
            if mailchimp_enabled:
                self.success()
            else:
                self.warning(Exception(
                    'Incorrect Mailchimp configuration: API_KEY: {}, LIST_ID: {}'.format(
                        str(settings.MAILCHIMP_API_KEY),
                        str(settings.MAILCHIMP_LIST_ID),
                    )
                ))

        return super().form_valid(form) 
Example #5
Source File: context_processors.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def global_vars(request):
    return {
        'APPLY_SITE': ApplyHomePage.objects.first().get_site(),
        'PUBLIC_SITE': HomePage.objects.first().get_site(),
        'newsletter_form': NewsletterForm(),
        'newsletter_enabled': settings.MAILCHIMP_API_KEY and settings.MAILCHIMP_LIST_ID,
        'ORG_LONG_NAME': settings.ORG_LONG_NAME,
        'ORG_SHORT_NAME': settings.ORG_SHORT_NAME,
        'ORG_EMAIL': settings.ORG_EMAIL,
    } 
Example #6
Source File: mailchimp.py    From education-backend with MIT License 5 votes vote down vote up
def _get_base_url(self):
        dc = settings.MAILCHIMP_API_KEY.split('-')[-1]

        return f'https://{dc}.api.mailchimp.com/3.0/' 
Example #7
Source File: mailchimp.py    From education-backend with MIT License 5 votes vote down vote up
def _post(self, url: str, payload: dict):
        response = requests.post(
            url=self.format_url(url),
            auth=HTTPBasicAuth('user', settings.MAILCHIMP_API_KEY),
            json=payload,
        )
        if response.status_code != 200:
            raise AppMailchimpWrongResponseException(f'Wrong response from mailchimp: {response.status_code}. Response = {response.json()}')

        return response 
Example #8
Source File: signals.py    From open-humans with MIT License 4 votes vote down vote up
def member_pre_save_cb(sender, instance, raw, **kwargs):
    """
    Subscribe or unsubscribe a user from Mailchimp.
    """
    if raw or settings.TESTING:
        return

    try:
        member = sender.objects.get(pk=instance.pk)
    except sender.DoesNotExist:
        pass
    else:
        if member.newsletter == instance.newsletter:
            return

    if not settings.MAILCHIMP_API_KEY:
        logger.warn(
            "User changed email preference but no Mailchimp API key "
            "has been specified, set MAILCHIMP_API_KEY."
        )

        return

    mc = mailchimp.Mailchimp(settings.MAILCHIMP_API_KEY)

    try:
        address = instance.primary_email.email
    except AttributeError:
        # We're not sure why the callback is firing an extra time, before
        # SignupView.create_account runs (when email not yet saved).
        return

    if instance.newsletter:
        try:
            mc.lists.subscribe(
                settings.MAILCHIMP_NEWSLETTER_LIST,
                {"email": address},
                double_optin=False,
                update_existing=True,
            )
        except mailchimp.ListAlreadySubscribedError:
            logger.info('"%s" was already subscribed', address)
        except (mailchimp.Error, ValueError) as e:
            logger.error("A Mailchimp error occurred: %s, %s", e.__class__, e)
    else:
        try:
            mc.lists.unsubscribe(
                settings.MAILCHIMP_NEWSLETTER_LIST,
                {"email": address},
                send_goodbye=False,
                send_notify=False,
            )
        except (mailchimp.ListNotSubscribedError, mailchimp.EmailNotExistsError):
            logger.info('"%s" was already unsubscribed', address)
        except (mailchimp.Error, ValueError) as e:
            logger.error("A Mailchimp error occurred: %s, %s", e.__class__, e)