从Django应用程序在Salesforce中创建ContentVersion

2024-10-03 11:20:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些用户上传到Django应用程序的InMemoryUploadedFile。 在Salesforce中创建ContentVersion对象时,我需要将这些文件中用base 64编码的数据作为VersionData传递

如果我传入示例数据,比如fileData=base64.b64encode(b“testing”),那么一切都正常。 问题是试图从Django的InMemoryUploadedFile读取/编码数据

如果我过去 base64.b64encode(files[file].file.read())由于VersionData(files[file]是InMemoryUploadedFile-我正在遍历每一个文件),它给了我“bytes对象不是JSON可序列化的”错误。如果我传入该文件的字符串版本:str(base64.b64encode(files[file].file.read()),那么该文件将被上载,但内容是乱七八糟的(也称为字节字符串)

如何格式化InMemoryUploadedFile,使其能够正确地将文件内容传递给REST API调用

更多完整代码(如果有帮助):

 def postFilesToDB(self, docRecords, files):
        
        payloadDict = {'passport_picture': { "name":"Passport Picture", "path":"", "data": None},
                       'teudat_oleh': { "name":" Teudat Oleh", "path":"", "data": None },
                       'tzav_giyus': { "name":"Tzav Giyus", "path":"", "data": None },
                       'teudat_boded': { "name":"Teudat Boded", "path":"", "data": None },
                       }

        docTypeToPayloadEntry = {
            'Passport Photo Scan': 'passport_picture',
            'Teudat Oleh/Zakaut': 'teudat_oleh',
            'Teudat Oleh/Zakaut - LSP Countries': 'teudat_oleh',
            'Tzav Giyus': 'tzav_giyus',
            'Teudat Boded': 'teudat_boded'
        }

        for file in files:
            payload = payloadDict[file]
            payload["path"] = files[file].name 
            payload["data"] = base64.b64encode(files[file].file.read())

        #if status is missing, create files
        for i in range(len(docRecords)):
            fileType = docTypeToPayloadEntry[docRecords[i]['Document_Type__r']['Name']]
            if docRecords[i]['Document_Status__c'] == 'Missing' and payloadDict[fileType]["data"] != None:
                ContentDocIdresult = self.createFile(payloadDict[fileType]["name"], payloadDict[fileType]["path"], payloadDict[fileType]["data"])
                #Link file to Documents record
                result = self.sf_api_call('/services/data/v50.0/sobjects/ContentDocumentLink', method="post", data={"ContentDocumentId": ContentDocIdresult['records'][0]['ContentDocumentId'], "LinkedEntityId": docRecords[i]['Id'], "Visibility": "AllUsers"})
                print(result)

    def createFile(self, title, path, data):
       #fileData = base64.b64encode(b"testing") #change the file into base64 encoding using base64.b64encode(files[file])
       fileData = str(data)
       contentVersionResult = self.sf_api_call('/services/data/v50.0/sobjects/ContentVersion', method="post", data={"Title": title, "PathOnClient": path, "ContentLocation": "S", "VersionData": fileData, "OwnerId": '0054J000004swPKQAY'})
       
       ContentDocIdresult = self.sf_api_call('/services/data/v50.0/query/',  {'q': f"SELECT ContentDocumentId FROM ContentVersion where id='{contentVersionResult['id']}'"})
       return ContentDocIdresult

Tags: 文件pathnameselfnonedatafilesfile