Home > front end >  how to send an numpy array or a pytorch Tensor through http post request using requests module and F
how to send an numpy array or a pytorch Tensor through http post request using requests module and F

Time:12-01

I have an image and I want to send it to the serve. I'm using requests module to perform simple post request as following(info is a dictionary):

    import requests

    print(type(info["array_image"]))
    print(type(info["visual_features"]))
    response = requests.post("url", data=info)

output :

<class 'numpy.ndarray'>
<class 'torch.Tensor'>

on the server side I'm trying to receive them as arrays at least:

from flask import Flask, request

@app.route('/path', methods=['POST'])
def function_name():
    visual_features = request.form['visual_features']
    array_image = request.form['array_image']
    print(type(array_image))
    print(type(visual_features))

output:

<class 'str'>
<class 'str'>

I want to get a bytes array to build the image, but what I'm getting is a string... If I didn't find a way I'll encode arrays in bas64 and then decode it in the server...

CodePudding user response:

You can try to convert your data to proper JSON or use Python pickle module or if you have an image as you've mentioned you can send it as a file (multipart request) to the server as shown in the examples here.

CodePudding user response:

Thanks to @praba230890 for giving me an easy to follow example.

I would still write the solution here down, since the provided link doesn't fit my case exactly.

import pickle
import io

array_image = pickle.dumps(info["array_image"])
stream = io.BytesIO(array_image)
files = {"array_image": stream}

info["array_image"] = None

response = http.post("url", data=info, files=files)

and in the server side:

from flask import Flask, request

@app.route('/path', methods=['POST'])
def function_name():
    image = request.files.get('array_image')
    array_image = image.read()

if you want to get the image from a file, then:

requests.post("http://localhost:5000/predict",
                 files={"file": open('<PATH/TO/.jpg/FILE>/cat.jpg','rb')})
  • Related