Source Code:
from pprint import pprint
import json
import os
import requests
import pandas as pd
from simple_salesforce import Salesforce, SalesforceLogin, SFType
username = '<username>'
password = '<password>'
security_token = '<security_token>'
domain = 'login' # or test
session_id, instance = SalesforceLogin(username=username, password=password, security_token=security_token, domain=domain)
sf = Salesforce(instance=instance, session_id=session_id)
# querySOQL = """
# SELECT Id, Name, ParentId, Body
# From Attachment
# WHERE ParentId IN (SELECT Id FROM Project__c)
# """
# query records method
response = sf.query(querySOQL)
lstRecords = response.get('records')
nextRecordsUrl = response.get('nextRecordsUrl')
while not response.get('done'):
response = sf.query_more(nextRecordsUrl, identifier_is_url=True)
lstRecords.extend(response.get('records'))
nextRecordsUrl = response.get('nextRecordsUrl')
df_records = pd.DataFrame(lstRecords)
"""
Download files
"""
instance_name = sf.sf_instance
folder_path = '.\Attachments Download'
for row in df_records.iterrows():
record_id = row[1]['ParentId']
file_name = row[1]['Name']
attachment_url = row[1]['Body']
if not os.path.exists(os.path.join(folder_path, record_id)):
os.mkdir(os.path.join(folder_path, record_id))
request = sf.session.get('https://{0}{1}'.format(instance_name, attachment_url), headers=sf.headers)
with open(os.path.join(folder_path, record_id, file_name), 'wb') as f:
f.write(request.content)
f.close()
Hello. Thank you for the explanation of the code. I am trying to implement this and I currently do not get any python errors and the PDF is saved in my downloads folder but when I try to open the file it shows an error “We can’t open this file” & “Something went wrong” and it shows that the file weighs 1kb when it actually weighs 289KB. Can you please help me to see why might be going on?