How to fetch Salesforce Attachment file content with django-salesforce?

ぃ、小莉子 提交于 2019-12-10 11:55:37

问题


I'm developing a Django 1.11 app serving as a UI for some Salesforce Objects using django-salesforce for the communication with Salesforce.

I have to give users the option to download files from Salesforce Attachment objects related to their Contact.

# Django Attachment model on my_app/models.py

...

class Attachment(models.Model):
    parent = models.ForeignKey(Contact, models.DO_NOTHING,
                               sf_read_only=models.NOT_UPDATEABLE)
    name = models.CharField(max_length=255, verbose_name='File Name')
    content_type = models.CharField(max_length=120, blank=True, null=True)
    body_length = models.IntegerField(sf_read_only=models.READ_ONLY)
    body = models.TextField()

...

On this Attachment model I can access the rest URL for the file content on the body field, but not the actual content.

Is there a way of getting file content from the Attachment without having to implement an OAuth client just for this?


回答1:


A) by REST API request encapsulated by handle_api_exceptions

from salesforce.backend.driver import handle_api_exceptions
# from salesforce.dbapi.driver import handle_api_exceptions  # can be changed soon to this
from django.db import connections

session = connections['salesforce'].sf_session
rows = Attachment.objects.filter(...)
for row in rows:
    url = session.auth.instance_url + row.body
    blob = handle_api_exceptions(url, session.get).text

B) You can get SOAP client (requires Beatbox) by

from salesforce.utils import get_soap_client
import base64

soap = get_soap_client('salesforce')
for ...:
    ret = soap.query("SELECT Body FROM Attachment WHERE Id = '...'")
    blob = base64.b64decode(ret)[0]['Body'])

Useful related answers are:

  • How to get files from Salesforce using Python
  • Uploading Attachments to Salesforce API via Beatbox, Python

EDIT I expect that you mean User = some Contact, not a Contact necessarily related to SFDC object User with some form of paid license. They should download only through your site, not directly, for security reasons. Any OAuth can not probably improve it.



来源:https://stackoverflow.com/questions/46034754/how-to-fetch-salesforce-attachment-file-content-with-django-salesforce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!