requests 上件中文文件名报错解决方案

这几天在用wxpy写机器人,在调用里面的上传文件接口的时候,一直报错。经过排查后,发现是不支持中文文件名;
在群里问了下作者后才知道是requests惹的祸,默认requests用的是unicode来处理文件路径的,所以一旦文件名里面包含了汉字,就会出现下面的错误。

An error occurred in <function process_text at 0x000001BB634DCEA0>.
Traceback (most recent call last):
  File "C:\Program Files\Python35\lib\site-packages\wxpy\api\bot.py", line 335, in process
    ret = config.func(msg)
  File "C:/Users/Administrator/PycharmProjects/example/weixin/1.py", line 62, in process_text
    msg.reply_file(r"D:\视频播放方法-windows.docx")
  File "C:\Program Files\Python35\lib\site-packages\wxpy\utils\misc.py", line 59, in wrapped
    smart_map(check_response_body, ret)
  File "C:\Program Files\Python35\lib\site-packages\wxpy\utils\misc.py", line 179, in smart_map
    return func(i, *args, **kwargs)
  File "C:\Program Files\Python35\lib\site-packages\wxpy\utils\misc.py", line 25, in check_response_body
    raise ResponseError('ret: {}; err_msg: {}'.format(ret, err_msg))
wxpy.exceptions.ResponseError: ret: 1; err_msg: 

 

好了,不多说,直接给解决方案

requests处理文件路径的模块是:C:\Program Files\Python35\Lib\site-packages\requests\packages\urllib3\fields.py

打开它!

1 value = email.utils.encode_rfc2231(value, 'utf-8')
2 value = '%s*=%s' % (name, value)   # 报错的原因就是这行代码

 

把它改成这样就可以正常运行了。

1 value = email.utils.encode_rfc2231(value, 'utf-8')
2 value = '%s="%s"' % (name, value.encode('utf-8'))

 

提示:我用的python3.5.2,其它版本的要所情况改下编码就行了

参考资料:
http://blog.csdn.net/wendaoinbeijing/article/details/48247261
https://github.com/requests/requests/issues/2117
https://segmentfault.com/q/1010000002633223/a-1020000002657633

posted @ 2020-01-15 16:24  seozed  阅读(398)  评论(0编辑  收藏  举报