def handle_noargs(self, **kwargs):
     api = SailthruClient(settings.SAILTHRU_API_KEY,
                          settings.SAILTHRU_API_SECRET)
     pp = pprint.PrettyPrinter(indent=4)
     i = 0
     total_i = 0
     out_file_count = 0
     out_file = None
     with open('/home/ubuntu/Project/ecomarket/all-users.csv',
               'rb') as csvfile:
         reader = csv.reader(csvfile)
         headers = None
         for row in reader:
             if headers is None:
                 headers = row
                 continue
             row = dict(zip(headers, row))
             non_empty_row = {}
             for k, v in row.items():
                 if v is not None:
                     v = v.strip()
                     if len(v) == 0:
                         v = None
                     non_empty_row[k] = v
             st_user = api.api_get('user',
                                   {'id': non_empty_row['Profile Id']})
             if st_user is None:
                 print "Cannot find user '%s'" % (
                     non_empty_row['Profile Id'], )
             body = st_user.get_body()
             st_user_vars = body['vars']
             if st_user_vars is None:
                 continue
             for key in st_user_vars.keys():
                 try:
                     if st_user_vars[k] is not None:
                         if type(st_user_vars[k]) == str:
                             st_user_vars[k] = st_user_vars[k].strip()
                             if st_user_vars[k] == '':
                                 st_user_vars[k] = None
                 except:
                     pass
             new_vars = clean_user(st_user_vars)
             email = body['keys']['email']
             if out_file is None or i > 5000:
                 i = 0
                 if out_file is not None:
                     out_file.close()
                 out_file_count += 1
                 out_file = open('batch_%d.txt' % (out_file_count, ), 'wb')
             out_file.write(
                 json.dumps({
                     'email': email,
                     'vars': new_vars
                 },
                            default=_encoder_default) + "\n")
             i += 1
             total_i += 1
             print "%d %d %d" % (i, total_i, out_file_count)
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'])
            raise RuntimeError('Failed to connect with Sailthru API')
        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()))
            raise RuntimeError('Failed to connect with Sailthru API')

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

        with tempfile.NamedTemporaryFile(delete=False, mode='w+t') 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'])
                raise RuntimeError('Failed to connect with Sailthru API')

            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)
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': '*****@*****.**'})

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())
# -*- 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": "*****@*****.**"})

    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 as e:
    # Handle exceptions
    print("Exception")
    print(e)