Estimated reading time: 3 minutes
Are you developing a website and looking to execute some Python script directly from the website?
Here we take you through how to achieve this using Python Flask, the scenarios we demonstrate are as follows:
- Javascript on load event – execute Python script
- Javascript on click event – execute a Python script
In both scenarios above you will be presented with pop-up boxes like below, but the python code can be changed to whatever you like.
The code you will need to run this is split into two. (A) The Index.HTML logic and (B) the app.py logic
The code for the INDEX.HTML page
This is the page that the user is presented with. As you can see the logic has two pieces of javascript that when run, go over to the python code and run some logic that it wishes the webpage to run.
In this instance, the app.py python script holds the commands that need to be executed.
Note the page load event goes to the route in app.py, namely ” @app.route(‘/’)”
Whereas the button click event is pointed directly at “@app.route(‘/test’ )” – essentially this will not run until the javascript asks it to, on the button click event.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Home Page</title>
</head>
<body>
<! -- Calls a function on the page load. -- >
<element onload="myfunction_onload">
<button type="submit" onclick='myfunction_clickevent()'>Run my Python!</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<! -- This script runs the python script on the page load -->
<script>
function myfunction_onload(){
$.ajax({
url: "app.py",
context: document.body
})
}
</script>
<! -- This script runs the python script when the button is clicked -->
<script>
function myfunction_clickevent(){
$.ajax({
url:"/test",
context: document.body});}
</script>
</body>
</html>
The code for the APP.PY Python script
Here we are linking to the index.html page and taking commands from it and executing those requests.
In this scenario, the message boxes are rendered by using the win32api package.
The app is using the flask package to run the website.
The powerful thing here is you can start customising this logic to do what you like, examples include:
(A) Return graphs to the webpage.
(B) Process data received and return statistics on the data.
(C) Validate data received in Python and return a response. An example here could be a user logging into a database.
import win32api
from flask import Flask, render_template
app = Flask(__name__)
#Using the below, the popup message appears on the page load of index.html
#0x00001000 - This makes the popup appear over the browser window
@app.route('/')
def index():
win32api.MessageBox(0, 'You have just run a python script on the page load!', 'Running a Python Script via Javascript', 0x00001000)
return render_template('index.html')
#Using the below, the popup message appears when the button is clicked on the webpage.
#0x00001000 - This makes the popup appear over the browser window
@app.route('/test')
def test():
win32api.MessageBox(0, 'You have just run a python script on the button press!', 'Running a Python Script via Javascript', 0x00001000)
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Dear Sir,
I am new to Python and web programming. I do have some programming experience but would not call myself an expert.
I am afraid I don’t seem to be able to make this run. I don’t get any errors when loading the webpage. It just doesn’t do anything when loading or when clicking the button. Apart from watching your video two times and reading the text, here is what I did and tried.
System: Windows11, Python 3.11.1, Browser Firefox 108.0
I made sure I have the necessary python packages and when putting the import lines in different (working) python code it does not throw an error when running it. Internet connection was stable during working.
I made a 1:1 copy of the code you posted, put the html code in a file index.html and the python code in a file app.py.
The files are both on my computer at the moment. The addresses of the files are
C:\……..\TEST\templates\index.html
C:\……..\TEST\app.py
There are no additional files in the folder structure under TEST.
For debugging purposes I added a text line to the html page which is empty on load and is filled with the text “You did click the button.” by the function “myfunction_clickevent()” when clicking the button. It works fine. So the html+javascript code seem to work properly.
I also tried with giving the full address of the script.
I also tried with a different python script which starts an R script (This is actually what I am planning to do, to play with some data from a database) but also nothing happens.
Did I do any obvious mistakes? Or how can I further debug this problem?
How does the javascript logic know where to look for the “app.py”, especially when doing the click event where in the function the “app.py” isn’t explicitly named (what if there were more than one python script in the same folder)?
Kind regards
Barbara
Hi Barbara,
Can I ask how you are runniing this code. What I mean is are you running through Python Idle?
My initial thoughts are the templates location should be within the application folder not a local folder.
Have you tried debugging, or running it an application such as Pycharm , that is where I did my coding.
Please let us know, so can look at further.
Thanks,
Data Analytics Ireland
Hi Data Analytics,
thank you for replying. I am coding in VS Code.
We found the error I made, it was quite simple and stupid, and due to a complete lack of understanding on my side with regards to how things are supposed to function.
I did not run the python code to start the web server before opening the web page. I just assumed it is supposed to sit there, waiting for the Javascript to start it, like my R script which is started by the Python script. So I just ran it once to make sure it doesn’t show any errors and then stopped it. I then opened the web page via the index.html, not through the IP address http://127.0.0.1:5000/
Your explanation and video doesn’t say explicitly (or I overlooked it) in which order to run things and the title is “How to run Python directly from Javascript”. Hence my conclusion. I guess it is a little like learning to drive a car (or using any type of machine) without knowing that it has to be started before the thing takes any commands. I believe while looking through the comments under your youtube video I saw that there was at least 1 person who maybe had the same problem I was having.
Anyway, it now works as intended.
Kind regards
Barbara
Hi Barbara,
That is great you got it resolved. It does take a while to understand parts of this, but once you get to understand more, the troubleshooting becomes easier.
Regards,
Data Analytics Ireland