English 中文(简体)
使用多部分编码的问题(海报图书馆)
原标题:Problems using multipart_encode (poster library)

我正试图用<代码>多部分_encode上载一个文件,以实现<代码>MIME程序。 然而,我遇到了以下错误:<代码>。 AttributeError: multipart_yielder instance has no Depende __len__ 。 下面是我的做法,我确实赞赏大家能向我提出一些建议。

url = "https://pi-user-files.s3-external-1.amazonaws.com/"           
post_data = {}
#data is a dict
post_data[ AWSAccessKeyId ]=(data[ ticket ][ AWSAccessKeyId ])
post_data[ success_action_redirect ]=(data[ ticket ][ success_action_redirect ])
post_data[ acl ]=(data[ ticket ][ acl ])
post_data[ key ]=(data[ ticket ][ key ])
post_data[ signature ]=(data[ ticket ][ signature ])
post_data[ policy ]=(data[ ticket ][ policy ])
post_data[ Content-Type ]=(data[ ticket ][ Content-Type ])

#I would like to upload a text file "new 2"
post_data[ file ]=open("new  2.txt", "rb")

datagen, headers = multipart_encode(post_data)
request2 = urllib2.Request(url, datagen, headers)
result = urllib2.urlopen(request2)
最佳回答

问题在于,在httplib.py中,没有发现发电机,而是将发电机视为带有所发送全部数据(因此它试图找到其长度):

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

解决办法是使发电机能够像(a)一样发挥作用:

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

并使用:

datagen, headers = multipart_encode(post_data)
readable = GeneratorToReadable(datagen)
req = urllib2.Request(url, readable, headers)
result = urllib2.urlopen(req)
问题回答

如果您要寄送文件,请填写MultipartParam物体的其他参数,例如制作发送档案申请的代码:

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)

我还认为,你从一开始就应执行<条码>登记——开放者。 http://atlee.ca/software/poster/“rel=“nofollow”





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签