Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Python script from React with next routing and a node.js server

I am working on an ethereum application that uses react, next-routing and a basic node.js server. I want to run a python script on a specific route, claimAnalysis to be specific, in order to perform some predictions. I want the script to be executed every time I visit the claimAnalysis route.

server.js

const express = require("express")();
const next = require("next");

const app = next({
    dev: process.env.NODE_ENV !== "production"
});

const routes = require("./routes");
const handler = routes.getRequestHandler(app);

app.prepare().then(() => {
    const server = express.use(handler);

    server.listen(3000, (err) => {
        if(err) throw err;
        console.log("Server ready on localhost:3000");
    });
});

routes.js

const routes = require("next-routes")();

routes
    .add("/insurance/new", "/insurance/new")
    .add("/insurance/:address", "/insurance/show")
    .add("/insurance/:address/claims", "/insurance/claims/index")
    .add("/insurance/:address/claims/new", "/insurance/claims/new")
    .add("/insurance/:address/claims/:id/claimAnalysis", "/insurance/claims/claimAnalysis");
    
module.exports = routes;

Please guide me if I can call a function from the claimAnalysis.js file that runs the python script.

like image 380
KS1798 Avatar asked Oct 15 '22 01:10

KS1798


1 Answers

If you're using Node 10+, you can use util.promisify to execute your python scriptwhich returns a Promise<{ stdout, stderr }> object. See an example below:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

// function to execute python script
async function executeScript(path) {
  try {
    const { stdout, stderr } = await exec(`python3 ${path}`);
    console.log('stdout:', stdout);
    console.log('stderr:', stderr);
  } catch (e) {
    console.error(e); 
  }
}

Now let's use the function in your route:

app.get('/insurance/claims/claimAnalysis', async function (req, res) {
  await executeScript();
  res.send('claimAnalysis request completed');
  ...

})


like image 118
Melchia Avatar answered Oct 22 '22 11:10

Melchia