Getting Started With PyScript Tutorial 2022 - Build Web Apps with Python in Your HTML

Getting Started With PyScript Tutorial 2022 - Build Web Apps with Python in Your HTML

What is PyScript?

For all Python lovers out there, that longed to use Python in the browser alongside HTML and CSS, well PyScript is making that possible. PyScript is a framework built with JavaScript that allows users to create python applications directly in the browser using an HTML interface. It uses Pyodide, WASM, and modern web technologies in order to create rich applications.

On top of that, since PyScript is built with javaScript, there is a Bi-directional communication between Python and Javascript objects and namespaces.

PyScript syntax can easily be understood by programmers from different backgrounds.

Adding PyScript to HTML.

Adding PyScript to your HTML file is actually pretty easy, you can head over to the PyScript official website at pyscript.net, to download the PyScript files or copy the links to the assets.

You have two options for using PyScript, first, you can download the PyScript assets to your local machine and link them to your HTML page or you can use the assets served from the official site.

Actually, you can choose any one of the approaches, they all refer to the same files.

For the sake of this article, we are going to use the assets served from the official site. You can copy the following code and add it to your HTML page.

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

Printing Hello world to the browser

Before we start writing code, let's make sure our environment is set up, preferably the creator of PyScripts warns that it is in the alpha stage and also currently under heavy development, so using it for production is not recommended. And also you should use the Chrome browser for developing your applications.

I am going to use VS Code as my code editor, you can use any code editor of your choice. I will be using the Live-Sever VS Code extension, to serve my HTML pages from a local server because PyScripts creators recommended that, also I want the page to reload itself once I make changes to the code. So if you have everything set up and ready, open your editor and create an index.html file and write the following code to it.

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

I know you must have questions like, "Where exactly are we writing the python code"?. well, let me answer that, PyScript has a special tag of its own which is <py-script></py-script>.

In between the opening and closing of the py-script tag you can be able to write your python code and it will get executed once the HTML page is rendered.

Let's follow tradition, and print a "Hello, World!". Update your index.html to this.

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body> <py-script> print('Hello, World!') </py-script> </body>
</html>

If you are using VS Code like me and you have the Live-Server extension installed, right-click on the body of your HTML code for the context menu to appear and then click on Open with live server.

Screenshot (164).png

This will automatically open up your default browser, if your default browser is not Chrome, copy the server URL and open it with Chrome.

But if you are not using VS Code or don't have the live-server extension installed, but happen to have the python software installed, you can use python http.server to serve your HTML file, by opening the directory in your terminal and typing this, python -m http.server [port]. Make sure you replace [port] with the port number you want it to run on, for example python -m http.server 5500.

image.png

We have successfully printed Hello, World! to our HTML page using PyScript, but it doesn't stop there, we can do more.

We can manipulate the DOM using PyScript, and do all sorts of things we normally do with javaScript but using python syntax and with many popular packages of Python and the scientific stack like NumPy, pandas, scikit-learn, and more.

Let's update the content of a specific element with PyScript.

Add this before the py-script tag, within the body tag:

<b>
<p>
Today is <u><label id="today"></label></u>
</p>
</b>

We have a label with an id of today and we would like to update the innerText of the label with the current date using PyScript.

Let's update our PyScript to import the datetime module and also write to the label element.

<py-script>
      import datetime as dt 
      pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y'))
</py-script>

Note:

You might come across a problem like VS code formatting the code in between the PyScript tag to a single line, and when you try to run it in the browser it throws an error. To fix this, in VS code, go to preferences and select settings, or if you are on windows you can press ctrl + ,. On the settings search bar type format and you will see two options that say, Format On Save and Format On Paste, if the two options are checked, unchecked them. And VS code will stop formatting your PyScript code into a single line.

Or you can optionally install the PyScript VS Code extension.

The PyScript write method accepts two arguments, first the identifier of the element and second, the text to write into that element.

Our final code will look like this:

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body>
    <b
      ><p>
        Today is <u><label id="today"></label></u></p
    ></b>

    <py-script>
      import datetime as dt 
      pyscript.write('today', dt.date.today().strftime('%A %B %d, %Y'))
    </py-script>
  </body>
</html>

When you open your web browser, you will see a page similar to this:

image.png

Adding 3rd Party Python packages to your PyScript Applications.

You can also be able to add 3rd party packages to your PyScript applications easily using the <py-env></py-env> tag.

Where you specify the name of a package after a hyphen. Example:

<head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
        - numpy
        - matplotlib
      </py-env>
</head>

The py-env tag should be added to the head tag, with a hyphen pre-pended to each package name. And these packages can be imported and used right in the py-script tag.

Adding a local python module to PyScript Application.

To add a python module or file to PyScript applications, you have to provide the path to the file in the py-env tag but also pre-pending a hyphen to it. But before we provide the path to the file we need to specify and tell PyScript that it is a path to a file, not another 3rd party package by adding the - paths: and then giving an indent before writing the path to the module on the next line.

For example, suppose we have a hello.py file in the same directory as our HTML file and we want to add hello.py to our HTML file, we do this.

<head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
       - paths:
            - ./hello.py
      </py-env>
</head>

If hello.py contains:

def sayHello():
   return 'Hello, PyScript!';

We can be able to use the sayHello function like this;

<body>
    <py-script>
      from hello import sayHello
      print(sayHello())
    </py-script>
</body>

And when you open the browser, you will see "Hello, PyScript!" printed to your page.

image.png

The py-repl tag

As you can see PyScript has many custom tags and each tag with a specific purpose, so what is the py-repl tag, and what is its purpose?

It's actually one of the coolest things i have seen in PyScript, the py-repl tag creates a Python REPL read-evaluate–print-loop which is like an interactive environment where you can write python code and execute it. It reads your python code, evaluates it and prints the result, and then goes back to the first step.

Let's implement the py-repl tag into our HTML page. In between the body tag, write this:

<py-repl></py-repl>

When you open your browser, you will see a code editor, where you can actually write and execute code.

image.png

Actually, this is all there is to get started with PyScript, as you can see PyScript is actually straightforward. Web developers and Python developers can be able to understand PyScript with ease.

It gives us the power of the browser and the simplicity of the Python programming language, so just imagine the awesome things you can build with PyScript.

Did you find this article valuable?

Support Usman Gurowa Hassan by becoming a sponsor. Any amount is appreciated!