Solutions

PyScript: Run Python in HTML File – Step by Step Tutorial

If you are a Python developer, and thinking how cool if I can write my Python code directly into HTML as all the Javascript developers do. Well, there is good news for all the Python developers. Here is the step-by-step tutorial for how to run Python in HTML using PyScript.

In a keynote speech at PyCon US 2022, Anaconda company’s  CEO Peter Wang revealed a new project named PyScript. Which is a JavaScript framework. It allows us to create Python applications in web browsers. It will allow us to embed Python code directly into HTML files. Just like we use JavaScript code in our HTML files.

Important Things About PyScript

  1. It allows us to write Python code into our HTML file. So we can use Python’s libraries within our browser.
  2. As we use PyScript, we don’t need to worry about deployments. Everything happens in a web browser. We can share our HTML files with anyone containing fancy dashboards or any chars data. They can directly run it in a web browser without any complex setup.
  3. Run Many popular libraries of Python like pandas, numpy etc.
  4. PyScript allows us to write python code with the help of 3 main components:
    1. Py-env: It defines the python packages list which needs to run your code.
    2. Py-script: In this tag, the user will write their python code.
    3. Py-repl: It will Create a REPL component. The REPL component executes the code user enters and displays the result of the code in the browser.

1. Let’s Create Our First Program with PyScript

You can download the alpha release of PyScript on pyScript.net. We’ll use the CDN of one stylesheet and one script in our HTML file. Add below CDNs to your HTML <head>.

<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
   <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

Our Hello world program will look something like this:

<!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>Python HTML app Hello World</title>
</head>
<body>
   <py-script>  
   print("Hello World!")
   </py-script>
</body>
</html>

When you run this HTML file into your browser, it will print Hello World. Something like this:

2. Print Current Date Time

<!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>Python HTML app</title>
</head>
<body>
   <py-script>
   from datetime import datetime
  
   print(f"It's now {datetime.now()}")
   </py-script>
</body>
</html>

In the above example, we are using python’s DateTime library for current DateTime.

3. Bokeh Chart with PyScript

Let’s create a chart to display the number of fruits sells during a month.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
   <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
   <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.min.js"></script>
   <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.2.min.js"></script>
   <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js"></script>
   <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
   <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.2.min.js"></script>
   <title>Chart Example</title>
   <py-env>
   - bokeh
   </py-env>
</head>
<body>
<h1>Bokeh Chart in PyScript</h1>
   <div id="chart"></div>
 
   <py-script>
       import json
       import pyodide
       from js import Bokeh, console, JSON
       from bokeh.embed import json_item
       from bokeh.plotting import figure
       from bokeh.resources import CDN
 
       fruits = ['Apples', 'Banana', 'Mango', 'Grapes', 'Strawberries']
       counts = [5, 3, 4, 4, 6]
       p = figure(x_range=fruits, height=350, title="Fruit Counts", toolbar_location=None, tools="")
       p.vbar(x=fruits, top=counts, width=0.9)
       p.xgrid.grid_line_color = None
       p.y_range.start = 0
       p_json = json.dumps(json_item(p, "chart"))
       Bokeh.embed.embed_item(JSON.parse(p_json))
   </py-script>
</body>
</html>

When you run this code, you will see a chart like;

As you see how easily we can create a graph into our HTML file only. There is no need to create complex components to display a chart like this. That’s how simply you can use PyScript to run python in HTML. 

Key Advantage of the Python Development

Python is one of the most popular programming languages for different types of use case development. Here are some key advantages of python programming development.

Python Programming for Frontend

Python programming language supports API integration with Backend, mobile, and front-end developments. We can develop API in the Python programming language and integrate it into any front-end technologies. such as 

Backend technologies

1) PHP

This is a scripting programming language that is used to create dynamic web pages. It is an open source and free. It is executed on the server which generates the html then sends it to the client. PHP is supported by all the major web servers including Nginx, Apache and IIS.

2) .Net

.Net is an open-source platform for developing desktop, web, and mobile applications that can natively run on any operating system .Net includes powerful tools and rich library support that help modern, scalable, and enterprise applications.

3) Node js

Nodejs is an open-source and cross-platform runtime environment. Node js allows creation of front-end and back-end applications using javascript. Node JS developers can help to establish runs on a v8 javascript engine and executes javascript code outside a web browser.

Front-end Technologies We Offers

React js

React is a javascript library that helps to build UI components. It is widely used in web development. It follows the Virtual DOM (Document Object Model) which optimizes the rendering performance by reducing the DOM size.

Angular js

Angular is a popular open-source front-end web application framework maintained by Google and the developer community. Core features of Angular are used for building dynamic, single-page web applications (SPAs), and medium and enterprise-level applications.

Vue js

Vue.js is open source frontend web application javascript framework. Vue.js uses an MVVM (Model-View-ViewModel) architecture which separates the business logic from the graphical UI interface.

Mobile Technologies We Serve:

1) React Native

This is an open-source javaScript framework developed for creating mobile applications on multiple platforms like iOS, android and web applications. It will help any organization to build an application with a single code base and run on multiple platforms. It also helps to save time and money for the development.

2) Ionic

Ionic is a robust cross-platform, open-source UI toolkit. It is used for creating native-quality mobile, web, and desktop applications using web technologies like CSS,HTML and JavaScript/TypeScript.

3) IOS

This operating system was developed by Apple. iOS application development is the process of making mobile applications for Apple hardware including iPad, iPhone,iPod Touch, apple watch and TV application. We can develop mobile applications using Swift programming language or objectiveC.we can deploy on the app store for users to download.

4) Android

Android is an operating system developed by the google. Android application development is the process of making mobile applications for android devices. We can develop mobile applications using Java, Kotlin and C++ language. After the development, it deployed on the Play Store for users to download.

5) Flutter

Google developed the open-source Flutter UI software development framework. Flutter is created for native applications compiled for desktop, web, and mobile apps from a single codebase. It is used in the development of cross-platform mobile applications for macOS,windows,linux,iOS and the web.

Database for Python Programming

Python programming language supports with any databases such as:

MySQL

An open-source relational database management system (RDBMS) called MySQL is used to manage and store an immense amount of data. The GNU General Public License (GPL) controls its release.MySQL is used across several industries, including B2B,B2C and web application development.

SQL

SQL is a strong programming language that plays a vital role in today’s world. It allows us to communicate with relational databases and gather information. We can find SQL in use wherever there is data that is widely used in governments, public organizations, and small, medium, and enterprise applications.

Postgres

PostgreSQL is a free and open-source database management system (DBMS) that supports both relational and non-relational data types, and advanced SQL functions like subqueries, foreign keys, and triggers. It is widely used in governments, public organizations,small,medium and enterprise applications.

MongoDB

It is a non-relational database management system (DBMS) that stores data in document format instead of tables and rows. businesses will choose a NoSQL database when they want to work in fast agile environments. It needs to store both semi-structured and structured data.

Use Cases of Python Programming

Here are some general use cases of Python programming language:

  • E-commerce websites, content management systems (CMS), social media platforms.
  • API development and RESTful web services.
  • Analyzing, creating, modifying large datasets in travel, finance, healthcare, marketing industries.
  • Predictive analytics in finance, marketing, and sales.
  • Web scraping for data collection.
  • Educational and productivity tools.
  • Automating server configuration, management, and software deployment.
  • Writing scripts for backups, monitoring, and scaling infrastructure.
  • Managing cloud resources on AWS, Google Cloud, and Azure.

Conclusion

This project is still in the alpha stage, so maybe we can see many more new things in the upcoming days. PyScript looks very promising for python developers, but there might be a lot of security issues. Also, we are running Python libraries into the browser, so execution time is also high. 

All these concerns might be resolved in upcoming releases. Comment down your thoughts about this new technology.

Recent Posts

  • OTA

The Rise of Dynamic Packaging in OTA

Using dynamic packaging technology, one can encapsulate flights, accommodation, cars,…

  • UI/Ux Design

Unlocking Digital Success with UX/UI Design

In today’s contemporary era of accelerated digital evolution, the importance…

  • UI/Ux Design

Why UI Design is Important for Your Website? A Step Towards Way Superior UX

The fact is that in today’s internet environment the only…