【问题标题】:salesforce api call returns too many responses within for loop in PythonSalesforce api调用在Python的for循环中返回太多响应
【发布时间】:2020-04-29 17:32:00
【问题描述】:

我正在调用 Salesforce 批量 API 来获取数据。我正在使用 simple_salesforce 库。我想获取我的 id 等于特定值的数据,我还需要返回一些响应,因为我有一个 id 列表。我的数据如下所示:

ids_dict = [{'ID-1010': 'abc'}, {'ID-1020': 'def'}]

代码如下:

for key, value in ids_dict.items():
    desired_opp = value
    sql = sf.bulk.OpportunityLineItem.query("SELECT Name, Price FROM OpportunityLineItem where Opportunity_ID__c = '%s'" % desired_opp)
    sql_response = []
    sql_response.append(sql)

返回的是一个包含多个响应的列表,其 ID 为 def。对于尊重的身份,我只需要两个响应。

【问题讨论】:

标签: python sql for-loop salesforce simple-salesforce


【解决方案1】:

根据我的经验,我发现最好使用 sf.query(query=SOQL) 并使用 sf.query_more(next_URL, True) 来获取其余记录

由于查询只返回2000条记录,需要使用.query_more()获取更多记录

来自simple-salesforce docs

SOQL 查询通过以下方式完成:

sf.query("SELECT Id, Email FROM Contact WHERE LastName = 'Jones'")

如果由于结果特别大,Salesforce 会在您的查询结果中添加 nextRecordsUrl,例如 "nextRecordsUrl" : "/services/data/v26.0/query/01gD0000002HU6KIAW -2000",您可以使用 ID 或完整 URL 提取附加结果(如果使用完整 URL,则必须传递 'True' 作为第二个参数)

sf.query_more("01gD0000002HU6KIAW-2000")
sf.query_more("/services/data/v26.0/query/01gD0000002HU6KIAW-2000", True)

也许您还想更改您的 sql 语句以使用“in”而不是“=”来选择它可以一次等于的多个值。这样,在您请求更多记录之前,您只需向 salesforce 进行一次 API 调用。 (消除多次少于 2000 条记录搜索的浪费调用)

这是一个使用这个的例子

 data = [] # list to hold all the records

 SOQL = "SELECT Name, Price FROM OpportunityLineItem where Opportunity_ID__c in ('abc', 'def')"

 results = sf.query(query=SOQL) # api call

 ## loop through the results and add the records
 for rec in results['records']:
     rec.pop('attributes', None) # remove extra data
     data.append(rec) # add the record to the list


 ## check the 'done' attrubite in the response to see if there are more records
 ## While 'done' == False (more records to fetch) get the next page of records
 while(results['done'] == False):
     ## attribute 'nextRecordsUrl' holds the url to the next page of records
     results = sf.query_more(results['nextRecordsUrl', True])

     ## repeat the loop of adding the records
     for rec in results['records']:
         rec.pop('attributes', None)
         data.append(rec)

遍历记录并使用数据

 ## loop through the records and get their attribute values
 for rec in data:
     # the attribute name will always be the same as the salesforce api name for that value
     print(rec['Name'])
     print(rec['Price'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2015-12-30
    • 2015-02-24
    • 2019-04-28
    • 1970-01-01
    • 2019-07-31
    • 2018-11-18
    相关资源
    最近更新 更多