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

Jay*_*har 6 python django salesforce simple-salesforce

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

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

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

Rob*_*vis 3

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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

然后我设置了承载者和标题。

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

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

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