Search code examples
pythonpython-3.xfunctionsimple-salesforce

How to write a for loop to dynamically call values in a function?


I have a couple of tables that I want to run my python functions through; however I am having a hard time writing my script to do that.

Here is my variable with the tables:

object_to_export = ['Opportunity','Asset']

Here is my code:

object_to_export = ['Opportunity','Asset']


def sf_login():
    """
    Purpose: This function is designed to validate your Salesforce credentials and create/return an instance or session.
    Note: If we have already signed in, this will just return the original object.
    Note: The credentials are being held inside of the config.py file.

    """
    session_id, instance = SalesforceLogin(username=config.username,
                                           password=config.password,
                                           security_token=config.security_token)
    sf = Salesforce(instance=instance,
                    session_id=session_id)
    return sf


def sf_object_extract():
    """
    Purpose: This function is designed to extract data from Salesforce objects and return the results.
    Note: For sample sake, I have set the limit to 1000 records per object.
    """
    dd = sf_login()
    set_limit = 1000
    for sf_obj in object_to_export:
        desc = dd.sf_obj.describe()
        field_names = [field['name'] for field in desc['fields']]
        soql = "SELECT {} FROM {} limit {}".format(','.join(field_names), sf_obj, set_limit)
        results = dd.query_all(soql)
    return results

sf_object_extract()

When I run my code, is receive this error:

Traceback (most recent call last):
  File "/Users/m/PycharmProjects/test/sf_etl_hw_aaa_v1.py", line 43, in <module>
    sf_object_extract()
  File "/Users/m/PycharmProjects/test/sf_etl_hw_aaa_v1.py", line 37, in sf_object_extract
    desc = dd.sf_obj.describe()
  File "/Users/m/venv/lib/python3.7/site-packages/simple_salesforce/api.py", line 565, in describe
    headers=headers
  File "/Users/m/venv/lib/python3.7/site-packages/simple_salesforce/api.py", line 771, in _call_salesforce
    exception_handler(result, self.name)
  File "/Users/m/venv/lib/python3.7/site-packages/simple_salesforce/util.py", line 68, in exception_handler
    raise exc_cls(result.url, result.status_code, name, response_content)
simple_salesforce.exceptions.SalesforceResourceNotFound: Resource sf_obj Not Found. Response content: [{'errorCode': 'NOT_FOUND', 'message': 'The requested resource does not exist'}]

Any idea as to why I am receiving this error and fix my script to pass the table parameters my desc and soql variables?

Addition: I also tried putting the desc variable as

 desc = int("dd.{}.describe()".format(sf_obj))

But it gives me this error:

    desc = int("dd.{}.describe()".format(sf_obj))
ValueError: invalid literal for int() with base 10: 'dd.Opportunity.describe()'

Solution

  • object_to_export = ['Opportunity','Asset']
    
    
    def sf_login():
        """
        Purpose: This function is designed to validate your Salesforce credentials and 
    create/return an instance or session.
        Note: If we have already signed in, this will just return the original object.
        Note: The credentials are being held inside of the config.py file.
    
        """
        session_id, instance = SalesforceLogin(username=config.username,
                                               password=config.password,
                                               security_token=config.security_token)
        sf = Salesforce(instance=instance,
                        session_id=session_id)
        return sf
    
    
    def sf_object_extract():
        """
        Purpose: This function is designed to extract data from Salesforce objects and 
    return the results.
        Note: For sample sake, I have set the limit to 1000 records per object.
        """
        dd = sf_login()
        set_limit = 1000
        for sf_obj in object_to_export:
            desc = getattr(dd, sf_obj).describe() #dd.sf_obj.describe()
            field_names = [field['name'] for field in desc['fields']]
            soql = "SELECT {} FROM {} limit {}".format(','.join(field_names), sf_obj, 
    set_limit)
            results = dd.query_all(soql)
        return results
    
    sf_object_extract()
    

    you need to use getattr(obj, name_of_member) see the line with comment

    and example:

    class d():
        def __init__(self):
            self.x = 0
    
    q = d()
    #to get the value of 'x' member of q you can do 2 things
    x_value = getattr(q, 'x')
    x_value = q.x