<p><code>request</code>确实将迭代器或生成器作为<code>data</code>参数,详细信息在<a href="http://docs.python-requests.org/en/master/user/advanced/#chunk-encoded-requests" rel="nofollow">Chunk-Encoded Requests</a>中描述。在这种情况下,传输编码需要分块,因为事先不知道数据大小。在</p>
<p>下面是一个非常简单的示例,它使用<a href="https://docs.python.org/3/library/queue.html#queue.Queue" rel="nofollow">^{<cd3>}</a>,可以用作类似于文件的对象进行写入:</p>
<pre><code>import requests
import queue
import threading
class WriteableQueue(queue.Queue):
def write(self, data):
# An empty string would be interpreted as EOF by the receiving server
if data:
self.put(data)
def __iter__(self):
return iter(self.get, None)
def close(self):
self.put(None)
# quesize can be limited in case producing is faster then streaming
q = WriteableQueue(100)
def post_request(iterable):
r = requests.post("http://httpbin.org/post", data=iterable)
print(r.text)
threading.Thread(target=post_request, args=(q,)).start()
# pass the queue to the serializer that writes to it ...
q.write(b'1...')
q.write(b'2...')
# closing ends the request
q.close()
</code></pre>