- Run Python in HTML
- Run Python Scripts in HTML using PHP
- Run Python script in HTML using Django
- PyScript: Loading Python Code in the Browser
- History
- Method 1 – Include Python with HTML
- example1.html
- example1.html version 2
- Benefits:
- Drawbacks:
- Method 2 – Load Python from a file
- example2.html
- Benefits:
- Drawbacks:
- Method 3 – Load Python from multiple source files
- Method 4 – Load Python and execute Python after a page is displayed
- Benefits:
- Drawbacks:
- Method 5 – Load Python using Pyodide
- Importing Python Packages
- Write your own Pyscript Replacement
- Pyscript Issue
- Summary
- More Information
- Photography Credits
Run Python in HTML
- Run Python Scripts in HTML using PHP
- Run Python script in HTML using Django
Web Development is a vast field, and there are endless opportunities and things that we can do. With complexity and demand come requirements. When building dynamic web pages, we often have to perform tasks that require the assistance of some programming language such as Python or PHP. In this article, we will learn how to run a Python script in HTML. We will talk about a few ways in which we can achieve this.
Run Python Scripts in HTML using PHP
We can use PHP or Hypertext Preprocessor to run Python scripts in HTML. Refer following code depicts a simple example.
html> head> title>Running a Python scripttitle> echo shell_exec("python script.py"); ?> head> body> body> html>
a = 2000 b = 21 print(f"a = a>") print(f"b = b>") print(f"a + b = a + b>")
This will print the following in the console.
If we want to pass some values to the Python scripts, we can use the following code.
html> head> title>Running a Python scripttitle> echo shell_exec("python script.py \"Parameter #1\" \"Parameter #2\""); ?> head> body> body> html>
Now, the Python script will look as follows.
import sys a = sys.argv[1] b = sys.argv[2] print(f"a = a>") print(f"b = b>") print(f"a + b = a + b>")
The output will remain the same, as shown above.
Run Python script in HTML using Django
Django is a famous and robust Python-based web development framework. Since it is Python-based, it makes it easier to run Python scripts inside the HTML. The way we do this is by using template tags. Django has some pre-built template tags such as date , linebreaks , safe , random , etc. You can learn more about them here.
Since Django is very customizable, it offers developers an easy way to create their custom template tags. Using template tags, we can return data to HTML templates, which can be embedded inside the HTML template.
Follow the following steps to create a simple template tag. We are assuming that we have a core application in our Django project.
Create a new directory, templatetags , inside the core application. The app directory should look something like this.
core/ __init__.py models.py admin.py views.py urls.py . templatetags/ __init__.py .
Inside the templatetags folder, create a Python file named my_custom_tags.py .
Inside this file, add the following code.
from django import template register = template.Library() @register.simple_tag def my_tag(): return "Hello World from my_tag() custom template tag."
my_custom_tags.py module will hold all the custom template tags. As shown in the code above, my_tag is a custom template tag that we just created and now it can be used inside any HTML template. This template tag will return «Hello World from my_tag() custom template tag.» this string to the template. We can create even more template tags here to perform specific and common tasks.
Now that we have created our first template tag, it is time to load it inside our HTML template and use it.
html lang="en" dir="ltr"> head> title>Introtitle> head> body> p> p> body> html>
We first load the my_custom_tags.py module inside the template. Once the module is loaded, we can now use the template tags defined inside the my_custom_tags module. Note that it is important to first load a module with custom template tags before using those template tags.
Instead of using a template tag, we can also create an end-point and make an AJAX request to that end-point to perform some task or get some data. We can use fetch() or jquery or any other available method to make an AJAX request. While making an end-point to handle an AJAX request, it is important to ensure that the end-point is secure and doesn’t give easy access to sensitive data or website features. Since anyone can make AJAX requests if they know the end-point, we can add CSRF ( Cross Site Request Forgery ) validation to it and configure it to handle only POST requests. The POST data should contain the CSRF token.
You can learn more about CSRF here
Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.
PyScript: Loading Python Code in the Browser
Today, you can now use Pyscript to run Python code in the web browser. This has enormous potential for AI, ML, Data Scientists, and regular Python developers. I often develop backend applications in Django and Flask, and the possibilities of writing both frontend and backend code in Python are intriguing.
This article is about how to load Python code in the web browser. There are a number of methods. Knowing these methods can improve development and debugging. I will also show methods of loading Python modules.
At this time, Pyscript is in alpha.
Including Python in the browser is amazingly simple. Include two tags in the HTML head:
In this article I will discuss the following methods:
- Include Python with HTML
- Load Python from a file
- Load Python from multiple source files
- Load Python and execute Python after a page is displayed
- Load Python using Pyodide
History
It has been possible to run Python in the browser for several years (2018). Pyscript does not actually interpret Python code. Pyodide (Pie-O-Dide) is the magic behind Pyscript. In my fifth method in this article, I will show an example that does not use Pyscript and directly loads Python using JavaScript and the Pyodide library.
Understanding Pyodide is important to understanding how to use Pyscript. Pyscript’s genius is wrapping Pyodide to completely hide it for most HTML/Python applications. However, you will import some functions from Pyodide. Example: from pyodide.http import pyfetch . I use that import to provide a replacement for requests which is not available in Webassembly based Python (Python in the browser).
Be sure to read the last section “Write your own Pyscript”.
Method 1 – Include Python with HTML
This method uses the
You must correctly format the Python code just like a normal .py file. Indentation matters.
Notice that I am wrapping the Python code in a main() function. In a future article when I discuss async Python in the web browser, the reason will become apparent.
example1.html
This example loads in the web browser and displays “Loading page …”. Once the Python code executes, the page changes to “Hello world”. The entire process takes about two seconds. I expect this time to decrease significantly as Pyscript reaches production quality.
This example demonstrates how to get a DOM element by ID:
and then write to that element:
Pyscript has a library named pyscript that has built-in functions to make this easy. The following one line of code replaces the two previous lines.
The source code for pyscript.write() is here. The signature is:
Notice append . If true you can append a as a child to the specified element ID.
Another interesting item is the class Element (link):
With those improvements, the updated example becomes:
example1.html version 2
The key is to understand how to get DOM elements and then modify them. This is an important concept for code that runs in the browser.
Benefits:
Drawbacks:
Method 2 – Load Python from a file
This method uses the style to load Python from a separate file. To the untrained eye, you might not even notice that Python is being loaded into the web browser.
example2.html
This example loads the Python as a separate step similar to loading CSS or JavaScript resources. This example displays “Loading page …”. Once the Python code load and executes, the page changes to “Hello world”. The entire process takes about two seconds. I expect this time to decrease significantly as Pyscript reaches production quality.
At this time, the defer keyword is not supported. This example will not work:
As Pyscript becomes popular, this would be a nice feature to lazy load Python while the DOM is generated.
Benefits:
Drawbacks:
- This example cannot be loaded into the web browser from a local file. This method requires a web server.
Simple web server for local Pyscript development:
Method 3 – Load Python from multiple source files
Typical applications are split into multiple source files. Pyscript supports including multiple files. There is a limitation where the files cannot have the same name even if located in different directories.
Once the source files are declared, you can then import functions from those files.
Method 4 – Load Python and execute Python after a page is displayed
This method uses pyfetch() to download a file containing Python code from a web server. An important undocumented detail is that you must import the asyncio package, otherwise, you will get unusual errors. This took me a while to figure out. Once the code is downloaded, it is executed.
Benefits:
- Separating Python from HTML simplifies development and testing.
- This method permits executing Python on demand instead of when the page loads.
- Demonstrates how to use pyfetch() and the asyncio package
Drawbacks:
- This example cannot be loaded into the web browser from a local file. This method requires a web server.
Method 5 – Load Python using Pyodide
Pyodide is the magic behind Pyscript. In this example, I will show how to load and execute Python without loading Pyscript.
This is a simple example of how easy it is to load a Python source file from a web server and run that Python code in the web browser.
Importing Python Packages
Pyscript defines the tag which defines the Python packages your program requires.
You can also declare the package version:
In some cases, you do not need to use . I have not figured out yet when using is required. My examples above, do not use , they just import the packages from the Python code. This might be because the packages are already part of the Pyscript downloads. numpy is an example that requires declaration in . Pyscript is brand new and my knowledge is limited but I am digging into everything.
Read Method 3 – Load Python from multiple source files for details on how to include multiple source files.
Write your own Pyscript Replacement
If you want to surprise a few developers, try this example. Here I show you how to create your own DOM tag element using, for example, your name. In this example, I use jhanley-python to signify the Python code to execute:
If you study that example, you will see how easy it is to implement Python in the browser using Pyodide. Pyscript offers many more features than my simpleton example, but with this, you might be able to contribute to Pyscript by knowing how some things are done.
Move the Javascript to a separate file and few would notice how this is done.
Pyscript Issue
Pyscript has one issue that my example could be used to fix. For a brief period of time, the Python code is visible in the browser window. This can be fixed by using Javascript and my section that hides a custom DOM element tag. For example:
This code needs to run before the Pyscript libraries start loading.
Summary
I am very intrigued with Pyscript. Writing frontend and backend applications in Python can be very useful. Today, the browser is often used as a display device. I want to use the browser to distribute processing power and move some activity from the server to the browser.
A simple example is uploading a large file for processing such as a spreadsheet. Now the spreadsheet can be processed and displayed in the browser, while only uploading the required rows and columns to the backend for storage. This saves a roundtrip where large amounts of data are transferred over the network.
One can argue that JavaScript does that today. That is true, but there are applications that are very difficult or impossible with JavaScript that is a walk in the park for Python.
The spreadsheet is a simplification of a common problem, but take this to the next step, which is AI, ML, and Data Science. These are areas where Python blows JavaScript away. Importing libraries such as numpy have enormous potential.
More Information
Photography Credits
Heidi Mustonen just started a new photography company in Seattle, WA. Her company in-TENSE Photography has some amazing pictures. I asked her for some images to include with my new articles. Check out her new website.
I design software for enterprise-class systems and data centers. My background is 30+ years in storage (SCSI, FC, iSCSI, disk arrays, imaging) virtualization. 20+ years in identity, security, and forensics.
For the past 14+ years, I have been working in the cloud (AWS, Azure, Google, Alibaba, IBM, Oracle) designing hybrid and multi-cloud software solutions. I am an MVP/GDE with several.