Search code examples
pythonsimple-salesforce

Simple_Salesforce Dynamic bulk query


Dynamically add an object to the bulk query job for Simple_Salesforce.

I'm not sure how to pass a variable to sf.bulk."Object".query.

I would like to be able to pass an object say "Account" to the definition and it does the bulk query sf.bulk.Account.query("SOQL...")

sf = Salesforce(username=sf_username, password=sf_password, security_token=sf_token)

def SOQL(table):
    qryResult = sf.bulk.`table`.query('SELECT Id FROM ' + table)

SOQL("Account")

I would like python to translate this to sf.bulk.Account.query("SELECT Id FROM Account")


Solution

  • You can directly call sf.bulk's __getattr__ method:

    sf = Salesforce(username=sf_username, password=sf_password, security_token=sf_token)
    
    def SOQL(table):
        return sf.bulk.__getattr__(table).query('SELECT Id FROM ' + table)
    
    result = SOQL("Account")
    

    I added a return cause I figured you'll want the result (I realize this is probably a minimal example but still).

    Why this works:

    Basically, behind the scenes, when you call sf.bulk.Account, python is calling sf.bulk.__getattr__("Account") for you. (that's a long story made short; dig more into python and into the linked source code for more)