[Answered ]-How to trigger a python script on the server through user action in react (Django+React)?

1πŸ‘

βœ…

I figured this out myself watching YouTube videos.

The answer is to use Express and routers with APIs. Basically create a form element and place the url in the form action tag that that is then read by app.use() function in express.

Here is an example:

const runPython = require('./apps/runPython.js'); //<--Node function that calls a child process for python

app.use('/runPython/:appName',(req,res,next)=>{

    var inputData = JSON.stringify(req.body);
    var appName = req.params.appName //<--name of the python script file
    const result = runPython.run_python_script(inputData, appName); //<--Python returns a text string
    context = JSON.parse(result) //<-- conver test string to json

    res.status(200).render('calculate_savings',{context}); //<--send python data back to browser

    next
   });

"runPython" Node script imported above for launching python child process..

function run_python_script(appName, inputData){
    
    const { spawnSync } = require('child_process');
    const python = spawnSync('python3', ['-c', `from apps import ${appName}; ${appName}.run(${inputData}); assert False`], { encoding: "utf8" });

    // Access stdout
    return(python.stdout)

    // Access stderr
    console.log(python.stderr)

}
module.exports = { run_python_script };

And finally, the form in html where python is called from…

<div>
    <form action="/pythonApp/calculate_savings" method="POST">

        <label for="revenue">Revenue</label>

        <input name="revenue" value="123456789">

        <button type="submit">Submit</button>

    </form>
</div>
πŸ‘€aghosh03

Leave a comment