Techno Blender
Digitally Yours.

3 Things You Must Know Before Building with PyScript | by Braden Riggs | May, 2022

0 77


After recently running into a few blockers, bugs, and quirks I wanted to make a guide for building with PyScript, Python and HTML

Photo by David Clode on Unsplash

For anyone who hasn’t already heard PyScript, which debuted at PyCon 2022, is a browser-embedded python environment, built on top of an existing project called Pyodide. This project, to the shock of long-term Pythonistas and web developers, seamlessly blends (well almost) JavaScript and Python in a bi-directional environment allowing developers to utilize Python staples such as NumPy or Pandas in the browser.

After playing with the project for a few days I wanted to share a few learnings and gotchya’s that tripped me up on my journey to master PyScript.

Prelude: A Crash Course in PyScript
1. Package Indentation Matters!
2. Local File Access
3. DOM Manipulation

A Crash Course in PyScript

To get started using PyScript we first have to link our HTML file with the PyScript script as we would for any ordinary javascript file. Additionally, we can link the PyScript style sheet to improve usability.

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

With PyScript imported in the head of our HTML file, we can now utilize the <py-script> tag in the body of our HTML to write python code.

<body>
<py-script>
for i in ["Python", "in", "html?"]:
print(i)
</py-script>
</body>

Yep! It really is just that simple to get started. Now, where do things get tricky?

Package Indentation Matters

One of the big advantages of using PyScript is the ability to import Python libraries such as NumPy or Pandas, which is first done in the Head using the <py-env> tag and then inside of the <py-script> tag just like you would in regular Python.

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

On the surface, this may seem straightforward but note the indentation of the packages within <py-env>.

    <py-env>
- numpy
- pandas

</py-env>

Turns out that if there is any indentation you’ll receive a ModuleNotFoundError: No module named ‘pandas’ or ModuleNotFoundError: No module named ‘numpy’ ) for PyScript. This error caught me off guard initially since indentation in Python is so important.

Local File Access

JavaScript handles file access very differently compared to Python… as it should given the relationship between web development and privacy and security. Hence Vanilla JavaScript does not have direct access to local files. Since the PyScript project is built on top of JavaScript your Python code won’t be able to access local files like you might be used to.

PyScript does offer a solution to file access in the <py-env> tag. In addition to importing packages, you can also import files such as CSVs or XLSXs.

    <py-env>
- numpy
- pandas
- paths:
- /views.csv

</py-env>

Again note the indentation as in this case the CSV must be indented in relation to the paths.

With the file included in the path, you can read it within your <py-script> code.

<py-script>
import pandas as pd
df = pd.read_csv("views.csv")
</py-script>

DOM Manipulation

For anyone who has worked in web development, you should be familiar with the DOM or Document Object Model. DOM Manipulation is common in most web applications as developers typically want their websites to interact with users, reading inputs and responding to button clicks. In the case of PyScript this raises an interesting question how do buttons and input fields interact with the Python code?

Again PyScript has a solution to this, however, it mightn’t be what you expect. Here are a few (of many) examples where PyScript has functionality:

  1. For buttons, you can include pys-onClick=”your_function” parameter to trigger python functions when clicked.
  2. For retrieving user input from within the <py-script> tag document.getElementById(‘input_obj_id’).value can retrieve the input value.
  3. And Finally pyscript.write(“output_obj_id”, data) can write output to a tag from within the <py-script> tag.

We can see these three DOM manipulation techniques put together into one web application that lets users check if a CSV has been added to the PyScript path:

<body>
<form onsubmit = 'return false'>
<label for="fpath">filepath</label>
<input type="text" id="fpath" name="filepath" placeholder="Your name..">
<input pys-onClick="onSub" type="submit" id="btn-form" value="submit">
</form>
<div id="outp"></div> <py-script>
import pandas as pd
def onSub(*args, **kwargs):
file_path = document.getElementById('fpath').value
df = pd.read_csv(file_path)
pyscript.write("outp",df.head())
</py-script>
</body>

These examples aren’t comprehensive as the project also supports visual component tags.

Conclusion

PyScript is a wonderful step in the right direction for bringing some excellent Python packages into the web development space. With that said it still has a bit of growing to do and there are many improvements that need to be made before the project sees widespread adoption.

Show some support to the team working on this awesome project: https://github.com/pyscript

Leave a comment with any other insights or gotchya’s that you might have experienced working with PyScript and I’ll make a part 2.

Photo by Jan Kahánek on Unsplash


After recently running into a few blockers, bugs, and quirks I wanted to make a guide for building with PyScript, Python and HTML

Photo by David Clode on Unsplash

For anyone who hasn’t already heard PyScript, which debuted at PyCon 2022, is a browser-embedded python environment, built on top of an existing project called Pyodide. This project, to the shock of long-term Pythonistas and web developers, seamlessly blends (well almost) JavaScript and Python in a bi-directional environment allowing developers to utilize Python staples such as NumPy or Pandas in the browser.

After playing with the project for a few days I wanted to share a few learnings and gotchya’s that tripped me up on my journey to master PyScript.

Prelude: A Crash Course in PyScript
1. Package Indentation Matters!
2. Local File Access
3. DOM Manipulation

A Crash Course in PyScript

To get started using PyScript we first have to link our HTML file with the PyScript script as we would for any ordinary javascript file. Additionally, we can link the PyScript style sheet to improve usability.

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

With PyScript imported in the head of our HTML file, we can now utilize the <py-script> tag in the body of our HTML to write python code.

<body>
<py-script>
for i in ["Python", "in", "html?"]:
print(i)
</py-script>
</body>

Yep! It really is just that simple to get started. Now, where do things get tricky?

Package Indentation Matters

One of the big advantages of using PyScript is the ability to import Python libraries such as NumPy or Pandas, which is first done in the Head using the <py-env> tag and then inside of the <py-script> tag just like you would in regular Python.

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

On the surface, this may seem straightforward but note the indentation of the packages within <py-env>.

    <py-env>
- numpy
- pandas

</py-env>

Turns out that if there is any indentation you’ll receive a ModuleNotFoundError: No module named ‘pandas’ or ModuleNotFoundError: No module named ‘numpy’ ) for PyScript. This error caught me off guard initially since indentation in Python is so important.

Local File Access

JavaScript handles file access very differently compared to Python… as it should given the relationship between web development and privacy and security. Hence Vanilla JavaScript does not have direct access to local files. Since the PyScript project is built on top of JavaScript your Python code won’t be able to access local files like you might be used to.

PyScript does offer a solution to file access in the <py-env> tag. In addition to importing packages, you can also import files such as CSVs or XLSXs.

    <py-env>
- numpy
- pandas
- paths:
- /views.csv

</py-env>

Again note the indentation as in this case the CSV must be indented in relation to the paths.

With the file included in the path, you can read it within your <py-script> code.

<py-script>
import pandas as pd
df = pd.read_csv("views.csv")
</py-script>

DOM Manipulation

For anyone who has worked in web development, you should be familiar with the DOM or Document Object Model. DOM Manipulation is common in most web applications as developers typically want their websites to interact with users, reading inputs and responding to button clicks. In the case of PyScript this raises an interesting question how do buttons and input fields interact with the Python code?

Again PyScript has a solution to this, however, it mightn’t be what you expect. Here are a few (of many) examples where PyScript has functionality:

  1. For buttons, you can include pys-onClick=”your_function” parameter to trigger python functions when clicked.
  2. For retrieving user input from within the <py-script> tag document.getElementById(‘input_obj_id’).value can retrieve the input value.
  3. And Finally pyscript.write(“output_obj_id”, data) can write output to a tag from within the <py-script> tag.

We can see these three DOM manipulation techniques put together into one web application that lets users check if a CSV has been added to the PyScript path:

<body>
<form onsubmit = 'return false'>
<label for="fpath">filepath</label>
<input type="text" id="fpath" name="filepath" placeholder="Your name..">
<input pys-onClick="onSub" type="submit" id="btn-form" value="submit">
</form>
<div id="outp"></div> <py-script>
import pandas as pd
def onSub(*args, **kwargs):
file_path = document.getElementById('fpath').value
df = pd.read_csv(file_path)
pyscript.write("outp",df.head())
</py-script>
</body>

These examples aren’t comprehensive as the project also supports visual component tags.

Conclusion

PyScript is a wonderful step in the right direction for bringing some excellent Python packages into the web development space. With that said it still has a bit of growing to do and there are many improvements that need to be made before the project sees widespread adoption.

Show some support to the team working on this awesome project: https://github.com/pyscript

Leave a comment with any other insights or gotchya’s that you might have experienced working with PyScript and I’ll make a part 2.

Photo by Jan Kahánek on Unsplash

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment