Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send BytesIO using requests post

I am trying to send msgpack encoded values to server using requests post to an insert rest endpoint which takes the serialized byte stream as input. But it seems like the values are not getting there properly as I see no values getting inserted in the table. I have never tried this before, so please pardon my ignorance. Here's what I am doing:

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')
like image 318
ShellZero Avatar asked Feb 19 '26 13:02

ShellZero


2 Answers

Whenever I write to the buffer, the pointer will always point to the end of the buffer and waiting for a new write. So, when I pass data=buf, that is going to make an insertion with no values. The solution is to do buf.seek(0) and then pass data=buf as a parameter or simply data=buf.seek(0)

So, the following works:

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')
like image 188
ShellZero Avatar answered Feb 22 '26 02:02

ShellZero


extending your answer, using a with block is advised in-order to fix memory leak in case of exception.

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')
like image 28
Alen Paul Varghese Avatar answered Feb 22 '26 03:02

Alen Paul Varghese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!