Lets say I have an Apache webserver that hosts a webpage, the webpage contains a button, how can I trigger the execution of a python script on my machine (the server machine) when clicking on the button?
-
You can use Flask to serve the webpage and make the button submit the form on click. Then process the submission (Or do whatever you want) within the submission handler function. [Detected Button Press In Flask](https://stackoverflow.com/questions/19794695/flask-python-buttons/51385199) – sqz Mar 16 '21 at 23:20
-
Configure your Apache server with ExecCGI to run Python scripts. – Anon Coward Mar 16 '21 at 23:23
3 Answers
Easiest solution:
Create an endpoint on the webserver that executes the Python process every time someone accesses it (via GET/POST, anything really), and then use AJAX in the browser (jQuery, VueJS+axios, native XmlHttpRequest) to connect the button to that endpoint.
This has a number of problems: anyone could GET the endpoint and trigger the process multiple times, which could crash your server. You'll need to password protect it unless you code the endpoint so that it can't be spammed.
This also spawns a process for every click. Another solution is to keep the Python process running and open a socket, which you can then send commands to from the endpoint on the local machine.
Many ways this can be done.

- 920
- 8
- 20
One solution, that would work, is by using a web-request. I can't really give you any code since your request is very general, but I can give you a sort of procedure.
Python WebApp is running on the same server
Website makes XmlHttprequest with javascript to your set location
The defined function executes / executes your Python script
All this can be done easily by using a FrameWork like Flask.

- 717
- 4
- 11
One of the solutions out there is:
- Make an endpoint that invoke the python script (depending on your server, if it's python you will just call the script and if it's another function you can make a system call to invoke the python script)
- Use xml/Ajax or any other call when you click the button to this endpoint
Please note that you need to secure your endpoint through JWT for maximum security

- 49
- 1
- 8