1

How can I call a Python function with my Node.js (express) backend server?

I want to call this function and give it an image url

def predictImage(img_path):
    # load model
    model = load_model("model.h5")
    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

    return str(pred)
2
  • you can run python command using child_process and can call the required function. This link may be useful geeksforgeeks.org/… Commented Mar 12, 2019 at 13:59
  • The fact it's a python script is totally irrelevant, the question would be exactly the same if it was a shell script or any executable binary. Commented Mar 13, 2019 at 13:01

1 Answer 1

1

You can put this function in separated file; let's called it 'test.py' for example.

In the Js file:

const { exec } = require('child_process');

function runPythonScript(){
    return new Promise((resolve, reject) => {
        exec('python test.py', (err, stdout, stderr) => {
            if(err) reject(err);

            resolve(stdout);
        });
    });
}

and call the function runPythonScript in express route.

runPythonScript()
.then(result => res.send(result))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.