Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
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.
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.
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.
PyScript has the following capabilities:
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:
PyScript solves both the challenges mentioned above along with problems faced during packaging, continuous integration/continuous distribution (CI/CD), and deployment.
The features of PyScript are:
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.
Developing a complete Python web app framework involves the following stages:
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.
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:
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.
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:
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 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 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.
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.
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.
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.
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">
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>
To include libraries in the HTML file, they must be included within the "<py-env>" tag. For example:
<py-env> - matplotlib - pandas </py-env>
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.
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></py-env> <py-repl auto-generate="true">data.sum(axis=0)</py-script>
</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>
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.
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.
Importing js library allows accessing JavaScript functions using Py-Script:
from js import document def selectChange(event): choice = document.getElementById("select").value plot(choice)
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 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.