Replit EdFest 2022 Jam – Intro To PyScript

[read_meter]

Table of Contents

ATTENTION! If you’d like to do the course yourself, join up using this link for FREE.

And don’t forget to watch the video walkthrough.

Instructions – Intro To PyScript

Welcome to your Intro to PyScript, a simple replit that teaches you the basics of the modern Python web dev technology. You’re going to set up your own simple HTML page with a linked Python program. You’ll enable PyScript, take user data, run it through your program and print it back out to the user.

You’re learning the basics of building front-end, browser-based web applications. With minimal setup, it’s all about your imaginations limitation. Follow the steps below to complete the project, enjoy and we hope you learn a lot!

Goals

  1. HTML page w/ Bulma CSS Framework
  2. Use PyScript to create a Python program
  3. Produce a complete, simple web app

1. HTML page w/ Bulma CSS Framework

1.1 HTML Structure

Okay, let’s start with a basic html structured page, and save it in index.html.

<!DOCTYPE html>
<html>
  <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">
  </head>
  <body>
		...
  </body>
</html>

1.2 CSS + Meta Links

Great, next we’ll be using some css files over the air via a CDN (Content Distribution Network). Make sure to include these in-between <head></head> tags.

<link rel="stylesheet" href="<https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css>">
<link rel="stylesheet" href="<https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css>"/>

While we’re adding links, let’s take a look at what’s going to help out later, PyScript. Currently, it shows the following links, but bare in mind these will change in the future so check their website.

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

1.3 Complete Layout

Awesome, now it’s time to set up the full page structure, from here on out the html code will be in shorthand for you to write yourself. Keep in mind this all goes within the <body></body> tags. Here’s the html outline for you to create, notice the indention.

Note, . (dots) are classes, # (hashtags) are IDs, for example section.container would be <section class="container"></section> and label#name would be <label id="name"></label>. If you’ve used Emmet, this will be familiar. If not, don’t worry, you can pick it up as you go.

section.container
  section.notification
    h1.title
    label
    input#name.textarea
    label
    input#email.textarea
    button#convert.button
  section.notification
    div#output
pyscript

To explain, you’re setting up a primary section with two sub-sections. The first section will have the titles, labels and inputs. And the second section will display the outputs after PyScript has had it’s fun.

2. Use PyScript to create a Python program

Alright, now we’re getting into the weeds… I mean, fun stuff, because it is a lot of fun. The links we added in earlier are going to allow us to use Python in the browser, how cool? Yep, just HTML and Python, crazy!

2.1 The PyScript HTML Tag

Let’s start by adding the PyScipt specific syntax to see it in action and get a taste for it all. Under your <button></button> tags inside index.html, add <py-script></py-script>. This is one of a few new PyScript syntaxes brought into HTML. Inside the tags, write print('Hello world') the infamous right of passage in coding. Run your code and walla, you have Python in the browser, easy hey?

Now switch over to main.py and link to index.html. Copy print('Hello world') statement from your code and paste it into main.py. Update your PyScript tag to look like this <py-script src="main.py"></py-script>. If you run the code again you shouldn’t see any changes, ‘Hello World’ should be printing as normal, but the difference this time is it’s now a separate Python file, great work.

Before moving on, add a new tag to your button <button pys-OnClick="convert"></button>, this calls the function we’ll set up in main.py. Okay, let’s focus on building out our main.py program and seeing more of what PyScript can do.

2.2 PyScript’s Elements() Class

Alright, now in main.py it’s time to set your objects, this is going to allow PyScript to manipulate HTML elements. We do this by calling Elements('Element-ID') class, where 'Element-ID' is for example name in id="name" and assigning it to a variable. For example, here’s how to create an object for the first input in index.html.

input_name = Element('name')

Go ahead and repeat this for email and output.

Remember, an object is an instance of a class, and a class has it’s own methods, i.e. functions designed for class objects. Let’s take a quick look at some other methods. If we run dir(input_name) we can see all the methods associated with the class, let’s print a few out.

print(input_name.id)
print(input_name.element)
print(input_name.value)

Feel free to remove these print examples or highlight them and press CTRL/CMD + / to comment them out.

3. Produce a complete, simple web app

Okay, now you’ve got a better idea of what’s going on, let’s build out the main.py more.

The goal here is to take the user’s input from the input fields in index.html, let PyScript manipulate them and then display it back to the user.

3.1 Code Check

Let’s check our code before we go any further, here’s index.html.

...
  <body>
    <section class="container">
      <section class="notification">
        <h1 class="title">Title</h1>
        <label for="name">Name</label>
        <input id="name" class="textarea">
        <label for="email">Email</label>
        <input id="email" class="textarea">
        <button class="button" id="convert" pys-onClick="convert">Convert</button>
      </section>
      <section class="notification">
        <div id="#output"></div>
      </section>
    </section>
    <py-script src="main.py"></py-script>
  </body>
</html>

And here’s main.py so far.

input_name = Element('name')
input_email = Element('email')
output_area = Element('output')

3.2 Main.py Function

Great work, so our button in index.html has an attribute of pys-onClick="convert" which invokes a Python function called convert. Let’s code the convert function now.

def convert(*args, **kwargs):
  pass

Currently, the convert function simply passes without doing anything else, it’s up to you to write this code. Implement an f string that writes to the output_area. Now to do this, there’s a write method, that’s convenient. Use output_area.write(), don’t forget to include input_name.value and input_email.value which uses the inputs values.

If you’re stuck, write an f string like this f'Hello, my name is {name}, and my email is {email} but using the methods listed above.

Awesome, now it’s the moment of truth, run your code and see what you’ve got!

3.3 Publish & Share

If all goes well, you’ll have your first PyScript application running on HTML & Python, cool!

Now it’s time to tell the world, tweet @mrashleyball and @pyscript_dev – we’d love to hear!

If you’d like to see my own implementation, here’s Mailto Me. A simple way to generate HTML mailto links with embedded subject lines & body messages. Feel free to use it to help you with your project.

If you’d like to contact me, feel free to reach out over Twitter. Feel free to check out my blog mrash.co for regular articles on Cyber Security, Python Programming and Work-Life. I also have a monthly newsletter to keep in touch.

Thanks for reading!

About The Author
Mr Ash

Mr Ash

“Learn, create, share, repeat.” • IT teacher, former web designer, learning CyberSec • Road to #100DaysOfHacking on Hackers Learning Path.
Share This Article
LinkedIn
Twitter
Facebook
WhatsApp
Email

Monthly Newsletter

Learn about cyber security, hacking guides & python programming.

Leave A Comment

Leave a Reply

Your email address will not be published.

More Content

Monthly Newsletter

Learn about cyber security, hacking guides & python programming.

This site uses cookies and other tracking technologies to assist with navigation, monitor site usage and web traffic, assist with our promotional and marketing efforts, and customize and improve our services, as set out in our privacy policy