gpt4 book ai didi

python - 用于在类文件对象中发送 HTTP 请求的库

转载 作者:可可西里 更新时间:2023-11-01 16:11:18 24 4
gpt4 key购买 nike

我目前正在使用 Python requests对于 HTTP 请求,但由于 API 的限制,我无法继续使用该库。

我需要一个库,它允许我以类似流文件的方式编写请求主体,因为我要发送的数据不会立即可用,而且我想尽可能多地保存发出请求时尽可能多地存储内存。是否有一个易于使用的库可以让我发送这样的 PUT 请求:

request = HTTPRequest()
request.headers['content-type'] = 'application/octet-stream'
# etc
request.connect()

# send body
with open('myfile', 'rb') as f:
while True:
chunk = f.read(64 * 1024)
request.body.write(chunk)
if not len(chunk) == 64 * 1024:
break

# finish
request.close()

更具体地说,我有一个线程可以使用。使用此线程,我在通过网络接收流时收到回调。本质上,这些回调看起来像这样:

class MyListener(Listener):
def on_stream_start(stream_name):
pass

def on_stream_chunk(chunk):
pass

def on_stream_end(total_size):
pass

我需要在 on_stream_start 方法中创建我的上传请求,在 on_stream_chunk 方法中上传 block ,然后在 on_stream_end 中完成上传> 方法。因此,我需要一个支持像 write(chunk) 这样的方法的库,以便能够执行类似于以下的操作:

class MyListener(Listener):
request = None

def on_stream_start(stream_name):
request = RequestObject(get_url(), "PUT")
request.headers.content_type = "application/octet-stream"
# ...

def on_stream_chunk(chunk):
request.write_body(chunk + sha256(chunk).hexdigest())

def on_stream_end(total_size):
request.close()

requests 库支持用于读取 的类文件对象和生成器,但不支持写入 请求:拉取而不是推送。是否有一个库可以让我将数据推送到服务器?

最佳答案

据我所知,httplibHTTPConnection.request完全按照您的意愿行事。

我追踪了实际执行发送的函数,只要您传递的是类似文件的对象(而不是字符串),它就会将其分块:

Definition: httplib.HTTPConnection.send(self, data)
Source:

def send(self, data):
"""Send `data' to the server."""
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()

if self.debuglevel > 0:
print "send:", repr(data)
blocksize = 8192
if hasattr(data,'read') and not isinstance(data, array):
if self.debuglevel > 0: print "sendIng a read()able"

## {{{ HERE IS THE CHUCKING LOGIC
datablock = data.read(blocksize)
while datablock:
self.sock.sendall(datablock)
datablock = data.read(blocksize)
## }}}

else:
self.sock.sendall(data)

关于python - 用于在类文件对象中发送 HTTP 请求的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15837116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com