Как написать для l oop для динамического вызова значений в функции? - PullRequest
0 голосов
/ 17 апреля 2020

У меня есть пара таблиц, через которые я хочу выполнить свои функции python; однако мне трудно написать свой сценарий для этого.

Вот моя переменная с таблицами:

object_to_export = ['Opportunity','Asset']

Вот мой код:

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()

Когда я запускаю свой код, получаю ли это сообщение об ошибке:

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'}]

Есть идеи, почему я получаю эту ошибку и исправляю свой скрипт для передачи параметров таблицы моим desc и soql переменным?

Дополнение: я также попытался поместить переменную des c как

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

Но это выдает мне эту ошибку:

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

1 Ответ

1 голос
/ 17 апреля 2020
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()

вам нужно использовать getattr (obj, name_of_member), посмотреть строку с комментарием

и пример:

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 
...