Пример #1
0
    def retrieve_de(self, args):
        """
        retrieve all rows from data extension.

        :param string customer_key: data extension's customer key
        :return: data extension's name array.
        """
        fields = self.describe_de(args)
        row = FuelSDK.ET_DataExtension_Row()
        row.auth_stub = self.client
        row.CustomerKey = args.customer_key
        row.props = [field['Name'] for field in fields]
        response = row.get()
        writer = csv.writer(sys.stdout,
                            quoting=csv.QUOTE_ALL,
                            lineterminator='\n')
        writer.writerow(row.props)

        for result in response.results:
            row = []
            for prop in result.Properties[0]:
                if prop.Value is None:
                    row.append("")
                else:
                    row.append(prop.Value.encode("utf-8"))
            writer.writerow(row)
Пример #2
0
 def get_de_rows_filter(self,
                        de_name,
                        col_name,
                        filter_value,
                        operation,
                        value_type='date'):
     """
     Get filtered records from data extension based on the filter applied
     on the column
     Use value_type != 'date' for filtering values other than date type
     Operation: SFMC supported operations
     """
     dataextensionrow = FuelSDK.ET_DataExtension_Row()
     dataextensionrow.auth_stub = self.sfmc_client
     dataextensionrow.Name = de_name
     col_names = self._get_col(de_name)
     if col_name not in col_names:  #Check for column presence
         logging.error(
             f"{col_name} column not present in data extension {de_name}")
         return False
     if value_type.lower() == 'date':
         logging.debug('Date value selected for filtering')
         dataextensionrow.search_filter = {
             'Property': col_name,
             'SimpleOperator': operation,
             'DateValue': filter_value
         }
     else:
         logging.debug('Non date value selected for filtering')
         dataextensionrow.search_filter = {
             'Property': col_name,
             'SimpleOperator': operation,
             'Value': filter_value
         }
     df_in_file = pd.DataFrame()
     for col in col_names:  #Get data column wise
         dataextensionrow.props = [col]
         results = dataextensionrow.get()
         col_data = [
             i['Properties']['Property'][0]['Value']
             for i in results.results
         ]
         while results.more_results:
             results = dataextensionrow.getMoreResults()
             col_data = col_data + [
                 i['Properties']['Property'][0]['Value']
                 for i in results.results
             ]
         df_in_file[col] = col_data
     logging.info(
         f"Total rows gathered from data extension:{de_name} = {df_in_file.shape[0]}"
     )
     return df_in_file
Пример #3
0
 def get_data_extension_rows(self,
                             customer_key,
                             search_filter=None,
                             property_list=None):
     de_row = FuelSDK.ET_DataExtension_Row()
     de_row.auth_stub = self.get_client()
     de_row.CustomerKey = customer_key
     if search_filter:
         de_row.search_filter = search_filter
     if property_list:
         de_row.props = property_list
     return de_row.get()
Пример #4
0
def load_de(table_name, de_name):

    debug = False
    stubObj = f.ET_Client(False, debug)
    DE_NAME = de_name
    FOLDER_ID = 502  # API_GEN
    de_to_load = f.ET_DataExtension_Row()
    de_to_load.CustomerKey = de_name
    de_to_load.auth_stub = stubObj
    # de_to_load.props = {"Col1": "Value1", "Col2": "Value2"}
    de_to_load.props = fetch_table_data(table_name)
    de_loaded_response = de_to_load.post()
Пример #5
0
def get_subscriberkey(EmailAddress):

    headers = {
        'content-type': 'application/json',
        'Authorization': get_auth_token()
    }
    if (not os.environ.get('PYTHONHTTPSVERIFY', '')
            and getattr(ssl, '_create_unverified_context', None)):
        ssl._create_default_https_context = ssl._create_unverified_context

    debug = False
    stubObj = f.ET_Client(False, debug)

    row = f.ET_DataExtension_Row()
    row.auth_stub = stubObj

    # define DE List
    # deList = list()
    # deList = ['DE_order_confirm']
    # deList = ['DE_order_confirm', 'DE_password_reset', 'DE_password_changed',
    #               'DE_pdt_print_ready', 'DE_pdt_proof_ready', 'DE_photo_share_receiver',
    #               'DE_photo_share_sender', 'DE_share_project_receiver']
    # nameOfDE = 'DE_password_reset'
    # loop over DE list

    de = 'DE_SF_USER_D'

    row.CustomerKey = str(de)

    row.props = ["USERID"]

    # set search filter
    row.search_filter = {
        'Property': 'CURR_EMAIL_ADDRESS',
        'SimpleOperator': 'equals',
        'Value': EmailAddress
    }
    getResponse = row.get()

    data = dict()
    #

    if len(getResponse.results) > 0:
        data = {
            "name": getResponse.results[0].Properties.Property[0].Name,
            "value": getResponse.results[0].Properties.Property[0].Value
        }
    else:
        data = {"Message": str(getResponse.results)}

    return data
Пример #6
0
    def create_de_row(self, args):
        """
        create data extension row.

        :param string customer_key: data extension's customer key
        :param string attributes_json:
        :return: data extension's name array.
        """
        deRow = FuelSDK.ET_DataExtension_Row()
        deRow.CustomerKey = args.customer_key
        deRow.auth_stub = self.client
        args.attributes = json.loads(args.attribute_file.read())

        deRow.props = json.loads(args.attributes_json)
        deRowResponse = deRow.post()
        print(json.dumps(deRowResponse.results))
    def _replicate(self, customer_key, keys,
                   parent_category_id, table,
                   partial=False, start=None,
                   end=None, unit=None, replication_key=None):
        if partial:
            LOGGER.info("Fetching {} from {} to {}"
                        .format(table, start, end))

        cursor = FuelSDK.ET_DataExtension_Row()
        cursor.auth_stub = self.auth_stub
        cursor.CustomerKey = customer_key
        cursor.props = keys

        if partial:
            cursor.search_filter = get_date_page(replication_key,
                                                 start,
                                                 unit)

        batch_size = int(self.config.get('batch_size', 2500))
        result = request_from_cursor('DataExtensionObject', cursor,
                                     batch_size=batch_size)

        for row in result:
            row = self.filter_keys_and_parse(row)
            row['CategoryID'] = parent_category_id

            self.state = incorporate(self.state,
                                     table,
                                     replication_key,
                                     row.get(replication_key))

            singer.write_records(table, [row])

        if partial:
            self.state = incorporate(self.state,
                                     table,
                                     replication_key,
                                     start)

            save_state(self.state)
Пример #8
0
def get_de_row(EmailAddress):

    headers = {
        'content-type': 'application/json',
        'Authorization': get_auth_token()
    }
    if (not os.environ.get('PYTHONHTTPSVERIFY', '')
            and getattr(ssl, '_create_unverified_context', None)):
        ssl._create_default_https_context = ssl._create_unverified_context

    debug = False
    stubObj = f.ET_Client(False, debug)

    row = f.ET_DataExtension_Row()
    row.auth_stub = stubObj

    # define DE List
    de = 'SentEvent'

    row.CustomerKey = str(de)

    # get columns in the DE and append to row props

    # row.props = getDeColumns(nameOfDE)
    row.props = ["TriggeredSendCustomerKey", 'EmailAddress']

    # correlationID from method param
    # correlationID = 'a3e3227f-b8e8-40f2-b5e2-9e899147e2d1'

    SubscriberKey = get_subscriberkey(EmailAddress).get('value')

    print("SubscriberKey = %s" % SubscriberKey)

    # set search filter
    row.search_filter = {
        'Property': 'SubscriberKey',
        'SimpleOperator': 'equals',
        'Value': SubscriberKey
    }

    # start_time = time.time()

    getResponse = row.get()

    data = list()

    if len(getResponse.results) > 0:
        record_found = True

        for response in getResponse.results[0].Properties.Property:
            for property in response:
                data.append(property, )
                # https://stackoverflow.com/questions/13761054/more-pythonic-way-to-format-a-json-string-from-a-list-of-tuples
                data = '{{{}}}'.format(','.join([
                    '{}:{}'.format(json.dumps(k), json.dumps(v))
                    for k, v in data
                ]))
    else:
        data = {"Message": str(getResponse.results)}

    return data
Пример #9
0
import FuelSDK as f
import os
import ssl


if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):
    ssl._create_default_https_context = ssl._create_unverified_context

debug = False
stubObj = f.ET_Client(False, debug)

row = f.ET_DataExtension_Row()
row.auth_stub = stubObj

# loop over DE list
# deList = list()
# nameOfDE = '_SENT'
nameOfDE = 'password_reset'
# nameOfDE = 'DE_password_changed'
# nameOfDE = 'DE_order_confirm'
# nameOfDE = 'DE_password_reset'


row.CustomerKey = nameOfDE

# TODO: get columns in the DE and append to row props
# row.props = getDeColumns(nameOfDE)
row.props = ["correlationId", 'EmailAddress']

# correlationID from method param
correlationId = 'PASS_RESET_TEST_001'
Пример #10
0
    def get(self, emailType, correlationId):
        """
            Fetch sends for a given emailType and correlationId
            ---
            tags:
              - SFMC
            parameters:
              - in: path
                name: emailType
                required: true
                description: The emailType of the send, try password_reset.
                type: string
              - in: path
                name: correlationId
                required: true
                description: The correlationId  of the send, try TEST
                type: string
            responses:
              200:
                description: Results from Salesforce
        """

        # requestToken
        token_url = "https://auth.exacttargetapis.com/v1/requestToken"
        headers = {'content-type': 'application/json'}
        token_data = {
            "clientId": config.clientid,
            "clientSecret": config.clientsecret
        }

        response = requests.post(token_url, json=token_data, headers=headers)

        token = json.loads(response.text)

        # print("access token =" + str(token['accessToken']))
        access_token = ''.join(token['accessToken'])

        # request token
        auth_token = 'Bearer ' + access_token  # Bearer Token
        # print("auth_token = " + auth_token)

        # SSL context verification

        if (not os.environ.get('PYTHONHTTPSVERIFY', '')
                and getattr(ssl, '_create_unverified_context', None)):
            ssl._create_default_https_context = ssl._create_unverified_context

        debug = False
        stubObj = f.ET_Client(False, debug)

        if emailType.lower() == 'password_reset':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        print("{\"name\": %s, \"value\": %s}" %
                              (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'order_confirm':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)
            # print("# records  = %s" % len(getResponse.results))

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'password_changed':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'pdt_print_ready':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'pdt_proof_ready':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'photo_share_receiver':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'photo_share_sender':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'share_project_receiver':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'share_project_sender':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'ship_confirm':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'welcome':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        elif emailType.lower() == 'new_prospect_request':

            row = f.ET_DataExtension_Row()
            row.auth_stub = stubObj

            nameOfDE = emailType.lower()
            row.CustomerKey = nameOfDE

            # TODO: get columns in the DE and append to row props
            # row.props = getDeColumns(nameOfDE)
            row.props = [
                "correlationId", 'EmailAddress', 'SubscriberKey', 'emailType',
                'uid', 'timestamp_DT'
            ]

            # correlationId = 'PASS_RESET_TEST_001'

            # set search filter
            row.search_filter = {
                'Property': 'correlationId',
                'SimpleOperator': 'equals',
                'Value': correlationId
            }

            getResponse = row.get()

            data = list()
            data_dict = {}

            records_found = len(getResponse.results)

            if records_found > 0:

                results = getResponse.results
                for i, j in enumerate(results):
                    # print("%s-%s"%(i,j))
                    for p, q in enumerate(j.Properties.Property):
                        # print(("%s-%s-%s"%(i,p,q)))
                        # print("{\"name\": %s, \"value\": %s}" % (q.Name, q.Value))
                        data_dict.update({"name": q.Name, "value": q.Value})
                        data.append(data_dict.copy())

                response_dict = {
                    "status": 'success',
                    "message":
                    str(records_found) + ' result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                # REF: https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict

            else:

                data = []

                response_dict = {
                    "status": 'success',
                    "message": '0 result(s) returned by Salesforce',
                    "data": data
                }

                response_str = json.dumps(response_dict)
                response = json.loads(response_str)

                pass

        return response
Пример #11
0
# Add a require statement to reference the Fuel SDK's functionality:
import FuelSDK
import ET_Client

print('>>>  Add a row to a data extension using CustomerKey')

# Next, create an instance of the ET_Client class:


try:
    # debug = False
    myClient = FuelSDK.ET_Client()
    # Create an instance of the object type we want to work with:
    de = FuelSDK.ET_DataExtension_Row()
    # Associate the ET_Client to the object using the auth_stub property:
    de.auth_stub = myClient

    de.CustomerKey = "2ECB6A6E-9A50-453C-9A3A-241AB39B0092"
    de.props = {"Email" : "*****@*****.**", "First" : "Gill", "Last" : "Roush", "EID" : "0678923", "Action" : "viewed financials"}
    # Utilize one of the ET_List methods:

    postResponse = de.post()

    # Print out the results for viewing
    print('Post Status: ' + str(postResponse.status))
    print('Code: ' + str(postResponse.code))
    print('Message: ' + str(postResponse.message))
    print('Results: ' + str(postResponse.results))

except Exception as e:
    print('Caught exception: ' + str(e.message))