PyScript: Run Python in HTML File – Step by Step Tutorial
Are you a Python developer dreaming of seamlessly integrating your code into HTML, much like JavaScript developers do? Great news awaits you! In this step-by-step tutorial, we’ll explore PyScript, a groundbreaking framework that empowers you to run Python directly in HTML files.
Unveiled by Anaconda’s CEO Peter Wang during his keynote speech at PyCon US 2022, PyScript allows developers to create rich Python applications that run directly in web browsers. This innovative approach makes it possible to embed Python code into HTML, unlocking a new realm of possibilities for web development. Join us as we dive into the details of this exciting technology and learn how to leverage it for your projects!
Important Things About PyScript
- It allows us to write Python code into our HTML file. So we can use Python’s libraries within our browser.
- 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.
- Run Many popular libraries of Python like pandas, numpy etc.
- PyScript allows us to write python code with the help of 3 main components:
- Py-env: It defines the python packages list which needs to run your code.
- Py-script: In this tag, the user will write their python code.
- 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.
- Extensive and rich standard of library support
- Develop a wide range of applications using
- Web development
- API development
- Data Science
- Machine Learning
- Game development
- IoT app development
- Strong Automation using tools like Selenium and PyAutoGUI
Python Programming for Frontend
Python programming language supports API integration with Backend, mobile, and front-end developments. OneClick a python development company 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
In conclusion, PyScript represents a promising advancement for Python developers, enabling the integration of Python code directly into HTML files. While this project is still in its alpha stage and holds great potential for future enhancements, it’s essential to be mindful of some current limitations, such as security concerns and increased execution times when running Python libraries in the browser.
As the project evolves, we can anticipate solutions to these issues in forthcoming releases. We’d love to hear your thoughts on this exciting technology! Share your insights or any questions you may have in the comments below. Let’s explore the future of web development together!