在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ python2 post 上傳壓縮文件編碼報錯

python2 post 上傳壓縮文件編碼報錯

python版本是2.7,使用urllib2將文件推送至微信,在上傳文件時,碰到這樣一個問題:上傳未經(jīng)壓縮的文本文件,可以成功;上傳經(jīng)過壓縮的二進制文件,則提示編碼錯誤
代碼如下

def upload_tmpfile_old(self,filepath):
        try:
            #文件存在、文件可讀、文件大小小于19M
            if not (os.path.isfile(filepath) and os.access(filepath,os.R_OK)
                and os.path.getsize(filepath)<19922944):
                return -1

            boundary = '----------%s' % hex(int(time.time() * 1000))
            data = []
            data.append('--%s' % boundary)
            fr = open(filepath, 'rb')
            data.append('Content-Disposition: form-data; name="media"; filename="pickdump"')
            data.append('Content-Type: application/octet-stream\r\n\r\n')
            data.append(fr.read())
            fr.close()
            data.append('--%s--\r\n' % boundary)
            http_body = '\r\n'.join(data)

            print http_body
            sendurl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + Token.gettoken() + "&type=file"
            req = urllib2.Request(sendurl, data=http_body)
            req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
            req.add_header('Content-Length',len(http_body))
            print req.headers
            self.resp = urllib2.urlopen(req, timeout=5)
            print self.resp.__dict__
            print self.resp.read()
        except:
            logger.exception("上傳文件出現(xiàn)異常")
            raise

if __name__ == '__main__':
    uploadfile = wxRequest("WZ", '', '', "file", 1000002)
    uploadfile.upload_tmpfile_old("/home/wz/12306.txt.zip")    

報錯信息如下:

Traceback (most recent call last):
  File "/home/wzk/wx2x/wxpush.py", line 264, in <module>
    uploadfile.upload_tmpfile_old("/home/wzk/12306.txt.zip")
  File "/home/wzk/wx2x/wxpush.py", line 227, in upload_tmpfile_old
    self.resp = urllib2.urlopen(req, timeout=5)
  File "/usr/lib64/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib64/python2.7/urllib2.py", line 431, in open
    response = self._open(req, data)
  File "/usr/lib64/python2.7/urllib2.py", line 449, in _open
    '_open', req)
  File "/usr/lib64/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/lib64/python2.7/urllib2.py", line 1242, in https_open
    context=self._context)
  File "/usr/lib64/python2.7/urllib2.py", line 1196, in do_open
    h.request(req.get_method(), req.get_selector(), req.data, headers)
  File "/usr/lib64/python2.7/httplib.py", line 1057, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib64/python2.7/httplib.py", line 1097, in _send_request
    self.endheaders(body)
  File "/usr/lib64/python2.7/httplib.py", line 1053, in endheaders
    self._send_output(message_body)
  File "/usr/lib64/python2.7/httplib.py", line 895, in _send_output
    msg += message_body
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb6 in position 149: invalid start byte

以前用python3,byte和str有明確的區(qū)分。這個功能由于版本問題,只能用python2,結(jié)果發(fā)現(xiàn)編碼各種坑啊。
壓縮文件本來就是一個二進制文件,不能被utf-8解碼也是正常的,不知道對于這個問題有沒有方法解決?
PS 以前用requests的時候,是把文件讀成bytes后,直接拼回body里面的,不知道這樣做在python2中應該如何寫?

回答
編輯回答
尕筱澄

這個是urllib2庫本身的邏輯導致的。他會將含有bytestring的字符串解碼為unicode字符串后,與msg相加,再進行發(fā)送。如果要發(fā)送流文件,需要直接使用httplib。

2017年4月25日 11:18