- Say Hello to PyScript
- What is PyScript? Well, here are some of the core components:
- PyScript: Run Python in HTML File – Step by Step Tutorial
- Important Things About PyScript
- 1. Let’s Create Our First Program with PyScript
- 2. Print Current Date Time
- 3. Bokeh Chart with PyScript
- Conclusion
- Run Python in HTML
- Run Python Scripts in HTML using PHP
- Run Python script in HTML using Django
Say Hello to PyScript
PyScript is a framework that allows users to create rich Python applications in the browser using HTML’s interface and the power of Pyodide, WASM, and modern web technologies. The PyScript framework provides users at every experience level with access to an expressive, easy-to-learn programming language with countless applications.
What is PyScript? Well, here are some of the core components:
- Python in the browser: Enable drop-in content, external file hosting, and application hosting without the reliance on server-side configuration
- Python ecosystem: Run many popular packages of Python and the scientific stack (such as numpy, pandas, scikit-learn, and more)
- Python with JavaScript: Bi-directional communication between Python and Javascript objects and namespaces
- Environment management: Allow users to define what packages and files to include for the page code to run
- Visual application development: Use readily available curated UI components, such as buttons, containers, text boxes, and more
- Flexible framework: A flexible framework that can be leveraged to create and share new pluggable and extensible components directly in Python
All that to say… PyScript is just HTML, only a bit (okay, maybe a lot) more powerful, thanks to the rich and accessible ecosystem of Python libraries.
In short, our mission is to bring programming for the 99%.
PyScript: Run Python in HTML File – Step by Step Tutorial
If you are a python developer, and thinking that how cool if I can write my python code directly into HTML as all the Javascript developers do. Well, there is good news for all the Python developers. Here is the step by step tutorial for how to run python in HTML using PyScript.
In a keynote speech at PyCon US 2022, Anaconda company’s CEO Peter Wang revealed a new project named PyScript. Which is a JavaScript framework. It allows us to create Python applications in web browsers. It will allow us to embed Python code directly into HTML files. Just like we use JavaScript code in our HTML files.
Important Things About PyScript
- It allows us to write python code into our HTML file. So we can use Python’s libraries within our browser.
- As we use PyScript, we don’t need to worry about deployments. Everything happens in a web browser. We can share our HTML files with anyone containing fancy dashboards or any chars data. They can directly run it in a web browser without any complex setup.
- Run Many popular libraries of Python like pandas, numpy etc.
- PyScript allows us to write python code with the help of 3 main components:
- Py-env: It defines the python packages list which needs to run your code.
- Py-script: In this tag, the user will write their python code.
- Py-repl: It will Create a REPL component. The REPL component executes the code user enters and displays the result of the code in the browser.
1. Let’s Create Our First Program with PyScript
You can download the alpha release of PyScript on pyScript.net. We’ll use the CDN of one stylesheet and one script in our HTML file. Add below CDNs to your HTML .
Our Hello world program will look something like this:
print("Hello World!") When you run this HTML file into your browser, it will print Hello World. Something like this:
2. Print Current Date Time
from datetime import datetime print(f"It's now ") In the above example, we are using python’s DateTime library for current DateTime.
3. Bokeh Chart with PyScript
Let’s create a chart to display the number of fruits sells during a month.
- bokeh Bokeh Chart in PyScript
import json import pyodide from js import Bokeh, console, JSON from bokeh.embed import json_item from bokeh.plotting import figure from bokeh.resources import CDN fruits = ['Apples', 'Banana', 'Mango', 'Grapes', 'Strawberries'] counts = [5, 3, 4, 4, 6] p = figure(x_range=fruits, height=350, title="Fruit Counts", toolbar_location=None, tools="") p.vbar(x=fruits, top=counts, width=0.9) p.xgrid.grid_line_color = None p.y_range.start = 0 p_json = json.dumps(json_item(p, "chart")) Bokeh.embed.embed_item(JSON.parse(p_json)) When you run this code, you will see a chart like;
As you see how easily we can create a graph into our HTML file only. There is no need to create complex components to display a chart like this. That’s how simply you can use PyScript to run python in HTML.
Conclusion
This project is still in the alpha stage, so maybe we can see many more new things in the upcoming days. PyScript looks very promising for python developers, but there might be a lot of security issues. Also, we are running Python libraries into the browser, so execution time is also high.
All these concerns might be resolved in upcoming releases. Comment down your thoughts about this new technology.
Run Python in HTML
- Run Python Scripts in HTML using PHP
- Run Python script in HTML using Django
Web Development is a vast field, and there are endless opportunities and things that we can do. With complexity and demand come requirements. When building dynamic web pages, we often have to perform tasks that require the assistance of some programming language such as Python or PHP. In this article, we will learn how to run a Python script in HTML. We will talk about a few ways in which we can achieve this.
Run Python Scripts in HTML using PHP
We can use PHP or Hypertext Preprocessor to run Python scripts in HTML. Refer following code depicts a simple example.
html> head> title>Running a Python scripttitle> echo shell_exec("python script.py"); ?> head> body> body> html>
a = 2000 b = 21 print(f"a = a>") print(f"b = b>") print(f"a + b = a + b>")
This will print the following in the console.
If we want to pass some values to the Python scripts, we can use the following code.
html> head> title>Running a Python scripttitle> echo shell_exec("python script.py \"Parameter #1\" \"Parameter #2\""); ?> head> body> body> html>
Now, the Python script will look as follows.
import sys a = sys.argv[1] b = sys.argv[2] print(f"a = a>") print(f"b = b>") print(f"a + b = a + b>")
The output will remain the same, as shown above.
Run Python script in HTML using Django
Django is a famous and robust Python-based web development framework. Since it is Python-based, it makes it easier to run Python scripts inside the HTML. The way we do this is by using template tags. Django has some pre-built template tags such as date , linebreaks , safe , random , etc. You can learn more about them here.
Since Django is very customizable, it offers developers an easy way to create their custom template tags. Using template tags, we can return data to HTML templates, which can be embedded inside the HTML template.
Follow the following steps to create a simple template tag. We are assuming that we have a core application in our Django project.
Create a new directory, templatetags , inside the core application. The app directory should look something like this.
core/ __init__.py models.py admin.py views.py urls.py . templatetags/ __init__.py .
Inside the templatetags folder, create a Python file named my_custom_tags.py .
Inside this file, add the following code.
from django import template register = template.Library() @register.simple_tag def my_tag(): return "Hello World from my_tag() custom template tag."
my_custom_tags.py module will hold all the custom template tags. As shown in the code above, my_tag is a custom template tag that we just created and now it can be used inside any HTML template. This template tag will return «Hello World from my_tag() custom template tag.» this string to the template. We can create even more template tags here to perform specific and common tasks.
Now that we have created our first template tag, it is time to load it inside our HTML template and use it.
html lang="en" dir="ltr"> head> title>Introtitle> head> body> p> p> body> html>
We first load the my_custom_tags.py module inside the template. Once the module is loaded, we can now use the template tags defined inside the my_custom_tags module. Note that it is important to first load a module with custom template tags before using those template tags.
Instead of using a template tag, we can also create an end-point and make an AJAX request to that end-point to perform some task or get some data. We can use fetch() or jquery or any other available method to make an AJAX request. While making an end-point to handle an AJAX request, it is important to ensure that the end-point is secure and doesn’t give easy access to sensitive data or website features. Since anyone can make AJAX requests if they know the end-point, we can add CSRF ( Cross Site Request Forgery ) validation to it and configure it to handle only POST requests. The POST data should contain the CSRF token.
You can learn more about CSRF here
Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.