本文整理匯總了Python中mailchimp.Mailchimp方法的典型用法代碼示例。如果您正苦於以下問題:Python mailchimp.Mailchimp方法的具體用法?Python mailchimp.Mailchimp怎麽用?Python mailchimp.Mailchimp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mailchimp
的用法示例。
在下文中一共展示了mailchimp.Mailchimp方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add_subscriber
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def add_subscriber(email):
if (MailingListService.mailchimp_api == 'ADD_YOUR_API_KEY' or
MailingListService.mailchimp_list_id == 'ADD_YOUR_LIST_ID'):
print("WARNING: CANNOT USE MAILCHIMP API. KEYS NOT SET")
print("Set your API keys in development.ini")
return False
api = mailchimp.Mailchimp(apikey=MailingListService.mailchimp_api)
if not email or not email.strip():
return False
try:
api.lists.subscribe(
MailingListService.mailchimp_list_id,
{'email': email.strip().lower()},
double_optin=False,
update_existing=True,
replace_interests=False)
return True
except Exception as x:
print("Error during mailing list signup: {}".format(x))
return False
示例2: add_subscriber
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def add_subscriber(email):
if not MailingListService.get_is_initialized():
MailingListService.__log.warn("CANNOT USE MAILCHIMP API. KEYS NOT SET")
MailingListService.__log.warn("Set your API keys in development.ini / production.ini")
return False
api = mailchimp.Mailchimp(apikey=MailingListService.mailchimp_api)
if not email or not email.strip():
return False
try:
api.lists.subscribe(
MailingListService.mailchimp_list_id,
{'email': email.strip().lower()},
double_optin=False,
update_existing=True,
replace_interests=False)
MailingListService.__log.notice("Successfully added {} to the mailchimp list.".format(email))
return True
except Exception as x:
MailingListService.__log.error("Error during mailing list signup: {}".format(x))
return False
開發者ID:mikeckennedy,項目名稱:cookiecutter-pyramid-talk-python-starter,代碼行數:25,代碼來源:mailinglist_service.py
示例3: get_mailchimp_api
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def get_mailchimp_api():
if hasattr(settings, 'MAILCHIMP_API_KEY'):
key = settings.MAILCHIMP_API_KEY
else:
key = '00000000000000000000000000000000-us1'
return mailchimp.Mailchimp(key)
示例4: add_subscriber
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def add_subscriber(email):
if not MailingListService.get_is_initialized():
MailingListService.__log.warn("CANNOT USE MAILCHIMP API. KEYS NOT SET")
MailingListService.__log.warn("Set your API keys in development.ini / production.ini")
return False
# noinspection PyBroadException
try:
api = mailchimp.Mailchimp(apikey=MailingListService.mailchimp_api)
except IndexError:
MailingListService.__log.warn("Cannot initialize mailchimp, bad key?")
return False
except:
MailingListService.__log.warn("Unexpected error initializing mailchimp via API key?")
return False
if not email or not email.strip():
return False
try:
api.lists.subscribe(
MailingListService.mailchimp_list_id,
{'email': email.strip().lower()},
double_optin=False,
update_existing=True,
replace_interests=False)
MailingListService.__log.notice("Successfully added {} to the mailchimp list.".format(email))
return True
except Exception as x:
MailingListService.__log.error("Error during mailing list signup: {}".format(x))
return False
示例5: main
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def main(api_key, list_id, group=None, interests=None, just_interests=False):
"""
Get dictionary of subscribers from based on query parameters
:param api_key: Mailchimp API key
:param list_id: Mailchimp list ID to query
:param group: Name of Mailchimp group to query (if None all list
subscribers are returned as a dictionary)
:param interests: List of interests under given group to query (if None
subscribers are returned as a dictionary)
:param just_interests: Boolean to include only list of interests that users
are actually interested in
:returns: Dictionary of subscriber data
"""
subscribers = get_subscribers(api_key, list_id)
if not subscribers:
return {}
if group is None:
if just_interests:
return filter_interests(subscribers)
else:
return subscribers
return query_subscribers(subscribers, group, interests)
示例6: query_subscribers
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def query_subscribers(subscribers, group, interests=None):
"""
Iterator through subscribers based on query parameters
:param subscribers: Dictionary of subscribers to query (as returned from
Mailchimp API)
:param group: Name of Mailchimp group to query (if None all list
subscribers are returned as a dictionary)
:param interests: List of interests under given group to query (if None
subscribers are returned as a dictionary)
:returns: Iterator through dictionary of subscriber data
"""
for subscriber in subscribers:
subscribers_subset = collections.defaultdict(list)
for g in subscriber['merges']['GROUPINGS']:
if g['name'] != group:
continue
email = subscriber['merges']['EMAIL']
if interests is None:
# Grab all interests for group
for interest in g['groups']:
if interest['interested']:
subscribers_subset[email].append(interest['name'])
continue
for interest in g['groups']:
if interest['name'] in interests and interest['interested']:
subscribers_subset[email].append(interest['name'])
break
if subscribers_subset:
yield subscribers_subset
示例7: get_subscribers
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def get_subscribers(api_key, list_id):
"""
Generator through subscribers dicts as paginated from Mailchimp API
:param api_key: Mailchimp API key
:param list_id: Mailchimp list ID to query
:returns: Iterator of Dict of subscribers from Mailchimp
/lists/{list_id}/members/ API
"""
mc = mailchimp.Mailchimp(api_key)
page = 0
total_read = 0
total_available = None
# This is the max mailchimp will let us pull with a single request
opts = {'limit': 100, 'start': page}
while True:
subs = mc.lists.members(list_id, opts=opts)
if total_available is None:
total_available = subs['total']
if not subs['data']:
raise StopIteration
for sub in subs['data']:
yield sub
total_read += len(subs)
if total_read >= total_available:
raise StopIteration
opts['start'] += 1
示例8: _parse_args
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def _parse_args():
desc = textwrap.dedent("""
Script to print out CSV listing of mailchimp subscribers. The output format
when using --just-interests (default) is suitable for redirecting to a file
for importing to Mailchimp. For example:
python mailchimp_subscribers.py -k <key> -l <list_id> > subscribers.csv
python mailchimp_subscribers.py -k <key> -l <list_id> -g favorite-languages -i "ruby,rails" > rails_subs.csv
""")
parser = argparse.ArgumentParser(
prog=__file__,
description=desc,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-k', '--api-key', action='store', dest='api_key',
required=True, help='API key for mailchimp')
parser.add_argument('-l', '--list-id', action='store', dest='list_id',
required=True, help='List ID to print subscribers from')
parser.add_argument('-g', '--group', action='store', dest='group',
required=False, default=None,
help='Name of group to query')
parser.add_argument('-i', '--interests', action='store', dest='interests',
required=False, default=None,
help='CSV list of interests to query (enclose interests with spaces inside quotes)')
parser.add_argument('--just-interests', action='store_true',
dest='just_interests', required=False, default=True,
help='Print just the interests for each subscriber')
args = vars(parser.parse_args())
if args['interests'] is not None:
args['interests'] = args['interests'].split(',')
return args
示例9: main
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def main(api_key, list_id, file_, dry_run=False):
"""
:param api_key: Mailchimp API key
:param list_id: Mailchimp list ID to add subscribers to
:param file_: File to read subscribers from
:param dry_run: Do a dry run and print the import data without importing
:returns: None
"""
mc = mailchimp.Mailchimp(api_key)
return add_subscribers_from_file(mc, list_id, file_, dry_run)
示例10: add_subscriber
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def add_subscriber(api_instance, list_id, email, stacks, group_name):
"""
Add subscriber to mailchimp list
:param api_instance: Instance of mailchimp.Mailchimp API object
:param list_id: List ID to add subscribers to
:param email: Email of subscriber
:param stacks: List of programming 'stacks' to association with subscriber
:param group_name: Name of group in Mailchimp list that stacks belong to
:returns: Subscriber ID or None if subscriber was not added
"""
groups = [{'name': group_name, 'groups': stacks}]
# Mailchimp API requires this to be in a dict
email = {'email': email}
# The 'groupings' is a special key in the API merge_vars dict that's
# required to add subscribers to a group.
merge_vars = {'groupings': groups}
subscriber_id = api_instance.lists.subscribe(list_id,
email,
merge_vars=merge_vars,
double_optin=False,
update_existing=True,
replace_interests=True)
return subscriber_id
示例11: add_subscriber
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
def add_subscriber(email, stacks):
"""
Add subscriber to mailchimp list
:param email: Email of subscriber
:param stacks: List of programming 'stacks' to association with subscriber
:returns: Subscriber ID or None if subscriber was not added
"""
initialize_favorite_stacks(LIST_ID)
# Weed out any stacks that are not already in mailchimp list groups
groups = []
valid_stacks = list(set(stacks).intersection(FAVORITE_STACKS))
groups = [{'name': FAVORITE_STACKS_NAME, 'groups': valid_stacks}]
# Mailchimp API requires this to be in a dict
email = {'email': email}
# The 'groupings' is a special key in the API merge_vars dict that's
# required to add subscribers to a group.
merge_vars = {'groupings': groups}
try:
subscriber_id = MC.lists.subscribe(LIST_ID,
email,
merge_vars=merge_vars,
double_optin=False,
update_existing=True,
replace_interests=True)
except Exception as err:
app.logger.error('Failed adding subscriber: %s (list: "%s", email: "%s", stacks: "%s", groups: "%s")',
err, LIST_ID, email, stacks, groups, exc_info=True)
return None
return subscriber_id
示例12: member_pre_save_cb
# 需要導入模塊: import mailchimp [as 別名]
# 或者: from mailchimp import Mailchimp [as 別名]
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)