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


Python sailthru_client.SailthruClient类代码示例

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


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

示例1: update_user_email

def update_user_email(self, new_email, old_email):
    """
    Adds/updates Sailthru when a user email address is changed
     Args:
        username(str): A string representation of user identifier
        old_email(str): Original email address
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    # ignore if email not changed
    if new_email == old_email:
        return

    sailthru_parms = {"id": old_email, "key": "email", "keysconflict": "merge", "keys": {"email": new_email}}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to update email for %s in Sailthru - %s", old_email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        log.error("Error attempting to update user email address in Sailthru: %s", error.get_message())
        if _retryable_sailthru_error(error):
            raise self.retry(countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)
开发者ID:CredoReference,项目名称:edx-platform,代码行数:34,代码来源:tasks.py

示例2: add_email_marketing_cookies

def add_email_marketing_cookies(sender, response=None, user=None,
                                **kwargs):  # pylint: disable=unused-argument
    """
    Signal function for adding any cookies needed for email marketing

    Args:
        response: http response object
        user: The user object for the user being changed

    Returns:
        response: http response object with cookie added
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return response

    post_parms = {
        'id': user.email,
        'fields': {'keys': 1},
        'vars': {'last_login_date': datetime.datetime.now().strftime("%Y-%m-%d")}
    }

    # get anonymous_interest cookie to capture usage before logon
    request = crum.get_current_request()
    if request:
        sailthru_content = request.COOKIES.get('anonymous_interest')
        if sailthru_content:
            post_parms['cookies'] = {'anonymous_interest': sailthru_content}

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        log.info(
            'Sending to Sailthru the user interest cookie [%s] for user [%s]',
            post_parms.get('cookies', ''),
            user.email
        )
        sailthru_response = \
            sailthru_client.api_post("user", post_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        return response

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']

            response.set_cookie(
                'sailthru_hid',
                cookie,
                max_age=365 * 24 * 60 * 60,  # set for 1 year
                domain=settings.SESSION_COOKIE_DOMAIN,
                path='/',
            )
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user.email)
    else:
        error = sailthru_response.get_error()
        # generally invalid email address
        log.info("Error attempting to obtain cookie from Sailthru: %s", error.get_message())
    return response
开发者ID:shevious,项目名称:edx-platform,代码行数:60,代码来源:signals.py

示例3: update_user

def update_user(self, sailthru_vars, email, site=None, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        sailthru_vars(dict): User profile information to pass as 'vars' to Sailthru
        email(str): User email address
        new_user(boolean): True if new registration
        activation(boolean): True if activation request
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_email_user_param(sailthru_vars, sailthru_client,
                                                                              email, new_user, email_config,
                                                                              site=site))

    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        if _retryable_sailthru_error(error):
            raise self.retry(countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)
        return

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        scheduled_datetime = datetime.utcnow() + timedelta(seconds=email_config.welcome_email_send_delay)
        try:
            sailthru_response = sailthru_client.api_post(
                "send",
                {
                    "email": email,
                    "template": email_config.sailthru_activation_template,
                    "schedule_time": scheduled_datetime.strftime('%Y-%m-%dT%H:%M:%SZ')
                }
            )
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", email, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
            if _retryable_sailthru_error(error):
                raise self.retry(countdown=email_config.sailthru_retry_interval,
                                 max_retries=email_config.sailthru_max_retries)
开发者ID:shevious,项目名称:edx-platform,代码行数:60,代码来源:tasks.py

示例4: update_user

def update_user(self, username, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        username(str): A string representation of user identifier
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    # get user
    user = User.objects.select_related('profile').get(username=username)
    if not user:
        log.error("User not found during Sailthru update %s", username)
        return

    # get profile
    profile = user.profile
    if not profile:
        log.error("User profile not found during Sailthru update %s", username)
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_sailthru_user_parm(user, profile, new_user, email_config))
    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", username, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        # put out error and schedule retry
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        raise self.retry(countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        try:
            sailthru_response = sailthru_client.api_post("send",
                                                         {"email": user.email,
                                                          "template": email_config.sailthru_activation_template})
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", username, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            # probably an invalid template name, just put out error
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
开发者ID:AndreySonetico,项目名称:edx-platform,代码行数:57,代码来源:tasks.py

示例5: force_unsubscribe_all

def force_unsubscribe_all(sender, **kwargs):  # pylint: disable=unused-argument
    """
    Synchronously(!) unsubscribes the given user from all Sailthru email lists.

    In the future this could be moved to a Celery task, however this is currently
    only used as part of user retirement, where we need a very reliable indication
    of success or failure.

    Args:
        email: Email address to unsubscribe
        new_email (optional): Email address to change 3rd party services to for this user (used in retirement to clear
                              personal information from the service)
    Returns:
        None
    """
    email = kwargs.get('email', None)
    new_email = kwargs.get('new_email', None)

    if not email:
        raise TypeError('Expected an email address to unsubscribe, but received None.')

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_parms = {
        "id": email,
        "optout_email": "all",
        "fields": {"optout_email": 1}
    }

    # If we have a new email address to change to, do that as well
    if new_email:
        sailthru_parms["keys"] = {
            "email": new_email
        }
        sailthru_parms["fields"]["keys"] = 1
        sailthru_parms["keysconflict"] = "merge"

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = sailthru_client.api_post("user", sailthru_parms)
    except SailthruClientError as exc:
        error_msg = "Exception attempting to opt-out user {} from Sailthru - {}".format(email, text_type(exc))
        log.error(error_msg)
        raise Exception(error_msg)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        error_msg = "Error attempting to opt-out user {} from Sailthru - {}".format(email, error.get_message())
        log.error(error_msg)
        raise Exception(error_msg)
开发者ID:cmscom,项目名称:edx-platform,代码行数:52,代码来源:signals.py

示例6: update_user

def update_user(self, sailthru_vars, email, new_user=False, activation=False):
    """
    Adds/updates Sailthru profile information for a user.
     Args:
        sailthru_vars(dict): User profile information to pass as 'vars' to Sailthru
        email(str): User email address
        new_user(boolean): True if new registration
        activation(boolean): True if activation request
    Returns:
        None
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return

    sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
    try:
        sailthru_response = sailthru_client.api_post("user",
                                                     _create_sailthru_user_parm(sailthru_vars, email,
                                                                                new_user, email_config))

    except SailthruClientError as exc:
        log.error("Exception attempting to add/update user %s in Sailthru - %s", email, unicode(exc))
        raise self.retry(exc=exc,
                         countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    if not sailthru_response.is_ok():
        error = sailthru_response.get_error()
        # put out error and schedule retry
        log.error("Error attempting to add/update user in Sailthru: %s", error.get_message())
        raise self.retry(countdown=email_config.sailthru_retry_interval,
                         max_retries=email_config.sailthru_max_retries)

    # if activating user, send welcome email
    if activation and email_config.sailthru_activation_template:
        try:
            sailthru_response = sailthru_client.api_post("send",
                                                         {"email": email,
                                                          "template": email_config.sailthru_activation_template})
        except SailthruClientError as exc:
            log.error("Exception attempting to send welcome email to user %s in Sailthru - %s", email, unicode(exc))
            raise self.retry(exc=exc,
                             countdown=email_config.sailthru_retry_interval,
                             max_retries=email_config.sailthru_max_retries)

        if not sailthru_response.is_ok():
            error = sailthru_response.get_error()
            # probably a disabled template, just put out error message
            log.error("Error attempting to send welcome email to user in Sailthru: %s", error.get_message())
开发者ID:LeslieZhu,项目名称:edx-platform,代码行数:50,代码来源:tasks.py

示例7: add_email_marketing_cookies

def add_email_marketing_cookies(sender, response=None, user=None,
                                **kwargs):  # pylint: disable=unused-argument
    """
    Signal function for adding any cookies needed for email marketing

    Args:
        response: http response object
        user: The user object for the user being changed

    Returns:
        response: http response object with cookie added
    """
    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return response

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        sailthru_response = \
            sailthru_client.api_post("user", {'id': user.email, 'fields': {'keys': 1},
                                              'vars': {'last_login_date':
                                                       datetime.datetime.now().strftime("%Y-%m-%d")}})
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        return response

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']

            response.set_cookie(
                'sailthru_hid',
                cookie,
                max_age=365 * 24 * 60 * 60  # set for 1 year
            )
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user.email)
    else:
        error = sailthru_response.get_error()
        log.error("Error attempting to obtain cookie from Sailthru: %s", error.get_message())
    return response
开发者ID:AndreySonetico,项目名称:edx-platform,代码行数:41,代码来源:signals.py

示例8: get_email_cookies_via_sailthru

def get_email_cookies_via_sailthru(self, user_email, post_parms):
    """
    Adds/updates Sailthru cookie information for a new user.
     Args:
        post_parms(dict): User profile information to pass as 'vars' to Sailthru
    Returns:
        cookie(str): cookie fetched from Sailthru
    """

    email_config = EmailMarketingConfiguration.current()
    if not email_config.enabled:
        return None

    try:
        sailthru_client = SailthruClient(email_config.sailthru_key, email_config.sailthru_secret)
        log.info(
            'Sending to Sailthru the user interest cookie [%s] for user [%s]',
            post_parms.get('cookies', ''),
            user_email
        )
        sailthru_response = sailthru_client.api_post("user", post_parms)
    except SailthruClientError as exc:
        log.error("Exception attempting to obtain cookie from Sailthru: %s", unicode(exc))
        raise SailthruClientError

    if sailthru_response.is_ok():
        if 'keys' in sailthru_response.json and 'cookie' in sailthru_response.json['keys']:
            cookie = sailthru_response.json['keys']['cookie']
            return cookie
        else:
            log.error("No cookie returned attempting to obtain cookie from Sailthru for %s", user_email)
    else:
        error = sailthru_response.get_error()
        # generally invalid email address
        log.info("Error attempting to obtain cookie from Sailthru: %s", error.get_message())

    return None
开发者ID:cmscom,项目名称:edx-platform,代码行数:37,代码来源:tasks.py

示例9: SailthruClient

# -*- coding: utf-8 -*-

from sailthru.sailthru_client import SailthruClient
from sailthru.sailthru_response import SailthruResponseError
from sailthru.sailthru_error import SailthruClientError

api_key = 'API_KEY'
api_secret = 'SUPER_SECRET'
sailthru_client = SailthruClient(api_key, api_secret)

try:
    response = sailthru_client.api_get("user", {"id": "[email protected]"})

    if response.is_ok():
        body = response.get_body()
        # handle body which is of type dictionary
        print body
    else:
        error = response.get_error()
        print "Error: " + error.get_message()
        print "Status Code: " + str(response.get_status_code())
        print "Error Code: " + str(error.get_error_code())
except SailthruClientError, e:
    # Handle exceptions
    print "Exception"
    print e
开发者ID:Dude-X,项目名称:sailthru-python-client,代码行数:26,代码来源:api.get.py

示例10: SailthruClient

__author__ = 'brucepannaman'

from sailthru.sailthru_client import SailthruClient
from sailthru.sailthru_response import SailthruResponseError
from sailthru.sailthru_error import SailthruClientError
import datetime
import psycopg2
import csv
import tinys3
import os

api_key = '***'

api_secret = '***'

sailthru_client = SailthruClient(api_key, api_secret)

# Validate if the connection to Sailthru works
try:
    response = sailthru_client.api_get("user", {"id": "[email protected]"})
except SailthruClientError:
    print SailthruResponseError

# Log if the connection is live
if response.is_ok():
    body = response.get_body()
    print "Test went ok"

# This is the final array of each day that will be written into the db
output_array = []
开发者ID:brucey31,项目名称:Sailthru_reporting,代码行数:30,代码来源:Sailthru_Reporting.py

示例11: SailthruClient

# -*- coding: utf-8 -*-

from sailthru.sailthru_client import SailthruClient
from sailthru.sailthru_response import SailthruResponseError
from sailthru.sailthru_error import SailthruClientError

api_key = 'API_KEY'
api_secret = 'SUPER_SECRET'
sailthru_client = SailthruClient(api_key, api_secret)

try:
    data = {
        "id": "[email protected]",
        "vars": {
            "name": "Prajwal Tuladhar",
            "address": {
                "city": "New York",
                "state": "NY",
                "zip": 11372
            },
            "preferred_login": "facebook",
            "has_used_smartphone": true
        },
        "keys": {
            "fb": "infynyxx",
            "twitter": "infynyxx"
        }
    }
    response = sailthru_client.api_post("user", data)

    if response.is_ok():
开发者ID:Dude-X,项目名称:sailthru-python-client,代码行数:31,代码来源:api.post.py

示例12: SailthruClient

from sailthru.sailthru_client import SailthruClient

api_key = "replace-with-your-api-key"
api_secret = "replace-with-your-api-secret"
api_url = "http://api.sailthru.com" # optional

sc = SailthruClient(api_key, api_secret, api_url)

# GET /user
response = sc.api_get('user', {'email': '[email protected]'})

print "is_ok: " + str(response.is_ok())
print "body: " + str(response.get_body())
print "response: " + str(response.get_response())
print "status_code: " + str(response.get_status_code())
print "error: " + str(response.get_error())
开发者ID:mydagobah,项目名称:sailthru-python-client-example,代码行数:16,代码来源:userApi.py

示例13: SailthruApiService

class SailthruApiService(object):
    """The service to interface with Sailthru API"""
    def __init__(self, sailthru_key, sailthru_secret, content_url_root):
        self.sailthru_client = SailthruClient(sailthru_key, sailthru_secret)
        self.content_url_root = content_url_root

    def list(self, list_size=1000):
        sailthru_content_list = []
        response = self.sailthru_client.api_get('content', {'items': list_size})

        if not response.is_ok():
            logging.error(
                "Error code %d connecting to Sailthru content api: %s",
                response.json['error'],
                response.json['errormsg']
            )
        else:
            for body in response.json['content']:
                logging.info(body)
                sailthru_content_list.append(body)

        return sailthru_content_list

    def _upload_batch_file(self, filepath, report_email=None):
        """Use Sailthru job API to upload all content as a batch job"""
        logging.info("Uploading %s" % filepath)
        request_data = {
            'job': 'content_update',
            'file': filepath,
            'report_email': report_email
        }
        response = self.sailthru_client.api_post('job', request_data, {'file': 1})

        if response.is_ok():
            job_id = response.get_body().get("job_id")
            logging.info("Import job started on SailThru - JOB ID: " + job_id)

            # Keeping checking status until we find out that it's done
            while True:
                logging.info("waiting for import to complete...")
                time.sleep(10)
                response = self.sailthru_client.api_get('job', {'job_id': job_id})
                if response.get_body().get("status") == "completed":
                    return

        else:
            error = response.get_error()
            logging.error("Error: " + error.get_message())
            logging.error("Status Code: " + str(response.get_status_code()))
            logging.error("Error Code: " + str(error.get_error_code()))

    def upload(self, library_items, report_email=None):
        if not library_items:
            return

        with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
            for item in library_items:
                json.dump(item, tmp_file)
                tmp_file.write('\n')
            tmp_file.close()
            self._upload_batch_file(tmp_file.name, report_email)
            os.unlink(tmp_file.name)

    def clear(self):
        while True:
            response = self.sailthru_client.api_get('content', {'items': 4000})

            if not response.is_ok():
                logging.error(
                    "Error code %d connecting to Sailthru content api: %s",
                    response.json['error'],
                    response.json['errormsg']
                )
                return

            sailthru_content = response.json['content']
            if not sailthru_content:
                logging.info('Content cleared')
                return

            for body in sailthru_content:
                item_key = body.get('url')
                if item_key:
                    response = self.sailthru_client.api_delete('content', {'url': item_key})
                    if response.is_ok():
                        logging.info("content item %s deleted", item_key)
                    else:
                        logging.info("content item %s delete encountered errors", item_key)
开发者ID:edx,项目名称:ecommerce-scripts,代码行数:88,代码来源:sailthru_api_service.py

示例14: __init__

 def __init__(self, sailthru_key, sailthru_secret, content_url_root):
     self.sailthru_client = SailthruClient(sailthru_key, sailthru_secret)
     self.content_url_root = content_url_root
开发者ID:edx,项目名称:ecommerce-scripts,代码行数:3,代码来源:sailthru_api_service.py

示例15: SailthruClient

# -*- coding: utf-8 -*-

from sailthru.sailthru_client import SailthruClient
from sailthru.sailthru_response import SailthruResponseError
from sailthru.sailthru_error import SailthruClientError

api_key = 'API_KEY'
api_secret = 'SUPER_SECRET'
sailthru_client = SailthruClient(api_key, api_secret)

try:
    template = "not_so_useful_template"
    response = sailthru_client.api_delete("template", {"template": template})

    if response.is_ok():
        body = response.get_body()
        # handle body which is of type dictionary
        print body
    else:
        error = response.get_error()
        print "Error: " + error.get_message()
        print "Status Code: " + str(response.get_status_code())
        print "Error Code: " + str(error.get_error_code())
except SailthruClientError, e:
    # Handle exceptions
    print "Exception"
    print e
开发者ID:Dude-X,项目名称:sailthru-python-client,代码行数:27,代码来源:api.delete.py


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