Create a Basic Webpage with Pyscript in Python
Pyscript is a Python framework used to run the Python script on the web browser. Pyscript is an open-source Python framework that gives the ability to design the front end of the web application with the help of Python. It means HMLT code can be run and written. Pyscript allows us to either embed Python code in HTML or link to a Python file, and the code will run in the browser. We do not need to run the Python code in the backend. PyScript was built by the Anaconda and made public on April 30 at PyCon US 2022. At the time of writing, PyScript is in the development phase, and teams are actively working on it.
Basically, PyScript is based on pyodide, which means “port of CPython to web assembly/Emscripten” project. WebAssembly is a low-level binary format that gives users the ability to write programs in other languages, which are then executed in the web browsers.
Features of PyScript:
The features of Pyscript are given as follows:
PyScript allows the embedding of Python code in HTML (Hyper Text Markup Language).
There is no need to worry about the deployment because pyscripts are used. Everything is handled by the web browsers. HTML files can be exchanged by containing refined dashboards or any chart data with anyone.
PyScript contains three primary parts – py-env, py-script, and py-replt.
Setup project for PyScript:
To start working with PyScript, create a directory where all the code will take place. First, let an HTML be created and linked to the PyScript asset comprising of a CSS file and JavaScript file in the <head> section of an HTML page. Once the assets are, we can use PyScript in an HTML file in either of two ways-
- Internal Pyscript: The internal pyscript is embedded in the Python code within <py-script> tag in an HTML. The <py-script> tag can be added in the <head> or <body> tag, depending on the task at hand.
- External Pyscript: In external pyscript, the code is written with a .py extension, which can then be referenced in the <py-script> tag with the help of the src attribute.
Internal PyScript:
The internal pyscript is the quickest and easiest way to start using PyScript is to embed Python code in the HTML file. In the working directory, make a hello_pyscript.html and add the following script.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello World!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<!-- Put Python code inside the <py-script> tag -->
<py-script>print("Hello World!, Welcome to Python programming")</py-script>
</body>
</html>
Output:
When you run the hello_pyscript.html file, you will see the output as given. In the code given, a pyscript.css is added in the <head> section. It includes a style for PyScript visual components, REPL, the PyScript loader, etc. Then, the pyscript.js file is linked and contains the necessary features for using PyScript, like creating tag <py-script> where Python can be written.
External PyScript:
The better and more scalable approach is to use external PyScript to add code. There are a few reasons given below to use PyScript code in an external file.
- The browser caches the file, which increases the performance.
- We can reference the file on multiple pages to reduce duplication.
- Python code can be formatted using other tools like black or Python litres. These tools don't currently work on Python code embedded in an HMTL.
To implement External PyScript, an index.html is to be created, and a Python file that we want to embed is to be created.
First, make an index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello from PyScript!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
</body>
</html>
Now, the file will not work as we just link the file to PyScript resources. To make it work, we need to make the main.py file where our Python will take place.
Create the main.py file.
Let's create a main.py file in which a function is created that prints a greeting message.
Code:
def greetings(name):
print(f'Hi, {name}')
greetings('John Doe')
Now embed the main.py file in the HMTL file by adding a line style to the body tag.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello from PyScript!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
//Add the following line
<py-script src="main.py"></py-script>
</head>
<body>
</body>
</html>
The src tag is added that takes the file name along with the path.
Python provides a Read Eval Print Loop (REPL) that can be used to experiment and try out Python code. For using the REPL, add the <py-repl> tag in the body tag in our index.html file
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hello from PyScript!</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
//Add the following line
<py-script src="main.py"></py-script>
<py-repl></py-repl>
</head>
<body>
</body>
</html>
Here, all the functionalities can be used, such as evaluating expressions and creating functions, and many other Python operations can be performed.
We can use the Python module in PyScript and use it in the HTML code. The module can also be imported form the Python standard library, as well as third-party modules. PyScript provides the <py-env>, which allows us to reference modules or module file paths.
Creating custom modules:
Now, we define two functions in the file my_module.py file in our project directory. Let's add some lines of code.
My_module.py code:
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 % num2
Two functions are made: multiply and divide, multiply two numbers, and divide two numbers, respectively.
Now create an html file module.html and add the following code.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>local modules</title>
<!-- linking to PyScript assets -->
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-env>
- paths:
- my_module.py
</py-env>
<py-script>
from my_module import multiply
print(subtract(8, 4))
<py-script>
</body>
</html>
In the code, <py-env> is used inside the body tag that takes a YAML list that has a path as its key. The my_module.py is the Python file path of the custom module relative to the modules.html file. Once the path added to the custom module is specified, PyScript will import the module in the file.
Creating a Basic Webpage with Pyscript in Python
As we have seen, PyScript is a Python framework or library that gives Python programmers the ability to write code in HTML directly using a pyscript tag.
Creating and displaying a list in PyScript using a loop:
A list of the elements can be generated in HTML with the help of a pure Python list. The syntax of Python can be easily used to print the elements of the list. The output is given to the program as a distinct line, which is the default of the print statement in PyScript.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>PyScript Demo</title>
</head>
<body>
<py-script>
sports = ["Football", "Cricket", "Hockey", "Basketball"]
for sport in sports:
print(f" - {sport}")
</py-script>
</body>
</html>
Creating and Displaying a dictionary using a conditional statement:
The Python dictionary is the key-value pairs that can be accessed one by one using a simple for loop or while loop.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>PyScript Demo</title>
</head>
<body>
<py-script>
name = "Python Programming"
freq = {}
for s in name:
key = freq.keys()
if s in key:
freq[s] += 1
else:
freq[s] = 1
for k in freq:
print(f"{k} : {freq[k]}")
</py-script>
</body>
</html>
Output:
A dictionary can be seen from the above code with the key values as the character of strings and the frequency of that character in the string.
Use the HTTP server to render the PyScript page:
The HTTP server can be used to render the PyScript page. To render the HTML page, the HTTP.server module can be used.
You just need to open the command prompt in the same directory and type the following command.
Python -m http.server
Output:
Serving HTTP on :: port 8000 (http://[::]:8000/) ...
::ffff:127.0.0.1 - - [14/Dec/2023 17:22:26] "GET / HTTP/1.1" 200 -
::ffff:127.0.0.1 - - [14/Dec/2023 17:22:28] code 404, message File not found
::ffff:127.0.0.1 - - [14/Dec/2023 17:22:28] "GET /favicon.ico HTTP/1.1" 404 –
Python -m http.server -d 'path-to-directory'
The flag d is given to locate the file in the directory without actually changing the directory in the terminal to run the HTTP server.