Home > Enterprise >  Is it possible to execute a python file on a button click in ReactJS?
Is it possible to execute a python file on a button click in ReactJS?

Time:10-05

My App.js file

return (
    <div>
      <button action={onClickHandler}>Click Me </button> 
    </div>
  );

My Test.py file

from flask import Flask, render_template
app = Flask(__name__)


@app.route('/data',methods=['GET', 'POST'])
def my_link():
  print("I got Clicked")
  return {'name': "geek", "password": "This is PWD"}
  

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

On Button click the React App should execute the python file which will create an API and using fetch("url") in React i want to get that data.

CodePudding user response:

Running a script (or any program) on the users computer is strictly prohibited by browser security rules. Otherwise, some very bad scenarios were possible, like a script downloading a malware/trojan/virus/... file silently in the background and running it on the victim's machine. The user would not notice anything in the first line. The only thing an attacker would need to make them do is open a specific web site prepared like this (and there are many possibilities to achieve this).

Anyway, the script you posted looks like a server-side script (as Flask is a server-side framework), there is no need to download it on the client side to execute it. As the script says, the user would have to access /data on the server via a GET or POST request and, in return, get the JSON object containing name and password (please see notes below about that!).

I'd suggest you to store your script on a server (there are many ways to achieve this, one of them is described here) and make your onClickHandler just send a GET or POST to it. (Let's say, your server is myserver.com, you would have to access myserver.com/data in your script.) Of course, during development, you can try it on localhost without the need for a production server setup.

Most important: I don't know your use case or what you want to achieve, but transferring user credentials that way is absolutely insecure and dangerous! Of course, for a playground or development environment, this is OK, but you should never use it in production as anyone able to access your /data endpoint will get to know your user name and password and be able to (mis)use it in the future!

  • Related