Python multipart / form-data请求错误:数据不能是字符串

时间:2018-05-31 09:26:19

标签: python multipartform-data

我正在使用文件附件自动发送eamil的python程序。

sendHTML是电子邮件内容。没有附加,它运作良好。

但是,添加以下原始来源等文件会导致错误:数据不能是字符串。 所以,我已经改变了代码,但是它也没有用。 请救救我:(

===============更改了代码============================== ===================

    files = {'json' : (None, json.dumps(sMailBody).encode("utf-8"), 'application/json' ),'file': (open('''20180430_'18 Tizen Store Buyer Report v2.4.xlsx''', 'rb'), 'application/octet-stream')}
    headers = {'authorization': 'Bearer xx',  "Content-Type" : "multipart/form-data"}
    res = requests.post(url, headers=headers, files=files)

===================来源========================

sendHTML = str(fullReportFrameSoup)                                    -
url = "the url of samsung"
sMailBody = {         
--> this is my company mail system's  Rest API                                                       
   "resourceVO" :
   {
   "email" : "xxx@samsung.com",
           "localeStr" : "ko_KR",
            "encoding" : "utf-8",
            "timeZone" : "GMT+9",
        },
    "sendMailVO" :
        {
            "contentText" : sendHTML,
            "subject" : "[Tizen Store] 일일통계",
            "docSecuType" : "PERSONAL",
            "contentType" : "HTML",
            "from" :
                   {
                    "email" : "xxx@samsung.com"
                   },
            "attachs" :[],
            "recipients" :
                [
                   {
                        "email" : "xxx@samsung.com",
                        "recipientType" : "TO"
                    }
                ]
        }
}



json_data = json.dumps(sMailBody).encode("utf-8")
files = {'file': ('''20180430_'18 Tizen Store Buyer Report v2.4.xlsx''', open('''20180430_'18 Tizen Store Buyer Report v2.4.xlsx''', 'rb') , 'application/vnd.ms-excel', {'Expires': '0'})}-->  
headers = {'authorization': 'Bearer xxx', "Content-Type" : "application/json"}
res = requests.post(url, data=json_data, headers=headers, files=files)

1 个答案:

答案 0 :(得分:0)

尝试在json参数中将JSON有效负载(sMailBody)作为dict传递:

headers = {'authorization': 'Bearer d7a71dbb2d2cb6cd9f70126a926f6a4c',  "Content-Type" : "multipart/form-data"}
files = {'file': open('1', 'rb')}
res = requests.post(url, json=sMailBody, headers=headers, files=files)