Post binary data to flask and save it to xlsx produces corrupted file

Viewed 1116

I do have two communicating backends that request then analyse/transform data :

  • The first is a NodeJS, that requests CSV and excel files from another application, then forwards the response body (which is the binary data of the files) to the python backend to analyse them.
  • The python backend is a flask app, my problem is when i save the binary data received in the python API, the files are corrupted and unreadable. I tried to utf-8 encode and 'wb' the files, still the same thing.

Please note that if i write the file with node, it's readable and fine, and the console.log() and print both display the same body data, it's just the writnig to the file that doesn't seem to go well for me.

Here is the necessary parts of my code :

Nodejs :

r.get({url : link, encoding: 'binary'}, function (error, res, body) {
    if(err)
        console.log(err);
    else {
        console.log("requesting data transformation");
        request.post({url : "http://127.0.0.1:5000/app_name/api/v1.0/transform", body : body} , function (error, res, json_body) {
            console.log("requesting");
            console.log(json_body)
        });
    }
})

Python :

from flask import Flask, request

app = Flask(__name__)


@app.route('/app_name/api/v1.0/transform', methods=['POST'])
def transform():
    print request.get_data()

    with open('binaryxl.xlsx', 'wb') as output_file:
        output_file.write(request.get_data())
        output_file.close()

    return "ok"

if __name__ == '__main__':
    app.run(debug=True, port=5000)

UPDATE

If i write the file using fs (binary mode), then read it, and post the data i read, and added content-type according to the docs, everything goes fine and the excel is readable, but i dont want to open/save/close, i want to be the most efficient possible in my code...

New node code :

fs.readFile('path/to/file.xlsx', function
    read(err, data) {
    if (err) {
        throw
        err;
    }
    console.log(data);
    request.post({
            url: "http://127.0.0.1:5000/app_name/api/v1.0/transform",
            body: data,
            headers: {
                "content-type": "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            }
        },
        function (error, res, json_body) {
            console.log("requesting");
            console.log(json_body)
        });
});

Any ideas ?

0 Answers
Related