Example #1
0
def _account_save(sender, instance, **kwargs):

    # Do not do anything if the instance is not valid!
    try:
        instance.full_clean()
    except ValidationError:
        return

    data_get = {'api_key': settings.API_KEY, 'username': settings.USERNAME}

    res = api(settings.API_ENDPOINT + '/v1/account_lead/', data_get)
    if res.status_code != 200:
        raise Exception("Couldn't connect to the database."+\
                " Status code: {0}, Reason: {1}.".format(res.status_code, res.reason))

    # If the resource_uri already exists means that the operation is to update
    # the record. There is no UPDATE request for the API, there fore do not
    # sync with the master DB.
    if instance.resource_uri:
        return

    # Make a POST request to update remote DB by API
    data_post = {}
    data_post['first_name'] = instance.first_name
    data_post['last_name'] = instance.last_name
    data_post['gender'] = instance.gender
    if instance.birth_date:
        data_post['birth_date'] = instance.birth_date.strftime("%Y-%m-%d")
    else:
        data_post['birth_date'] = None
    data_post['street_number'] = instance.street_number
    data_post['zipcode'] = instance.zipcode
    data_post['city'] = instance.city
    data_post['country'] = instance.country
    data_post['phone'] = instance.phone
    data_post['email'] = instance.email
    data_post['tr_referral'] = settings.TR_REFERRAL
    data_post['mailing_lists'] = 1
    data_post['utm_medium'] = 'api'
    data_post['ip_address'] = '192.168.10.10'

    res = api(settings.API_ENDPOINT + '/v1/account_lead/',
              data_get,
              data_post,
              method="POST")

    # Save the object into the current db only if was correctly saved into
    # the master DB
    if res.status_code != 201:
        raise Exception("Couldn't change the master db"+\
                " Status code: {0}, Reason: {1}.".format(res.status_code, res.reason))

    # Takes the resource_uri from the header of the response
    instance.resource_uri = res.headers.get('location',\
            '').replace(settings.API_ENDPOINT, '')
    if not instance.resource_uri:
        raise Exception("No resource uri available in the header response")
Example #2
0
def _account_save(sender, instance, **kwargs):

    # Do not do anything if the instance is not valid!
    try:
        instance.full_clean()
    except ValidationError:
        return

    data_get = {'api_key':settings.API_KEY, 'username':settings.USERNAME}

    res = api(settings.API_ENDPOINT+'/v1/account_lead/', data_get)
    if res.status_code != 200:
        raise Exception("Couldn't connect to the database."+\
                " Status code: {0}, Reason: {1}.".format(res.status_code, res.reason))


    # If the resource_uri already exists means that the operation is to update
    # the record. There is no UPDATE request for the API, there fore do not
    # sync with the master DB.
    if instance.resource_uri:
        return

    # Make a POST request to update remote DB by API
    data_post = {}
    data_post['first_name'] = instance.first_name
    data_post['last_name'] = instance.last_name
    data_post['gender'] = instance.gender
    if instance.birth_date:
        data_post['birth_date'] = instance.birth_date.strftime("%Y-%m-%d")
    else:
        data_post['birth_date'] = None
    data_post['street_number'] = instance.street_number
    data_post['zipcode'] = instance.zipcode
    data_post['city'] = instance.city
    data_post['country'] = instance.country
    data_post['phone'] = instance.phone
    data_post['email'] = instance.email
    data_post['tr_referral'] = settings.TR_REFERRAL
    data_post['mailing_lists'] = 1
    data_post['utm_medium'] = 'api'
    data_post['ip_address'] = '192.168.10.10'

    res = api(settings.API_ENDPOINT+'/v1/account_lead/', data_get, data_post, method="POST")


    # Save the object into the current db only if was correctly saved into
    # the master DB
    if res.status_code != 201:
        raise Exception("Couldn't change the master db"+\
                " Status code: {0}, Reason: {1}.".format(res.status_code, res.reason))

    # Takes the resource_uri from the header of the response
    instance.resource_uri = res.headers.get('location',\
            '').replace(settings.API_ENDPOINT, '')
    if not instance.resource_uri:
        raise Exception("No resource uri available in the header response")
Example #3
0
 def test_pos_add(self):
     """
     Checks when saving the record it appears stored in both local and remote DB
     """
     self.acc.save()
     self.assertEqual(self.acc, Account.objects.get(first_name='Barack'))
     res = api(settings.API_ENDPOINT+self.acc.resource_uri, {'username':settings.USERNAME,
         'api_key':settings.API_KEY})
     self.assertEqual(res.json['first_name'], 'Barack')
     self.acc.delete()
Example #4
0
 def test_pos_add(self):
     """
     Checks when saving the record it appears stored in both local and remote DB
     """
     self.acc.save()
     self.assertEqual(self.acc, Account.objects.get(first_name='Barack'))
     res = api(settings.API_ENDPOINT + self.acc.resource_uri, {
         'username': settings.USERNAME,
         'api_key': settings.API_KEY
     })
     self.assertEqual(res.json['first_name'], 'Barack')
     self.acc.delete()
Example #5
0
    def test_pos_del(self):
        """
        Checks when deleting a record it disappears in both local and remote DB
        """
        self.acc.save()
        self.acc.delete()

        self.assertRaises(Account.DoesNotExist, Account.objects.get, first_name='Barack')
        res = api(settings.API_ENDPOINT+self.acc.resource_uri, {'username':settings.USERNAME,
            'api_key':settings.API_KEY})
        # Checks the NOT FOUND status code
        self.assertEqual(res.status_code, 404)
Example #6
0
def _account_delete(sender, instance, **kwargs):
    data_get = {'api_key':settings.API_KEY, 'username':settings.USERNAME}

    # Make a DELETE request to update remote DB by API
    res = api(settings.API_ENDPOINT+instance.resource_uri,
            data_get, method="DELETE")

    # Two possible right cases when request a deletion:
    # 204 (NO CONTENT): Successfully deleted
    # 404 (NOT FOUND): Resource not found
    # all the other cases raise an Exception.
    if res.status_code != 204 and res.status_code != 404:
        raise Exception("Couldn't delete to the master db."+\
                " Status code:{0}, Reason: {1}".format(res.status_code,
                    res.reason))
Example #7
0
    def test_pos_del(self):
        """
        Checks when deleting a record it disappears in both local and remote DB
        """
        self.acc.save()
        self.acc.delete()

        self.assertRaises(Account.DoesNotExist,
                          Account.objects.get,
                          first_name='Barack')
        res = api(settings.API_ENDPOINT + self.acc.resource_uri, {
            'username': settings.USERNAME,
            'api_key': settings.API_KEY
        })
        # Checks the NOT FOUND status code
        self.assertEqual(res.status_code, 404)
Example #8
0
def _account_delete(sender, instance, **kwargs):
    data_get = {'api_key': settings.API_KEY, 'username': settings.USERNAME}

    # Make a DELETE request to update remote DB by API
    res = api(settings.API_ENDPOINT + instance.resource_uri,
              data_get,
              method="DELETE")

    # Two possible right cases when request a deletion:
    # 204 (NO CONTENT): Successfully deleted
    # 404 (NOT FOUND): Resource not found
    # all the other cases raise an Exception.
    if res.status_code != 204 and res.status_code != 404:
        raise Exception("Couldn't delete to the master db."+\
                " Status code:{0}, Reason: {1}".format(res.status_code,
                    res.reason))
Example #9
0
    def handle(self, *args, **options):
        # Make a GET request to get all the accounts
        data_get = {'api_key': settings.API_KEY, 'username': settings.USERNAME}

        # Update the accounts according to res
        res = api(settings.API_ENDPOINT + '/v1/mailing_list/', data_get)
        if res.status_code != 200:
            raise Exception("Couldn't connect to the DB."+\
                    " Status code: {0} Reason: {1}".format(res.status_code,
                        res.reason))

        existing_ml = set()
        for mailing in res.json['objects']:
            existing_ml.add(mailing['resource_uri'])
            ml, created =\
            MailingList.objects.get_or_create(resource_uri=mailing['resource_uri'])
            # Either if ml is created or already exists update the other fields
            if created:
                print "Creating mailing list: {0} - {1}".format(
                    ml.name, ml.resource_uri)
            else:
                print "Updating mailing list: {0} - {1}".format(
                    ml.name, ml.resource_uri)

            ml.name = mailing['name']
            ml.resource_uri = mailing['resource_uri']
            ml.save()

        # All mailing lists that doesn't exist in the master DB need to be
        # deleted
        for ml in MailingList.objects.all():
            if not ml.resource_uri in existing_ml:
                print "Deleting mailing list: {0} - {1}".format(
                    ml.name, ml.resource_uri)
                ml.delete()

        # Update the accounts according to res
        res = api(settings.API_ENDPOINT + '/v1/account_lead/', data_get)
        if res.status_code != 200:
            raise Exception("Couldn't connect to the DB."+\
                    " Status code: {0} Reason: {1}".format(res.status_code,
                        res.reason))

        existing_acc = set()
        for account in res.json['objects']:
            existing_acc.add(account['resource_uri'])
            acc, created = Account.objects.get_or_create(
                resource_uri=account['resource_uri'])
            # Either if acc is created or already exists update the other fields
            if created:
                print "Creating account: {0} {1} - {2}".format(
                    acc.first_name, acc.last_name, acc.resource_uri)
            else:
                print "Updating account: {0} {1} - {2}".format(
                    acc.first_name, acc.last_name, acc.resource_uri)

            acc.first_name = account['first_name']
            acc.last_name = account['last_name']
            acc.birth_date = account['birth_date']
            acc.gender = account['gender']
            acc.city = account['city']
            acc.country = account['country']
            acc.street_number = account['street_number']
            acc.zipcode = account['zipcode']
            acc.email = account['email']
            acc.phone = account['phone']
            acc.lead = account['lead']
            mailing_lists = []
            for ml in account['mailing_lists']:
                m, created = MailingList.objects.get_or_create(
                    resource_uri=ml['resource_uri'])
                m.name = ml['name']
                m.save()
                mailing_lists.append(m)
            acc.mailing_lists = mailing_lists
            acc.save()

        # All accounts that doesn't exist in the master DB need to be
        # deleted
        for acc in Account.objects.all():
            if not acc.resource_uri in existing_acc:
                print "Deleting account: {0} {1} - {2}".format(
                    acc.first_name, acc.last_name, acc.resource_uri)
                acc.delete()
Example #10
0
    def handle(self, *args, **options):
        # Make a GET request to get all the accounts
        data_get = {'api_key':settings.API_KEY, 'username':settings.USERNAME}

        # Update the accounts according to res
        res = api(settings.API_ENDPOINT+'/v1/mailing_list/', data_get)
        if res.status_code != 200:
            raise Exception("Couldn't connect to the DB."+\
                    " Status code: {0} Reason: {1}".format(res.status_code,
                        res.reason))

        existing_ml = set()
        for mailing in res.json['objects']:
            existing_ml.add(mailing['resource_uri'])
            ml, created =\
            MailingList.objects.get_or_create(resource_uri=mailing['resource_uri'])
            # Either if ml is created or already exists update the other fields
            if created:
                print "Creating mailing list: {0} - {1}".format(ml.name,
                        ml.resource_uri)
            else:
                print "Updating mailing list: {0} - {1}".format(ml.name,
                        ml.resource_uri)


            ml.name = mailing['name']
            ml.resource_uri = mailing['resource_uri']
            ml.save()

        # All mailing lists that doesn't exist in the master DB need to be
        # deleted
        for ml in MailingList.objects.all():
            if not ml.resource_uri in existing_ml:
                print "Deleting mailing list: {0} - {1}".format(ml.name,
                        ml.resource_uri)
                ml.delete()


        # Update the accounts according to res
        res = api(settings.API_ENDPOINT+'/v1/account_lead/', data_get)
        if res.status_code != 200:
            raise Exception("Couldn't connect to the DB."+\
                    " Status code: {0} Reason: {1}".format(res.status_code,
                        res.reason))


        existing_acc = set()
        for account in res.json['objects']:
            existing_acc.add(account['resource_uri'])
            acc, created = Account.objects.get_or_create(resource_uri=account['resource_uri'])
            # Either if acc is created or already exists update the other fields
            if created:
                print "Creating account: {0} {1} - {2}".format(acc.first_name,
                        acc.last_name, acc.resource_uri)
            else:
                print "Updating account: {0} {1} - {2}".format(acc.first_name,
                        acc.last_name, acc.resource_uri)

            acc.first_name = account['first_name']
            acc.last_name = account['last_name']
            acc.birth_date = account['birth_date']
            acc.gender = account['gender']
            acc.city = account['city']
            acc.country = account['country']
            acc.street_number = account['street_number']
            acc.zipcode = account['zipcode']
            acc.email = account['email']
            acc.phone = account['phone']
            acc.lead = account['lead']
            mailing_lists = []
            for ml in account['mailing_lists']:
                m, created = MailingList.objects.get_or_create(resource_uri=ml['resource_uri'])
                m.name = ml['name']
                m.save()
                mailing_lists.append(m)
            acc.mailing_lists = mailing_lists
            acc.save()


        # All accounts that doesn't exist in the master DB need to be
        # deleted
        for acc in Account.objects.all():
            if not acc.resource_uri in existing_acc:
                print "Deleting account: {0} {1} - {2}".format(acc.first_name,
                        acc.last_name, acc.resource_uri)
                acc.delete()