本文整理汇总了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)
示例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
示例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)
示例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())
示例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)
示例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())
示例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
示例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
示例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
示例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 = []
示例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():
示例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())
示例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)
示例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
示例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