如何使用请求发送 BytesIO post
How to send BytesIO using requests post
我正在尝试使用请求 post 将 msgpack 编码值发送到服务器,以将序列化字节流作为输入的插入剩余端点。但似乎这些值没有正确到达那里,因为我看到 table 中没有插入任何值。我以前从未尝试过这个,所以请原谅我的无知。这是我正在做的事情:
buf = io.BytesIO()
for rows in dataframe:
buf.write(msgpack.packb(rows))
response = requests.post(url, data=buf, verify=False)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error fetching response using requests')
每当我写入缓冲区时,指针总是指向缓冲区的末尾并等待新的写入。所以,当我传递 data=buf
时,这将进行一个没有值的插入。解决方案是执行 buf.seek(0)
然后将 data=buf
作为参数传递或简单地传递 data=buf.seek(0)
因此,以下工作:
for rows in dataframe:
buf = io.BytesIO()
buf.write(msgpack.packb(rows))
buf.seek(0)
response = requests.post(url, data=buf, verify=False)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error fetching response using requests')
扩展您的答案,建议使用 with 块,以便在出现异常时修复内存泄漏。
for rows in dataframe:
with io.BytesIO(msgpack.packb(rows)) as buf:
buf.seek(0)
response = requests.post(url, data=buf, verify=False)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error fetching response using requests')
您还可以在创建 BytesIO
对象时添加初始数据,这样您就不必调用 seek
:
>>> import io
>>> buf = io.BytesIO(b"test")
>>> buf.tell()
0
>>> buf.read()
b'test'
>>> buf.tell()
4
我正在尝试使用请求 post 将 msgpack 编码值发送到服务器,以将序列化字节流作为输入的插入剩余端点。但似乎这些值没有正确到达那里,因为我看到 table 中没有插入任何值。我以前从未尝试过这个,所以请原谅我的无知。这是我正在做的事情:
buf = io.BytesIO()
for rows in dataframe:
buf.write(msgpack.packb(rows))
response = requests.post(url, data=buf, verify=False)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error fetching response using requests')
每当我写入缓冲区时,指针总是指向缓冲区的末尾并等待新的写入。所以,当我传递 data=buf
时,这将进行一个没有值的插入。解决方案是执行 buf.seek(0)
然后将 data=buf
作为参数传递或简单地传递 data=buf.seek(0)
因此,以下工作:
for rows in dataframe:
buf = io.BytesIO()
buf.write(msgpack.packb(rows))
buf.seek(0)
response = requests.post(url, data=buf, verify=False)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error fetching response using requests')
扩展您的答案,建议使用 with 块,以便在出现异常时修复内存泄漏。
for rows in dataframe:
with io.BytesIO(msgpack.packb(rows)) as buf:
buf.seek(0)
response = requests.post(url, data=buf, verify=False)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error fetching response using requests')
您还可以在创建 BytesIO
对象时添加初始数据,这样您就不必调用 seek
:
>>> import io
>>> buf = io.BytesIO(b"test")
>>> buf.tell()
0
>>> buf.read()
b'test'
>>> buf.tell()
4