我正在使用
当我转储原始HTTP请求时,我发现数据没有被编码为
然而,我仍然不明白文件附件头中的
更新2
我不得不这样修改标题:
我在HTTP转储中看到了标题,但我仍然收到
更新3
看起来
requests
进行 HTTP PUT 请求,但是由于某种原因它上传的是原始 ASCII 而不是事先进行 base64 编码的文件。files = {'file': ('mydata.csv', open('mydata.csv', 'rb'))}
...
try:
logging.info("Upload URL: " + insert_upload_url)
headers = {'Content-type': 'multipart/form-data'}
upload_res = requests.put(insert_upload_url, files=files,
data={'insertUpload': data}, headers=headers)
logging.info("Status: " + str(upload_res.status_code))
if upload_res.status_code != requests.codes.ok:
logging.info("Reason: " + upload_res.reason)
else:
logging.info("Response: " + upload_res.text)
except Exception as e:
logging.info("Error: " + e.message)
当我转储原始HTTP请求时,我发现数据没有被编码为
application/octet-stream
,也不是base64编码:PUT /apibatchmember/services/rest/batchmemberservice/G9X7CsNn3HisxFdwAu4W76mBewUkQcKD_limGK1MDZ-eW3-olsn8HW0l5oePvEU_ZwHaPbEz2_c1YonjauDs7Jhk9DGvGNSTLMbgSSY9TGVuk00I_-tKPw8mjoXzC63YsFzBIYIeYXHKf34dYxmmhz4iSeDw/batchmember/insertUpload HTTP/1.1
Host: api.example.com
Content-Length: 5062
Content-type: multipart/form-data
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.2.3 CPython/2.7.5 Darwin/12.5.0
--5f934d42eabb4d7abe8bdef2cea94b6b
Content-Disposition: form-data; name="insertUpload"
<?xml version="1.0" encoding="UTF-8"?>
<insertUpload>
<criteria>LOWER(EMAIL)</criteria>
<fileName>email.csv</fileName>
<separator>,</separator>
<fileEncoding>UTF-8</fileEncoding>
<skipFirstLine>false</skipFirstLine>
<dateFormat>mm/dd/YYYY</dateFormat>
<mapping>
<column>
<colNum>0</colNum>
<fieldName>CUSTNUM</colNum>
<column>
<column>
<colNum>1</colNum>
<fieldName>FIRSTNAME</colNum>
<column>
<column>
<colNum>2</colNum>
<fieldName>LASTNAME</colNum>
<column>
<column>
<colNum>3</colNum>
<fieldName>EMAIL</colNum>
<column>
</mapping>
</insertUpload>
--5f934d42eabb4d7abe8bdef2cea94b6b
Content-Disposition: form-data; name="file"; filename="email.csv"
Content-Type: text/csv
\xef\xbb\xbf1045,Janice,Waddell,blah@example.com
1156,Scott,Sheldon,blah@example.com
1267,Adrianus,Lengkeek,blah@example.com
1295,EDWIN,ODIFE,blah@example.com
1345,Albert,Stephenson,blah@example.com
...
--5f934d42eabb4d7abe8bdef2cea94b6b--
我该如何将text/csv
编码成base64的流呢?
谢谢!
更新
现在我使用以下代码可以得到正确的附件头了:
with open('/Users/mark.richman/email.csv', 'rb') as fd:
b64data = base64.b64encode(fd.read())
files = {'file': ('email.csv', b64data, 'application/octet-stream')}
然而,我仍然不明白文件附件头中的
Content-Transfer-Encoding: base64
是什么意思。有任何想法吗?更新2
我不得不这样修改标题:
files = {'file': ('email.csv', b64data, 'application/octet-stream\r\nContent-Transfer-Encoding: base64')}
。我在HTTP转储中看到了标题,但我仍然收到
HTTP 415 Unsupported Media Type
。更新3
看起来
requests
需要API更新以支持我在这里尝试的操作。多部分的第一部分(XML数据)需要设置Content-Type: text/xml
,而API目前不支持此操作。讨论在此处。