You need to sign in to do that
Don't have an account?
Diwakar G 7
Reading the body of Attachment using Python
Hi,
I am trying to read the body of attachment and writing in a text file using Python. Below is the sample code.
Thanks and Regards,
Diwakar G
I am trying to read the body of attachment and writing in a text file using Python. Below is the sample code.
import urllib import requests import base64 import json from simple_salesforce import Salesforce import urllib.request as urllib instance = '' sf = Salesforce(username='username', password='password', security_token='security_token') sessionId = sf.session_id attachment = sf.query("SELECT id, name,Body FROM Attachment where parentID =''") body = "" req = urllib.Request('https://%s.salesforce.com/services/data/v38.0/sobjects/Attachment/<id>/Body/' % instance, headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % sessionId }) f = urllib.urlopen(req) f1 = open("demofile.txt", "wb") for x in f: f1.write(x) f.close() f1.close()But, I am getting below error.
f1.write(x) TypeError: write() argument must be str, not bytesPlease correct me, if something is wrong.
Thanks and Regards,
Diwakar G
f1.write(response.content) for binary content.
All Answers
The urlopen.urlOpen will return byte object. you need to change it urllib.ourlopen(req).read().decode('utf-8')
Let me know how it goes.
Below is the output of print(response.text) Along with that I am getting below error. Thanks and Regards,
Diwakar G
I am getting the below error.
Thanks and Regards,
Diwakar G
f1.write(response.content) for binary content.
The attachment body is read as binary data, and we open the file in binary write mode ('wb') using open.
We loop through the attachments fetched from Salesforce and download each attachment's body, saving it with the name specified in the 'Name' field.
Make sure to replace <your_instance_url> with your Salesforce instance URL and <your_parent_id> with the appropriate ParentId for the attachments you want to retrieve. Answer copied from https://codingspell.com/