FOR DEVELOPERS

How to Create an Interactive Web App With PyScript and Pandas

Interactive Web App with PyScript and Pandas

Today, web apps have become more popular than mobile apps. They are easily accessible on various devices, don’t require downloading (thus, have lower memory requirements), and are less expensive to build. While they can be developed using various languages, Python shares the top position with JavaScript, Java, and C#. In this article, we’ll be looking at how to build a Python web app framework. We’ll also explore the PyScript framework and libraries like Pandas.

Introduction to PyScript

PyScript was first introduced in 2022 at the PyCon conference by Anaconda’s Co-founder and CEO, Peter Wang. A major advantage of using PyScript is that it directly interacts with the browser and no server is required. This is achieved using the Pyodide Python interpreter, which is written in WebAssembly and is commonly supported by web browsers today.

How was Pyscript developed?

PyScript was developed by leveraging the power of Emscripten, Pyodide, and WASM. Emscripten is an LLVM-based compiler developed for compiling code and libraries written in C or C++ to WebAssembly for faster execution in web browsers, compared to interpreted or dynamically compiled languages like JavaScript. Pyodide allows any Python package available on PyPI to run on the web browser using micropip. WebAssemble, also known as WASM, is a binary instruction format for a stack-based virtual machine.

Capabilities of PyScript

PyScript has the following capabilities:

  1. Develop simple and clean APIs.
  2. Design and develop a system of reusable and extensible components.
  3. Support and extend standard HTML.

Why PyScript today?

PyScript was developed to leverage the features of UI languages such as HTML, CSS, and JavaScript. Prior to the development of PyScript, there were two major challenges:

  1. There was no way to develop UIs to easily package and deploy applications using Python.
  2. Modern HTML, CSS, and JavaScript have steep learning curves.

PyScript solves both the challenges mentioned above along with problems faced during packaging, continuous integration/continuous distribution (CI/CD), and deployment.

Features of PyScript

The features of PyScript are:

  1. Allows Python to run on web browsers directly without needing any server.
  2. Allows the use of Python packages like NumPy, Pandas, Seaborn, etc.
  3. Can communicate bi-directionally between JavaScript and Python objects.
  4. Allows developers to develop extensible components directly in Python, hence providing a flexible framework.
  5. Allows developers to build UI components easily.

Other Python web app frameworks

A few other common frameworks like Flask and Django are available for building a server-side web app in Python.

1. Flask: It is categorized as a micro-framework and is popular for building RESTful APIs. Some of its features are:

a. Integrated unit testing support

b. Easy debugging

c. Built-in development server

d. RESTful and HTTP request handling.

2. Django: It is among the most popular and powerful tools for developing web app frameworks in Python. It has many built-in features that allow for secure and fast web app frameworks. Some of its features are:

a. Built-in databases like SQLite3

b. Easy management, thanks to built-in administration web page

c. Scalability and easy maintenance

d. Portable and written in Python, a glue language.

Designing a Python web app framework

Developing a complete Python web app framework involves the following stages:

  1. Ideation
  2. UI/UX design
  3. Development
  4. Deployment

Ideation phase

The ideation phase of a product delivery life cycle involves brainstorming sessions with a focus on problems faced by users. It is user-centric so that the right product is delivered.

MoSCoW method in PyScript.webp

Once the ideation phase is over, the next step is to analyze the market and its competitors. This is followed by planning the key features and functionalities of the Python web app framework using the MoSCoW approach. This stands for:

  • Mo — Must-have features
  • S — Should-have features
  • Co — Could-have features
  • W — Won’t need features

UI/UX design

This step involves creating an esthetically pleasing UI (user interface) and an enjoyable UX (user experience). UI deals with the overall look of the web app framework and how it appears to the user. It includes fonts, color, and placement of icons within an app. Meanwhile, UX deals with enhancing the user experience. This includes how the web app framework responds to a user’s action and how swiftly a query is processed.

Development

In this stage, developers make decisions regarding the technologies, frameworks, and tools to be used to create the product. A complete tech stack is prepared which includes the above as well as databases, cloud servers for deployment, programming languages, and operating systems.

Some common examples of tech stacks are:

LAMP: Linux, Apache, MySQL, PHP / Perl / Python

MEAN: MongoDB, Express.js, Angular, Node.js

MERN: MongoDB, Express.js, React, Node.js

The development stage involves the following steps:

Database architecture design

A database is required for storing, collecting, processing, and managing the data, thus providing secure access for its retrieval. CRUD (create, retrieve, update, and delete) operations are performed on the database by writing SQL (structured query language) queries. The most common examples of databases include MySQL, PostgreSQL, and MongoDB. One of the more prevalent architectures is Model-View-Controller which is briefly explained below:

a. Model: Required for managing the data stored in the database. Data can be stored in the database, an API, or a JSON object.

b. View: Decides what the user will see on the screen and how. It is responsible for displaying the model data to the user, such as an output or GUI.

c. Controller: Required to pull, modify, and display data to the user from the database. It acts as a link between the view and the model and helps to convert the output from the model to the view component.

Front-end development

Front-end development refers to the user interface that interacts with the user through various components. It is written in HTML, CSS, and JavaScript with several frameworks providing access to components and templates. Popular front-end JavaScript frameworks are Vue, React, and Angular.

Backend and API development

Backend development is the writing of code and designing of the database and server. The back-end logic begins with one of two types of applications:

a. Single page application: Involves dynamically rewriting one single page without reloading the page from the server. It only requires APIs to reload the page.

b. Multi-page application: Requires the page to be loaded again and again from the server at the user’s request.

The backend needs extensive code and logic but there are a few frameworks that make it easier to develop. The choice of framework is up to the developer and also depends on the tech stack required for the project. Some frameworks are Node.js, Flask, Django, Laravel, Swift, and Flutter.

Backend integration with frontend using APIs

This is one of the most important steps of web development. It involves the integration of the front-end and the backend using APIs to exchange the data. Common examples are social media websites and e-commerce websites.

Web app testing

This is a crucial part of the product life cycle as it tests the functionality of the web app. In this stage, all types of bugs are reported and the app is returned for fixing. It is an iterative process that continues until all stages of testing are clear.

Deployment

This is the last stage of the product development life cycle. It involves hosting the web app on a cloud server so that it is available to users. The actual development of the web app takes place on a local server and once it is ready to use, it is deployed on the cloud server. A few cloud hosting services are Heroku and AWS.

How to write a PyScript code

The PyScript package can be downloaded from the official website. It can also be included within the HTML code directly using the URL.

<html>
   <head>
       <link rel="stylesheet"
           href="https://pyscript.net/alpha/pyscript.css" />
       <script defer
           src="https://pyscript.net/alpha/pyscript.js">
       </script>
       <py-env>
          #here libraries shall be included 
       </py-env>
   </head>
   <body>
       <!-- HTML layout code goes here -->
       <py-script>
           # Python code goes here
       </py-script>
   </body>
</html>

In the above HTML code, the Python code is written within the tags "<py-script>", similar to the IDE for writing Python code. It is important to include the PyScript stylesheet and JavaScript file in the "<head>" tag of the HTML file as shown below:

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

<script defer src="https://pyscript.net/alpha/pyscript.js&quot;>

For example, to print numbers from 0 to 2 on a web page, the following code must be written in "<py-script>" tag:

<py-script>
for i in range(3):
print(i)

</py-script>

How to include Python libraries in an HTML file

To include libraries in the HTML file, they must be included within the "<py-env>" tag. For example:

<py-env>
       - matplotlib
       - pandas
</py-env>

Python libraries for building web apps

1. Pandas: This is one of the most popular Python libraries for data analysis. It allows for conveniently reading data in a tabular format. It provides an in-memory 2D table object called dataframe that has rows and columns. The two most common types of objects are dataframe objects and series objects. Thus, data can be easily interpreted and visualized once converted to Pandas dataframe object or series.

2. NumPy: This is the most popular library for ‘Numerical Python’ or ‘Numeric Python’ for fast and easy computation on arrays and matrices. It allows easy manipulation of the arrays of different dimensions. It can perform matrix operations like addition, subtraction, inversion, etc.

3. Seaborn: This is a Python library that is commonly used for data visualization. It allows for the creation of high-level statistical graphs based on data.

4. Matplotlib: One of the most common libraries for plotting graphs and visualizing data, Matplotlib offers the following features:

a. Create publication quality plots.

b. Make interactive figures that can zoom, pan, and update.

c. Customize visual style and layout.

d. Export to many file formats.

e. Embed in JupyterLab and GUIs.

f. Use a rich array of third-party packages built on Matplotlib.

Use of Python REPL tag

One of the best ways to implement Python is to use REPL (Read, Eval, Print and Loop). It provides an interactive console to implement Python code. It lets you write code in Python, print the desired output, and continue to run the loop. An example of a web page that provides an REPL environment is Jupyter Notebook.

Another way to implement REPL is using PyScript, which gives access to the Python shell using the tag "<py-repl>". With this, you can easily write code in the cell visible on the web page and get the desired output like a Jupyter Notebook.

Jupyter notebook uses the Jupyter kernel along with the iPython shell, which is an interactive shell built in Python. The following code shows the implementation of the "<py-repl>".

<html>
   <head>
       <link rel="stylesheet"
           href="https://pyscript.net/alpha/pyscript.css" />
       <script defer
           src="https://pyscript.net/alpha/pyscript.js">
       </script>
       <py-env>
   &lt;/py-env&gt;
   &lt;py-repl auto-generate=&quot;true&quot;&gt;data.sum(axis=0)&lt;/py-script&gt;

</head> <body> <py-script> import numpy as np data=np.array([[1,2,3],[4,5,6],[7,8,9]]) pyscript.write(“data”, data) </py-script> <py-repl auto-generate="true">data.sum(axis=0)</py-script> </body> </html>

Implementation.webp

In the output image, the code written within the "<py-repl>" tag is present inside the cell in the web browser. The code can refer to the variables that were defined within "<py-repl>" tag. Thus, the output generated is shown below the cell.

How to create an interactive web app

Import libraries

A few Python libraries that are necessary for creating a web app have to be imported as shown below in the "<py-script>" section:

# Import libraries
import pandas as pd
import matplotlib.pyplot as plt 

In order to open any file using Pandas, pd.read_csv requires the following library to open the file in PyScript:

from pyodide.http import open_url

The code below will open the CSV file:

url = 'https://raw.githubusercontent.com/disease.csv'
url_content = open_url(url)
df = pd.read_csv(url_content)

The code below illustrates how to plot a graph in PyScript:

# Function to plot the chart
def plot(chart):
   fig, ax = plt.subplots()
   df.plot(y=chart, x='disease_type', figsize=(8,4),ax=ax)
   pyscript.write("chart1",fig)

Here, the difference between the usual Python code and the PyScript code is that the pyscript.write() function takes the first argument as an HTML ID of an element and then writes the output directly in the "<div>" tag containing that ID.

How to access JavaScript functions in PyScript

Importing js library allows accessing JavaScript functions using Py-Script:

from js import document
def selectChange(event):
   choice = document.getElementById("select").value
   plot(choice)

Pros and cons of PyScript

Since PyScipt was only launched recently, it isn’t mature enough to be extensively used. Its performance is determined by the hardware of the machine used to process it, which makes it unsuitable for business applications. If the hardware isn’t up to the mark, it will be quite slow as everything is done in the browser itself. However, this aspect is also its biggest advantage; since it doesn’t require a server to run, it is easier to deploy and run the app.

We have explored how to design a Python web app framework, the features of PyScript, how to write PyScript code and much more. PyScript is a breakthrough technology in the field of web development as it allows easy integration of the Python language with UI languages like HTML, CSS, and JavaScript without needing any server for development. It enables faster development of a web app framework and will definitely prove to be more efficient in the future.

Author

  • How to Create an Interactive Web App With PyScript and Pandas

    Turing

    Author is a seasoned writer with a reputation for crafting highly engaging, well-researched, and useful content that is widely read by many of today's skilled programmers and developers.

Frequently Asked Questions

PyScript doesn’t require any installation. It is a package that can be easily imported.

Yes, PyScript allows importing all Python packages like scikit-learn, Matplotlib, NumPy, Pandas, etc.

Pyodide is a port of CPython to WebAssembly which runs the Python code in the web browser with micropip. All Python packages available at PyPl are supported. Full support for error handling is also included.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.