当前位置: 首页>>代码示例>>Python>>正文


Python postmonkey.PostMonkey类代码示例

本文整理汇总了Python中postmonkey.PostMonkey的典型用法代码示例。如果您正苦于以下问题:Python PostMonkey类的具体用法?Python PostMonkey怎么用?Python PostMonkey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了PostMonkey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: lists

def lists():
	pm = PostMonkey(os.environ.get('MAILCHIMP_API_KEY',''))
	lists = pm.lists()
	for list in lists['data']:
	    print list['id'], list['name']

	return file('templates/200.json').read(), 200
开发者ID:optional-is,项目名称:email2mailchimp,代码行数:7,代码来源:run.py

示例2: snapshot_mailchimp

def snapshot_mailchimp(verbose=False):
    api_key = os.environ.get('MAILCHIMP_API_KEY')
    assert api_key, 'No MAILCHIMP_API_KEY defined in environment.'
    pm = PostMonkey(api_key, timeout=10)
    ping_string = pm.ping()
    expected = u'Everything\'s Chimpy!'
    assert ping_string==expected, 'Bad handshake, got "%s", expected "%s"' % (ping_string,expected)
    if verbose:
        print 'handshake ok'
    lists = pm.lists()
    if not 'data' in lists:
        print 'Got bad lists object from server.'
        pprint(lists)
        raise ValueError('Bad lists object from server')
    # Snapshot creation code...
    today = datetime.now().date()
    for l in lists['data']:
        try:
            if verbose: print 'Scraping %s...' % l['name']
            latest = Session.query(model.SnapshotOfMailchimp)\
                    .filter(model.SnapshotOfMailchimp.name==l['name'])\
                    .order_by(model.SnapshotOfMailchimp.timestamp.desc())\
                    .first()
            if latest and latest.timestamp>=today:
                if verbose: print ' -> most recent snapshots have already been processed.'
                continue
            snapshot = model.SnapshotOfMailchimp(\
                    name = l['name'],\
                    members = l['stats']['member_count'],
                    timestamp = today)
            if verbose: print '  -> ',snapshot.toJson()
            Session.add(snapshot)
            Session.commit()
        except Exception, e:
            pprint({'list':l,'exception':str(e)})
开发者ID:e6,项目名称:activityapi,代码行数:35,代码来源:snapshot_mailchimp.py

示例3: MailchimpLocator

class MailchimpLocator(object):
    """Utility for MailChimp API calls.
    """

    implements(IMailchimpLocator)

    def connect(self):
        registry = getUtility(IRegistry)
        self.settings = registry.forInterface(IMailchimpSettings)
        self.mailchimp = PostMonkey(self.settings.api_key)

    def lists(self):
        """Return all available MailChimp lists.
        http://apidocs.mailchimp.com/api/rtfm/lists.func.php
        """
        #print("MAILCHIMP LOCATOR: lists")
        self.connect()
        try:
            # lists returns a dict with 'total' and 'data'. we just need data
            return self.mailchimp.lists()['data']
        except MailChimpException:
            return []
        except PostRequestError:
            return []
        except:
            raise

    def default_list_id(self):
        self.connect()
        if self.settings.default_list:
            return self.settings.default_list
        lists = self.lists()
        if len(lists) > 0:
            return lists[0]['id']

    def groups(self, list_id=None):
        """Return all available MailChimp interest groups.

        @id: the list id to connect to. e.g. u'a1346945ab'. Not the web_id!

        http://apidocs.mailchimp.com/api/rtfm/listinterestgroupings.func.php
        """
        if not list_id:
            return
        #print("MAILCHIMP LOCATOR: groups")
        self.connect()
        try:
            # mailchimp returns a list of groups for a single mailinglist.
            # We always choose the first and return just the groups part.
            return self.mailchimp.listInterestGroupings(id=list_id)[0]
        except MailChimpException, error:
            if error.code == 211:
                # "This list does not have interest groups enabled"
                # http://apidocs.mailchimp.com/api/1.3/exceptions.field.php#210-list-_-basic-actions
                return
            elif error.code == 200:
                # "Invalid MailChimp List ID"
                # http://apidocs.mailchimp.com/api/1.3/exceptions.field.php#200-list-related-errors
                return
            raise
开发者ID:kingel,项目名称:collective.mailchimp,代码行数:60,代码来源:locator.py

示例4: register

def register():
    statsd.increment('api_calls.register')
    form = SignupForm(request.form)
    logger.info(request.form)
    if not form.validate():
        msg = {
            'success': False,
            'msg': form.errors}
        return jsonify(msg)
    user = session.query(Person).\
        filter(Person.email == form.email.data
               ).first()
    if user:
        msg = {
            'success': False,
            'msg': user.email + ' is already registered!',
            'parameter': 'email', }
        return jsonify(msg)
    u = Person(form)
    session.add(u)
    session.commit()
    try:
        pm = PostMonkey(apikey=MC_APIKEY, timeout=10)
        pm.listSubscribe(
            id=MC_LISTID, email_address=form.email.data)
    except MailChimpException, e:
        app.logger.error(str(e))
开发者ID:dhilipsiva,项目名称:moback,代码行数:27,代码来源:api.py

示例5: SignupWorker

class SignupWorker(QueueProcessingWorker):
    def __init__(self):
        super(SignupWorker, self).__init__()
        if settings.MAILCHIMP_API_KEY:
            self.pm = PostMonkey(settings.MAILCHIMP_API_KEY, timeout=10)

    def consume(self, data):
        merge_vars=data['merge_vars']
        # This should clear out any invitation reminder emails
        clear_followup_emails_queue(data["EMAIL"])
        if settings.MAILCHIMP_API_KEY and settings.PRODUCTION:
            try:
                self.pm.listSubscribe(
                        id=settings.ZULIP_FRIENDS_LIST_ID,
                        email_address=data['EMAIL'],
                        merge_vars=merge_vars,
                        double_optin=False,
                        send_welcome=False)
            except MailChimpException as e:
                if e.code == 214:
                    logging.warning("Attempted to sign up already existing email to list: %s" % (data['EMAIL'],))
                else:
                    raise e

        email = data.get("EMAIL")
        name = merge_vars.get("NAME")
        enqueue_welcome_emails(email, name)
开发者ID:150vb,项目名称:zulip,代码行数:27,代码来源:queue_processors.py

示例6: review

def review():

    app.logger.debug(request.form)

    # get form data (WE SHOULD VALIDATE)
    message = request.form.get('message')
    subject = request.form.get('subject')
    from_email = request.form.get('from_email')
    from_name = request.form.get('from_name')

    app.logger.debug(from_email)
    app.logger.debug(from_name)

    pm = PostMonkey(app.config['PM_API_KEY'])
    list_info = pm.lists(filters={'list_id':app.config['PM_LIST_ID']})
    list_name = list_info['data'][0]['name']
    list_count = list_info['data'][0]['stats']['member_count']

    return render_template('review_form.html',
                           page_title="Review E-mail",
                           from_name=from_name,
                           from_email=from_email,
                           list_name=list_name,
                           list_count=list_count,
                           message=message,
                           subject=subject)
开发者ID:gizmomathboy,项目名称:ncs-notifications,代码行数:26,代码来源:__init__.py

示例7: handleApply

 def handleApply(self, action):
     data, errors = self.extractData()
     if 'email' in data:
         # Fetch MailChimp settings
         registry = getUtility(IRegistry)
         mailchimp_settings = registry.forInterface(IMailchimpSettings)
         if len(mailchimp_settings.api_key) == 0:
             return
         mailchimp = PostMonkey(mailchimp_settings.api_key)
         # Fetch MailChimp lists
         # XXX, Todo: For now we just fetch the first list.
         try:
             lists = mailchimp.lists()['data']
             list_id = lists[0]['id']
         except MailChimpException, error:
             raise WidgetActionExecutionError(
                 Invalid(_(u"Could not fetch list from mailchimp.com: %s" %
                     error)))
         # Subscribe to MailChimp list
         try:
             mailchimp.listSubscribe(
                 id=list_id,
                 email_address=data['email'])
         except MailChimpException, error:
             raise WidgetActionExecutionError(
                 'email',
                 Invalid(_(
                     u"Could not subscribe to newsletter: %s" % error)))
开发者ID:fourdigits,项目名称:collective.mailchimp,代码行数:28,代码来源:newsletter.py

示例8: email_chimp

def email_chimp(request):
	email = request.POST['email']
	apikey = 'a36024c7bb5504d63b61963dd9741fa2-us8'
	mailid = 'c4ed436de6'

	pm = PostMonkey(apikey)
	pm.listSubscribe(id = mailid, email_address = email, double_optin = False)
	return HttpResponse()
开发者ID:AndreaLugli,项目名称:InstAutomation,代码行数:8,代码来源:views.py

示例9: test_mailchimp_ping_method

def test_mailchimp_ping_method(mock_class):
    mock_class().ping = MagicMock(
        return_value=u"Everything's Chimpy!"
    )

    from postmonkey import PostMonkey
    pm = PostMonkey('123')
    assert pm.ping() == u"Everything's Chimpy!"
开发者ID:tisto,项目名称:mock-testing-in-python,代码行数:8,代码来源:example-mock.py

示例10: valid_api_key

 def valid_api_key(data):
     if len(data.api_key) == 0:
         return
     mailchimp = PostMonkey(data.api_key)
     try:
         return mailchimp.ping()
     except:
         raise Invalid(
             u"Your MailChimp API key is not valid. Please go " +
             u"to mailchimp.com and check your API key.")
开发者ID:kingel,项目名称:collective.mailchimp,代码行数:10,代码来源:interfaces.py

示例11: available_lists

 def available_lists(self):
     registry = getUtility(IRegistry)
     mailchimp_settings = registry.forInterface(IMailchimpSettings)
     mailchimp = PostMonkey(mailchimp_settings.api_key)
     try:
         return mailchimp.lists()
     except MailChimpException, error:
         raise WidgetActionExecutionError(
             Invalid(u"Could not fetch available lists from MailChimp. " +
                 "Please check your MailChimp API key: %s" % error))
开发者ID:fourdigits,项目名称:collective.mailchimp,代码行数:10,代码来源:controlpanel.py

示例12: valid_api_key

 def valid_api_key(obj):
     registry = getUtility(IRegistry)
     mailchimp_settings = registry.forInterface(IMailchimpSettings)
     if len(mailchimp_settings.api_key) == 0:
         return
     mailchimp = PostMonkey(mailchimp_settings.api_key)
     try:
         return mailchimp.ping()
     except:
         raise Invalid(u"Your MailChimp API key is not valid. Please go " +
             "to mailchimp.com and check your API key.")
开发者ID:fourdigits,项目名称:collective.mailchimp,代码行数:11,代码来源:interfaces.py

示例13: mailchimp_account

 def mailchimp_account(self):
     registry = getUtility(IRegistry)
     mailchimp_settings = registry.forInterface(IMailchimpSettings)
     if len(mailchimp_settings.api_key) == 0:
         return []
     mailchimp = PostMonkey(mailchimp_settings.api_key)
     try:
         return mailchimp.getAccountDetails()
     except MailChimpException, error:
         raise WidgetActionExecutionError(
             Invalid(u"Could not fetch account details from MailChimp. " +
                 "Please check your MailChimp API key: %s" % error))
开发者ID:fourdigits,项目名称:collective.mailchimp,代码行数:12,代码来源:controlpanel.py

示例14: send

def send():
    """
    sends emails to a configured MailChimp list
    """

    # get form data (WE SHOULD VALIDATE)
    msg_text = request.form.get('message')
    subject = request.form.get('subject')
    from_email = request.form.get('from_email')
    from_name = request.form.get('from_name')
    test_list = request.form.get('test_list', None)

    if (test_list):
        list_id = app.config['PM_TEST_LIST_ID']
        app.logger.debug("sending to test list %s" % (list_id))
    else:
        list_id = app.config['PM_LIST_ID']
        app.logger.debug("sending to LIVE list %s" % (list_id))

    pm = PostMonkey(app.config['PM_API_KEY'])
    md = Mandrill(app.config['MD_API_KEY'])

    members = pm.listMembers(id=list_id, limit=1000)
    emails = []

    for mem in members['data']:
        emails.append(mem['email'])

    eastern = pytz.timezone('US/Eastern')
    now = eastern.localize(datetime.datetime.now())
    msg_text = "%s\n\n--------\n\nE-mail generated at %s" % (msg_text, now)

    for email in emails:
        message = {
            "text": msg_text,
            "subject": subject,
            "from_email": from_email,
            "from_name": from_name,
            "to": [{
                "email": email
            }]
        }

        app.logger.debug("sending to %s at %s" % (email, now))

        resp = md.messages.send(message, async=True)

        app.logger.debug(pformat(resp))

    flash("%s e-mails sent!" % len(emails))

    return redirect(url_for('home'))
开发者ID:funkatron,项目名称:ncs-notifications,代码行数:52,代码来源:__init__.py

示例15: available_lists

def available_lists(context):
    registry = getUtility(IRegistry)
    mailchimp_settings = registry.forInterface(IMailchimpSettings)
    if len(mailchimp_settings.api_key) == 0:
        return SimpleVocabulary([])
    mailchimp = PostMonkey(mailchimp_settings.api_key)
    try:
        lists = mailchimp.lists()["data"]
    except MailChimpException:
        pass
    except:
        return SimpleVocabulary([])
    return SimpleVocabulary([SimpleTerm(value=li["id"], title=li["name"]) for li in lists])
开发者ID:fourdigits,项目名称:collective.mailchimp,代码行数:13,代码来源:vocabularies.py


注:本文中的postmonkey.PostMonkey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。