Problems using multipart_encode (poster library)

一世执手 提交于 2019-12-07 15:44:27

The problem is that in httplib.py, the generator is not detected as such and is treated instead like a string that holds the full data to be sent (and therefore it tries to find its length):

if hasattr(data,'read') and not isinstance(data, array): # generator 
    if self.debuglevel > 0: print "sendIng a read()able"
    ....

A solution is to make the generator act like a read()able:

class GeneratorToReadable():
    def __init__(self, datagen):
        self.generator = datagen
        self._end = False
        self.data = ''

    def read(self, n_bytes):
        while not self._end and len(self.data) < n_bytes:
            try:
                next_chunk = self.generator.next()
                if next_chunk:
                    self.data += next_chunk
                else:
                    self._end = True
            except StopIteration:
                self._end = True
        result = self.data[0:n_bytes]
        self.data = self.data[n_bytes:]
        return result

and use like so:

datagen, headers = multipart_encode(post_data)
readable = GeneratorToReadable(datagen)
req = urllib2.Request(url, readable, headers)
result = urllib2.urlopen(req)
uhz

If you want to send a file you should wrap other parameters with a MultipartParam object, example code for creating a send file request:

from poster.encode import multipart_encode, MultipartParam
import urllib2

def postFileRequest(url, paramName, fileObj, additionalHeaders={}, additionalParams={}):
    items = []
    #wrap post parameters
    for name, value in additionalParams.items():
        items.append(MultipartParam(name, value))
    #add file
    items.append(MultipartParam.from_file(paramName, fileObj))
    datagen, headers = multipart_encode(items)
    #add headers
    for item, value in additionalHeaders.iteritems():
        headers[item] = value
    return urllib2.Request(url, datagen, headers)

Also I think you should execute register_openers() once at the beginning. Some details you can find in docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!