使用Python Requests 库,提交POST请求上传文件,不支持中文文件名?


使用Python Requests库,向微信服务器上传媒体问题。
当使用英文文件名称,上传时,一切OK。
当下面代码中file_name字段包含中文,怎无法上传成功。
返回media data missing
也咨询过微信端,他们说数据未发送成功,就是空数据。
首先我想问这样写有问题么?为什么中文失败,英文成功?
如果Requests有问题,该如何更改?
如果不是Requests的问题,哪些地方可能有问题如何排查?


 data = {'file': (file_name, open(url,'rb'), content_type)}
 #data = {'file': open(url, 'rb')}
 requests.post(url,params=params,files=data)

python requests 微信

JolBall 10 years ago

你对file_name字段URLEncoder一下,我记得Http协议不支持中文文件名

宇智波王五 answered 10 years ago

Inside site-packages/requests/packages/urllib3/fields.py, delete this (line ~50):

value = email.utils.encode_rfc2231(value, 'utf-8')
And change the line right underneath it to this:

value = '%s="%s"' % (name, value.decode('utf-8'))
This makes servers (that I've tested) pick up the field and process it correctly.

https://github.com/kennethreitz/requests/issues/2117 ~issues!

射得满满的 answered 10 years ago

Your Answer