Skip to main content
 首页 » 编程设计

python之使用 simple-salesforce python 上传多个文件

2025年04月02日9rubylouvre

我开始学习 SalesForce 并使用 django 开发应用程序。

我需要帮助将文件上传到 salesforce,为此我阅读了 simple-salesforce和 this这有助于使用 rest 和 SOAP api 上传文件。

我的问题是如何使用 simple-salesforce 上传一个或多个文件?

请您参考如下方法:

这是我用来上传文件的代码块。

def load_attachments(sf, new_attachments): 
    ''' 
        Method to attach the Template from the Parent Case to each of the     children. 
        @param: new_attachments the dictionary of child cases to the file name of the template 
    ''' 
    url = "https://" + sf.get_forced_url() + ".my.salesforce.com/services/data/v29.0/sobjects/Attachment/" 
    bearer = "Bearer " + sf.get_session_id() 
    header = {'Content-Type': 'application/json', 'Authorization': bearer} 
 
    for each in new_attachments: 
        body = "" 
        long_name = str(new_attachments[each]).split(sep="\\") 
        short_name = long_name[len(long_name) - 1] 
        with open(new_attachments[each], "rb") as upload: 
            body = base64.b64encode(upload.read()) 
        data = json.dumps({ 
                           'ParentId': each, 
                           'Name': short_name, 
                           'body': body 
                          }) 
        response = requests.post(url, headers=header, data=data) 
        print(response.text) 

基本上,要发送文件,您需要使用请求模块并通过交易后提交文件。 post 事务需要请求发送到的 URL、 header 信息和数据。

这里,sf 是 simple-salesforce 初始化返回的实例。由于我的实例使用自定义域,我必须在 simple-salesforce 中创建自己的函数来处理它;我称之为 get_forced_url()。注意:根据您使用的版本,URL 可能会有所不同 [v29.0 部分可能会更改]。

然后我设置我的 bearer 和 header。

接下来是一个循环,它为从父 ID 到我希望上传的文件的映射中的每个附件提交一个新附件。请务必注意,附件必须具有父对象,因此您需要知道 ParentId。对于每个附件,我都会清空正文,为附件创建一个长名称和短名称。然后是重要的部分。在附件中,文件的实际数据存储为 base-64 二进制数组。所以文件必须以二进制形式打开,因此是“rb”,然后编码为 base-64。

一旦文件被解析为 base-64 二进制文件,我将构建我的 json 字符串,其中 ParentId 是父对象的对象 ID,Name 是短名称,body 是 base-64 编码的数据字符串.

然后将文件连同标题和数据提交到 URL。然后我打印响应,这样我就可以看到它发生了。