本文整理汇总了Python中simple_salesforce.Salesforce.query_all方法的典型用法代码示例。如果您正苦于以下问题:Python Salesforce.query_all方法的具体用法?Python Salesforce.query_all怎么用?Python Salesforce.query_all使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simple_salesforce.Salesforce
的用法示例。
在下文中一共展示了Salesforce.query_all方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prettyQuery
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def prettyQuery(query):
"""prints JSON of SOQL query. For convenience console use."""
sf = Salesforce(username=config.username,
password=config.password,
security_token=config.security_token)
raw = sf.query_all(query)
pretty = jsonizer(raw)
print pretty
return pretty
示例2: main
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def main(argv):
from simple_salesforce import Salesforce
from simple_salesforce.util import date_to_iso8601 as iso
from datetime import datetime, timedelta
from secret import *
import pytz
print 'running...'
inputfile = 'C:\Users\mivinson\workspace\SFDC Data Connection\sfdcDataConnection\\accountSelect.sql'
# parameter = ''
startDate = datetime(2014,11,12,0,0,0, tzinfo=pytz.UTC)
endDate = datetime(2014,11,12,0,0,0, tzinfo = pytz.UTC)
print startDate
print endDate
delta = endDate - startDate
# desc = ''
# try:
# opts, args = getopt.getopt(argv,"hi:p:s:e:d:",["ifile=","param=","sDate=","eDate=","desc="])
# except getopt.GetoptError:
# print '-i <inputfile> -p whereParameter -s startDate -e endDate -d describe(Object)'
# sys.exit(2)
# for opt, arg in opts:
# if opt == '-h':
# print '-i <inputfile>\n-p where Parameter'
# sys.exit()
# elif opt in ("-i", "--ifile"):
# inputfile = arg
# elif opt in ("-s", "--sDate"):
# startDate = arg
# elif opt in ("-e", "--eDate"):
# endDate = arg
# elif opt in ("-p","--param"):
# parameter = arg
# elif opt in ("-d","--desc"):
# desc = arg
## elif opt in ("-o", "--ofile"):
## outputfile = arg
# print 'Input file is ', inputfile
# print 'Output file is "', outputfile
f = file(inputfile,'r')
select = f.read()
sf = Salesforce(username = USER, password = PASSWORD,security_token=HKEY)
#
for i in range(delta.days + 1):
iSelect = select.replace(':Start',(startDate + timedelta(days=i)).strftime('%Y-%m-%dT%H:%M:%SZ'))
iSelect = iSelect.replace( ':End',(startDate + timedelta(days=i+1) + timedelta(microseconds=-1)).strftime('%Y-%m-%dT%H:%M:%SZ'))
print iSelect
req = sf.query_all(iSelect)
print req
示例3: sync_country_data
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def sync_country_data(self, request, queryset):
for setting in queryset:
rows_updated = queryset.update(
sync_country_date = timezone.now(),
)
if setting.sf_active == True:
sfusername = setting.sf_username
sfpassword = setting.sf_password
sftoken = setting.sf_token
sftype = setting.sf_type
if sftype == 'Production':
sftypesetup = False
else:
sftypesetup = True
cursor = connection.cursor()
salesforce_login = {'username':sfusername, 'password':sfpassword, 'security_token':sftoken, 'sandbox':sftypesetup}
sf = Salesforce(**salesforce_login)
countries = sf.query_all("SELECT Id, Name, Programme_Launch__c FROM Country__c where Programme_Launch__c!=''")
for x in countries["records"]:
countryname = str(x["Name"])
sfrecordid = str(x["Id"])
launch = str(x["Programme_Launch__c"])
slug = str(x["Name"]).replace(" ","-").replace("/","-").replace(".","-").lower()
try:
add_objects = ("INSERT INTO data_country "
"(name,sfid,launch,slug) "
"VALUES (%(name)s,%(sfid)s,%(launch)s,%(slug)s)")
data_objects = {
'name' : countryname,
'sfid' : sfrecordid,
'launch' : launch,
'slug' : slug,
}
cursor.execute(add_objects,data_objects)
except:
add_objects = ("UPDATE data_country "
"SET name=%(name)s,sfid=%(sfid)s,launch=%(launch)s,slug=%(slug)s "
"WHERE sfid=%(sfid)s")
data_objects = {
'name' : countryname,
'sfid' : sfrecordid,
'launch' : launch,
'slug' : slug,
}
cursor.execute(add_objects,data_objects)
self.message_user(request, "Your Countries have been syncronised")
示例4: SalesforceService
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
class SalesforceService():
error_msg = None
topLevel = None
sf = None
def __init__(self, username, password, token, topLevel):
self.topLevel = topLevel
try:
self.sf = Salesforce(username=username, password=password, security_token=token)
except:
self.error_msg = "Invalid Salesforce credentials"
if not self.sf:
self.error_msg = "Invalid Salesforce credentials"
else:
ConfigManager().cache_sf_creds(username, password, token)
scholars = self.query_sf_scholars()
if scholars is None or not scholars:
self.error_msg = "No scholars returned from query"
else:
threading.Thread(target=self.async_process_data, args=(scholars,)).start()
def query_sf_scholars(self):
""" Queries Salesforce for scholars using query provided in config file.
Formats scholars as tuple expected by scholarscraper """
cfg_mgr = ConfigManager()
query = cfg_mgr.sf_select_scholars_query()
sf_obj_id_name = cfg_mgr.get_sf_account_id_name()
scholars = []
try:
query_result = self.sf.query_all(query)
records = query_result['records']
if not records:
msg = "No scholars returned from Salesforce query:\n{}".format(query)
ErrorLogService().log_error(msg, "High")
else:
for scholar in records:
scholar_info = (scholar["Google_Scholar_ID__c"],
{sf_obj_id_name: scholar["Id"]})
scholars.append(scholar_info)
except:
ErrorLogService().log_error("Error querying Salesforce",
"High", traceback.format_exc())
return scholars
def async_process_data(self, scholars):
""" Thread function to call scholar scraper """
results = scholarscraper.scraperEntry(scholars)
self.topLevel.processing_complete(results, self.error_msg)
示例5: user_id
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def user_id(self):
if not self.config.get('user_id'):
sf = Salesforce(
instance=self.instance_url.replace('https://', ''),
session_id=self.access_token,
version='38.0',
)
result = sf.query_all(
"SELECT Id FROM User WHERE UserName='{}'".format(
self.username
)
)
self.config['user_id'] = result['records'][0]['Id']
return self.config['user_id']
示例6: get_cases
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def get_cases(self, environment='staging',
type='01250000000Hnex',
status='In Progress',
sub_status='In Development',
technician=''):
""" Get helpdesk tickets for the respective que 100 at a time.
:return: OrderedDict that contains totalsize, done, and records. Records in turn is also given as an
OrderedDict with the actualrecords data.
"""
user_name, pw, token = auth.sfdc_login(environment)
sf = Salesforce(username=user_name, password=pw, security_token=token)
result = sf.query_all(self.build_query())
print result
return result
示例7: getTableData
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def getTableData(self,sObject):
sf = Salesforce(instance_url=self.instance_url, session_id=self.session_id)
session_id = sf.session_id
instance = sf.sf_instance
query = "Select "
sObjectName = SFType(sObject,session_id,instance)
for x in sObjectName.describe()['fields']:
query = query + x['name'] + ","
query = query[:-1] + " from " + sObjectName.name
#print query
res = sf.query_all(query)
records = res['records']
ls = []
adapter = mongoadapter.adapter()
collection = adapter.createColletion(sObject)
for x in records:
data = {}
for y in sObjectName.describe()['fields']:
data[y['name']] = x[y['name']]
#print data
#print data
ls.append(adapter.insert_posts(collection, data))
return ls
示例8: _salesforce_import
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def _salesforce_import(self, session_id, instance, user, user_company):
#print session_id, instance, user, user_company
#SESSION_ID = "00Dj0000001neXP!AQUAQIbUn9RsdTZH6MbFA7qaPtDovNU75.fOC6geI_KnEhJKyUzk2_yFx2TXgkth7zgFuJThY6qZQwH7Pq4UtlcW.Cq0aHt1"
print instance
print instance.replace("https://","")
sf = Salesforce(instance=instance.replace("https://",""),
session_id=session_id)
lol = sf.query_all("SELECT Id, Name, Email FROM Contact")
sf = pd.DataFrame(pd.DataFrame(lol).records.tolist())
sf = sf[["Name","Email"]]
sf.columns = ["name","email"]
sf = sf.dropna()
sf["domain"] = [i.split("@")[-1] if i else "" for i in sf.email]
sf["source"] = "salesforce"
sf["db_type"] = "crm"
sf["user"] = [Parse()._pointer("_User", user) for i in sf.index]
sf["user_company"] = [Parse()._pointer("UserCompany",user_company)
for i in sf.index]
Parse()._batch_df_create("UserContact", sf)
Prospecter()._batch_df_create("UserContact", sf)
print Prospecter().update("_User/"+user,
{"salesforce_integration":arrow.utcnow().timestamp,
"salesforce_token":session_id}).json()
示例9: index
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def index(request):
"""
When this view is loaded in a canvas app, Salesforce sends a POST request to it containing the
currently logged in user's data.
This post data contains a base64 string of the user's data, along with a signature. We can validate
the signature by comparing it to our own generated expected signature from our Salesforce
application's secret key.
The result of parsing the signed request is that we obtain an instance_url and oauth_token we
can use to query the Salesforce API. Feel free to dive into the parse_signed_request() function
to see the nitty-gritty details.
"""
data = parse_signed_request(request.POST['signed_request'], settings.SALESFORCE_CONSUMER_SECRET)
if data:
#User authenticated, let's do queries!
#Create a simple salesforce instance, using our newly obtained instance_url and oauth_token for authentication.
sf = Salesforce(instance_url=data['client']['instanceUrl'], session_id=data['client']['oauthToken'])
#execute a query
stats = {}
for opp in sf.query_all("SELECT LeadSource FROM Opportunity WHERE IsWon = True")['records']:
if opp['LeadSource'] not in stats:
stats[opp['LeadSource']] = 0
stats[opp['LeadSource']] += 1
results = []
for lead_source,total in stats.items():
results.append({"lead_source": lead_source, "total": total})
results = sorted(results, key=lambda k: k['total']*-1) #sort results by total
else:
#invalid signed request, throw error.
pass
return render(request, 'index.html', {
"results": results
})
示例10: getLeadsList
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def getLeadsList(sf, sfCred, audience):
try:
# response = sf.query_all("SELECT Email FROM Lead WHERE Email <> ''")
response = sf.query_all(audience['sql_query']) # Use query stored in db
except Exception, e:
if e.status == 401:
SALESFORCE_REFRESH_URL = "https://login.salesforce.com/services/oauth2/token"
SALESFORCE_CONSUMER_KEY = sfCred['consumer_key'] #"3MVG98_Psg5cppyYH7Cios03svOf9hpZtPg.n0yTXRIKlnjy43.MNRgdLDbmBc3T5wK2IoYOaPLNlqBzNouzE"
SALESFORCE_CONSUMER_SECRET = sfCred['consumer_secret'] #"2132402812325087889"
salesforce_refresh_token = sfCred['refresh_token']
# HTTP request
url = SALESFORCE_REFRESH_URL
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + sfCred['access_token'],
'X-PrettyPrint': '1'
}
params = {'grant_type': 'refresh_token',
'client_id': SALESFORCE_CONSUMER_KEY,
'client_secret': SALESFORCE_CONSUMER_SECRET,
'refresh_token': salesforce_refresh_token }
result = requests.get(url, headers=headers, params=params)
newSfCred = json.loads(result.content)
sfCred['instance_url'] = newSfCred['instance_url']
sfCred['access_token'] = newSfCred['access_token']
sfCred['signature'] = newSfCred['signature']
sfCred['id'] = newSfCred['id']
sfCred['issued_at'] = newSfCred['issued_at']
db.pushSalseforceCredentials(sfCred)
# try with new token
sf = Salesforce(instance_url=sfCred['instance_url'], session_id=sfCred['access_token'])
# response = sf.query_all("SELECT Email FROM Lead WHERE Email <> ''")
response = sf.query_all(audience['sql_query']) # Use query stored in db
示例11: getTableData
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def getTableData(self,*args):
sf = Salesforce(username=self.username, password=self.password, security_token=self.security_token)
session_id = sf.session_id
instance = sf.sf_instance
query = "Select "
#session_id, instance = SalesforceLogin(self.username, self.password, self.security_token, True)
for sObject in args:
sObjectName = SFType(sObject,session_id,instance)
for x in sObjectName.describe()['fields']:
query = query + x['name'] + ","
query = query[:-1] + " from " + sObjectName.name
print query
res = sf.query_all(query)
records = res['records']
ls = []
data = {}
adapter = mongoadapter.adapter()
collection = adapter.createColletion(sObject)
for x in records:
for y in sObjectName.describe()['fields']:
data[y['name']] = x[y['name']]
print data
ls.append(adapter.insert_posts(collection, data))
return ls
示例12:
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
#this has the list of ordered dictionaries that describe the fields
table_fields = this_table['fields']
#list comprehension style
field_names = []
[field_names.append(item['name']) for item in table_fields]
all_tables[i] = field_names
# #non list comprehension style, fro reference
# field_names = []
# for item in table_fields:
# field_names.append(item['name'])
for i in all_tables:
this_fields = all_tables[i]
sql = "SELECT " + ",".join(this_fields) + " FROM " + i
print "Getting table %s from Salesforce DB." % i
sf_result = sf.query_all(sql)
sf_df = DataFrame.from_dict(sf_result['records'], orient='columns', dtype=float)
# drop attributes column if it exists, if not then pass
try:
sf_df.drop('attributes', axis = 1, inplace = True)
except:
pass
# load table to database
print "loading table %s into Silo." % i
databaseconfig.create_sf_table(engine=engine, conn=conn, tablename= i, df=sf_df)
print "Done!"
示例13: __init__
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
class RFCReport:
def __init__(self):
print "Logging in to Salesforce API..."
# initialize our SFDC connection
self.sf = Salesforce(username=config.username,
password=config.password,
security_token=config.security_token)
self.caseData = None
self.reportData = dict()
self.fulltable = ''
self.outputDict = dict()
self.sorted_list = list()
print "Login successful."
def getData(self, initString, query, checkFields, exitString):
""" Generalized case data querying function.
Returns nested dict/list structure corresponding to SOQL output.
Query should be a SOQL query. See nestedGet for checkFields format."""
print initString
data = self.sf.query_all(query)
output = json.loads(jsonizer(data))
lengthset = set()
for change in output["records"]:
lengthset.add(nestedGet(checkFields, change))
totalcase = len(lengthset)
print "Got", totalcase, exitString
return output
def genReport(self, data):
"""deduplicate gathered case data"""
dupecount = 0
output = dict()
for change in data["records"]:
for line in change["FeedTrackedChanges"]["records"]:
if line is not None:
if line["NewValue"] in (
"Ready For Close",
"Closed",
"Cancelled",
"Closed as Duplicate"):
caseid = nestedGet(["Parent", "CaseNumber"], change)
changedate = dateparser.parse(change["CreatedDate"])
# need to account for >1 escalation per case
if caseid in output:
# chronological order - latest gets it
if output[caseid]["Date"] > changedate:
dupecount += 1
continue
if nestedGet(["Parent", "Cancel_Effective_Date__c"],
change) is not None:
teardown = True
else:
teardown = False
output[caseid] = frozendict(
Name=nestedGet(["CreatedBy", "Name"], change),
Case=caseid,
Status=line["NewValue"],
Teardown=teardown,
Date=changedate)
print "Found and removed", dupecount, "cases handled more than once."
print "Credit for duplicates given to latest resolver."
return output
def tabulateReport(self):
"""tabulates case data per team member"""
print "Reticulating splines..."
listedUsers = [TeamMember(y) for y in
set([x["Name"] for x in self.reportData.itervalues()])]
print "Generating summaries..."
for case in self.reportData.itervalues():
name = case["Name"]
nameobj = (filter(lambda z: z.name == name, listedUsers))[0]
nameobj.caseCount.add(case)
if case["Status"] == "Ready For Close":
nameobj.closedCount.discard(case)
nameobj.rfcCount.add(case)
if case["Status"] in (
"Closed",
"Cancelled",
"Closed as Duplicate"):
nameobj.closedCount.add(case)
nameobj.rfcCount.discard(case)
if case["Teardown"]:
nameobj.tdCount.add(case)
nameobj.rfcCount.discard(case)
nameobj.closedCount.discard(case)
self.sorted_list = sorted(listedUsers,
key=lambda q: len(q.caseCount),
reverse=True)
@property
def dataToJSON(self):
cutoff = ''
if config.closedOnly:
cutoff = "resolved cases only"
d = [x["Date"] for x in self.reportData.itervalues()]
dates = ' - '.join(
[x.strftime("%B %d, %Y") for x in (min(d), max(d))])
drange = ' '.join(
["current" if x == "this" else x for x in
#.........这里部分代码省略.........
示例14: run_tests
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
def run_tests():
username = os.environ.get('SF_USERNAME')
password = os.environ.get('SF_PASSWORD')
serverurl = os.environ.get('SF_SERVERURL')
test_name_match = os.environ.get('APEX_TEST_NAME_MATCH', '%_TEST')
test_name_exclude = os.environ.get('APEX_TEST_NAME_EXCLUDE', '')
namespace = os.environ.get('NAMESPACE', None)
poll_interval = int(os.environ.get('POLL_INTERVAL', 10))
debug = os.environ.get('DEBUG_TESTS',False) in ['true','True']
debug_logdir = os.environ.get('DEBUG_LOGDIR')
json_output = os.environ.get('TEST_JSON_OUTPUT', None)
junit_output = os.environ.get('TEST_JUNIT_OUTPUT', None)
if namespace:
namespace = "'{0}'".format(namespace,)
else:
namespace = 'null'
sandbox = False
if serverurl.find('test.salesforce.com') != -1:
sandbox = True
sf = Salesforce(username=username, password=password, security_token='', sandbox=sandbox, sf_version='32.0')
# Change base_url to use the tooling api
sf.base_url = sf.base_url + 'tooling/'
# Split test_name_match by commas to allow multiple class name matching options
where_name = []
for pattern in test_name_match.split(','):
if pattern:
where_name.append("Name LIKE '{0}'".format(pattern))
# Add any excludes to the where clause
where_exclude = []
for pattern in test_name_exclude.split(','):
if pattern:
where_exclude.append("(NOT Name LIKE '{0}')".format(pattern,))
# Get all test classes for namespace
query = "SELECT Id, Name FROM ApexClass WHERE NamespacePrefix = {0}".format(namespace,)
if where_name:
query += " AND ({0})".format(' OR '.join(where_name),)
if where_exclude:
query += " AND {0}".format(' AND '.join(where_exclude),)
print "Running Query: {0}".format(query,)
sys.stdout.flush()
res = sf.query_all(query)
print "Found {0} classes".format(res['totalSize'],)
sys.stdout.flush()
if not res['totalSize']:
return {'Pass': 0, 'Fail': 0, 'CompileFail': 0, 'Skip': 0}
classes_by_id = {}
classes_by_name = {}
trace_id = None
results_by_class_name = {}
classes_by_log_id = {}
logs_by_class_id = {}
for cls in res['records']:
classes_by_id[cls['Id']] = cls['Name']
classes_by_name[cls['Name']] = cls['Id']
results_by_class_name[cls['Name']] = {}
# If debug is turned on, setup debug traces for all test classes
if debug:
print 'Setting up trace flag to capture debug logs'
# Get the User's id to set a TraceFlag
res_user = sf.query("Select Id from User where Username = '{0}'".format(username,))
user_id = res_user['records'][0]['Id']
# Set up a simple-salesforce sobject for TraceFlag using the tooling api
TraceFlag = sf.TraceFlag
TraceFlag.base_url = (u'https://{instance}/services/data/v{sf_version}/tooling/sobjects/{object_name}/'
.format(instance=sf.sf_instance,
object_name='TraceFlag',
sf_version=sf.sf_version))
# First, delete any old trace flags still lying around
tf_res = sf.query('Select Id from TraceFlag')
if tf_res['totalSize']:
for tf in tf_res['records']:
TraceFlag.delete(tf['Id'])
expiration = datetime.datetime.now() + datetime.timedelta(1)
res = TraceFlag.create({
'ApexCode': 'Info',
'ApexProfiling': 'Debug',
'Callout': 'Info',
'Database': 'Info',
'ExpirationDate': expiration.isoformat(),
#'ScopeId': user_id,
'System': 'Info',
'TracedEntityId': user_id,
#.........这里部分代码省略.........
示例15: SalesforceOutputService
# 需要导入模块: from simple_salesforce import Salesforce [as 别名]
# 或者: from simple_salesforce.Salesforce import query_all [as 别名]
class SalesforceOutputService():
error_msg = None
topLevel = None
sf = None
def __init__(self, username, password, token, results, topLevel):
self.topLevel = topLevel
try:
self.sf = Salesforce(username=username, password=password, security_token=token)
except:
self.error_msg = "Invalid Salesforce credentials"
return
if not self.sf:
self.error_msg = "Invalid Salesforce credentials"
else:
try:
ConfigManager().cache_sf_creds(username, password, token)
threading.Thread(target=self.async_update_sf, args=(results,)).start()
except:
ErrorLogService().log_error("An error occurred, see log file for more information",
"High", traceback.format_exc())
def async_update_sf(self, results):
""" Thread function to update salesforce with results """
self.update_sf_helper(results)
self.topLevel.processing_complete("")
def update_sf_helper(self, results):
""" Updates Account and PRJ__c in salesforce """
cfg_mgr = ConfigManager()
sf_obj_id_name = cfg_mgr.get_sf_account_id_name()
sf_article_id_name = cfg_mgr.get_sf_article_id_name()
sf_person_obj_lbl = cfg_mgr.get_sf_person_obj_lbl()
sf_article_obj_lbl = cfg_mgr.get_sf_article_obj_lbl()
sf_person_obj = getattr(self.sf, sf_person_obj_lbl)
sf_articles = self.sf.query_all(cfg_mgr.sf_select_PRJs_query())
articles_to_update = {}
for result in results:
try:
if result.external_data is not None and sf_obj_id_name in result.external_data:
sf_id = (result.external_data)[sf_obj_id_name]
stats = result.stats.todict()
if stats is not None:
sf_person_obj.update(sf_id, stats)
articles_dict = self.map_sf_id_to_article(sf_article_id_name, result.articles, sf_articles)
articles_to_update.update(articles_dict)
else:
msg = "{}: Error processing object: {}.\nIs the Salesforce Id missing from the input CSV?".format(
sf_person_obj_lbl, pprint.pformat(result))
ErrorLogService().log_error(msg, "Medium")
self.topLevel.parent.add_error(msg)
except:
ErrorLogService().log_error("Error updating Scholar: {}".format(
pprint.pformat(result)), "High", traceback.format_exc())
try:
self.update_articles(articles_to_update, sf_article_id_name, sf_article_obj_lbl)
except:
ErrorLogService().log_error("Error updating articles",
"High", traceback.format_exc())
def map_sf_id_to_article(self, sf_article_id_name, scholar_articles, sf_articles):
""" Maps the salesforce Id for an article onto Google Scholar articles """
articles_dict = {}
for sf_article in sf_articles['records']:
for scholar_article in scholar_articles:
if sf_article[sf_article_id_name].split(':')[1] == scholar_article.articleid.split(':')[1]:
articles_dict[sf_article['Id']] = scholar_article
return articles_dict
def update_articles(self, articles_dict, article_id_name, sf_article_obj_lbl):
""" Updates PRJ__c objects (articles) in Salesforce """
if articles_dict is None or not articles_dict:
return
sf_article_obj = getattr(self.sf, sf_article_obj_lbl)
for article_id in articles_dict:
article_to_update = (articles_dict[article_id]).to_PRJ_dict()
sf_article_obj.update(article_id, article_to_update)