Как работать с PyScript — фреймворком для фронтенда на Python

В веб-разработке Python используется в основном на бэкенде с такими фреймворками, как Django и Flask. А сегодня, к старту курса по Fullstack-разработке на Python, расскажем о PyScript, который даёт возможность запускать Python прямо в HTML.
До сих пор Python не имел такой большой поддержки на фронтенде, как другие языки, например JavaScript. Но, к счастью, разработчики Python создали несколько библиотек для поддержки своего любимого языка в браузере, например Brython.
А на конференции PyCon 2022 анонсировали фреймворк PyScript от Anaconda для использования Python в вебе с помощью стандартного HTML. Вот твит о запуске фреймворка:
Нам понадобится
Чтобы писать код по этой статье, вам понадобятся следующие инструменты и знания:
любимый текстовый редактор или интегрированная среда разработки;
браузер (рекомендуется Google Chrome).
Что такое PyScript?
PyScript — это фронтенд-фреймворк для создания программ на Python в браузере с использованием HTML-интерфейса, а также мощи Emscripten, Pyodide, WASM и других современных веб-технологий. В соответствии со своими целями он призван дать такие возможности:
упрощённый и чистый API;
систему подключаемых и расширяемых компонентов;
поддержку и расширение стандартного HTML для чтения и надёжных, и своенравных компонентов с миссией «Программирование для 99% [людей]».
В последние 20 лет Python и продвинутые языки пользовательского интерфейса, такие как HTML, CSS и JavaScript, не работали вместе. В Python не было простого механизма создания привлекательных пользовательских интерфейсов для подготовки и развёртывания приложений, а на освоение современных HTML, CSS и JavaScript может уйти много времени.
С возможностью применять в Python соглашения из HTML, CSS и JavaScript решаются не только эти две проблемы, но и те, что связаны с разработкой, подготовкой к развёртыванию, собственно развёртыванием и распространением веб-приложений.
Однако PyScript не заменит JavaScript в браузере, а, скорее, даст разработчикам Python, особенно дата-сайентистам, больше гибкости и мощи.
Почему PyScript?
С PyScript язык получает последовательные правила оформления кода, простоту освоения и больше выразительности за счёт:
поддержки в браузере: с PyScript появляются поддержка Python и возможность размещения без серверов и конфигурации;
возможности взаимодействия Python и JavaScript: в программах может осуществляться двунаправленная связь между объектами и пространствами имён Python и JavaScript;
поддержки экосистемы: PyScript позволяет использовать популярные пакеты Python (Pandas, NumPy и др);
гибкости фреймворка: PyScript — гибкий фреймворк, на основе которого разработчики легко могут создавать расширяемые компоненты прямо в Python;
управления средой: PyScript позволяет разработчикам определять файлы и пакеты для запуска кода своей страницы;
разработки пользовательского интерфейса: с PyScript разработчики могут легко работать с доступными компонентами пользовательского интерфейса (кнопками, контейнерами и др.).
Начало работы с PyScript
PyScript довольно просто освоить: следуйте инструкциям на сайте или загрузите zip-архив.
В этой статье научимся использовать PyScript через сайт, связав компоненты в HTML-файле, и выведем первый Hello World в PyScript.
Создаём HTML-файл
HTML-файл нужен для отображения текста в браузере с помощью текстового редактора / интегрированной среды разработки:
Привязываем PyScript
После создания HTML-файла в теге <head> нужно указать в нём ссылку на PyScript, чтобы получить доступ к интерфейсу PyScript:
Выводим в браузере
Связав PyScript с HTML-файлом, выводим Hello World с помощью тега <py-script>, который позволяет запускать многострочные программы на Python и выводить результат выполнения на странице браузера. Помещаем тег внутри тега <body>:
Весь код HTML-файла:
В браузере вы должны увидеть:

Совет: в редакторе VSCode, чтобы перезагружать страницу при обновлении HTML-файла, используйте плагин Live Server.
Другие операции с PyScript
Прикрепляем метки к элементам
В PyScript переменные из кода на Python в HTML передаются с помощью метода write из модуля pyscript, в теге <pyscript>. Используя атрибут id, передаём строки, отображаемые в виде обычного текста.
В методе write принимаются две переменные: значение id и переменная, которая будет предоставлена:

Запускаем REPL в браузере
В PyScript код Python запускается и через интерфейс. С помощью тега <py-repl> компонент REPL добавляется на страницу, где пишется выполняемый код:
Мы получим вывод:

Импортируем файлы, модули и библиотеки
Одно из преимуществ PyScript — его гибкость. Здесь можно импортировать локальные файлы, встроенные модули или сторонние библиотеки. Для объявления зависимостей понадобится тег <py-env>.
Для локальных файлов Python можно поместить код в файл с расширением .py, а пути к локальным модулям указываются в строках вида пути: ключ (YAML) тега <py-env>.
Создадим файл Python example.py с функциями:
Импортируем его в HTML с тегом <py-env>, в <head>:
Вот что вернётся:

PyScript поддерживает сторонние библиотеки:
Настраиваем метаданные
С помощью тега <py config> в формате YAML можно задать и настроить общие метаданные приложения PyScript. Использовать этот тег можно так:
Вот необязательные значения, которые предоставляются <py-config>:
autoclose_loader (логическое значение): если оно false, загрузочный экран-заставка в PyScript не закроется;
name (строка): название пользовательского приложения;
version (строка): его версия;
runtimes (среды выполнения): список конфигураций среды выполнения с полями src, name и lang.
Заключение
Вы узнали, что такое PyScript и как его использовать в HTML-файлах для запуска кода Python в браузере, а также познакомились с различными операциями и функционалом PyScript. С помощью PyScript проще запускать и выполнять операции Python в вебе. Это отличный инструмент для всех, кому не терпится опробовать Python в Интернете.
PyScript находится на ранних стадиях разработки и активно дорабатывается. Он остаётся на стадии альфа-тестирования и сталкивается с известными проблемами, такими как время загрузки, которое может повлиять на удобство использования (на момент написания этой статьи другие операции не отображались из-за проблем с производительностью). Поэтому пока не стоит использовать его в продакшене: вероятно, будет много критических изменений.
А пока PyScript развивается, мы поможем прокачать ваши навыки или с самого начала освоить профессию, актуальную в любое время:
How can I include python script in a HTML file?
![]()
Something like this, if you want to create an html, not necessarily display it:
![]()
There’s now a solution to this, the solution is PyScript. This is a python framework that enables you to embed python scripts in HTML. Check out the sample code below.
If your web server supports it, you could run it as a CGI script to output an HTML file — more information here: http://www.penzilla.net/tutorials/python/cgi/
You would need to modify your script to ouput valid HTML, but that tutorial should get you started.
![]()
Not possible. Python isn’t like PHP; I can’t just do this
And be good to go.
However, if your web server has a Python interpreter (most all do, these days), you can write CGI (common gateway interface) scripts to make Python code run on your webpage.
If you’re trying to generate dynamic content (like change words in HTML), Javascript or PHP is better. Python is more suited to web applications.
if the script is in a server , you can run it using remote funcion call through JSON-RPC
you may refer the JSON-RPC documentation here
You can use <% %>tag in html and inside this you can write your python code.
Name already in use
pyscript / docs / tutorials / getting-started.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
23 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Getting started with PyScript
This page will guide you through getting started with PyScript.
PyScript does not require any development environment other than a web browser (we recommend using Chrome) and a text editor, even though using your IDE of choice might be convenient.
If you’re using VSCode, the Live Server extension can be used to reload the page as you edit the HTML file.
There is no installation required. In this document, we’ll use the PyScript assets served on https://pyscript.net.
If you want to download the source and build it yourself, follow the instructions in the README.md file.
Your first PyScript HTML file
Here’s a «Hello, world!» example using PyScript.
Using your favorite editor, create a new file called hello.html in the same directory as your PyScript, JavaScript, and CSS files with the following content, and open the file in your web browser. You can typically open an HTML by double-clicking it in your file explorer.
Using a Local Server
In some situations, your browser may forbid loading remote resources like pyscript.js and pyscript.css when you open an HTML file directly. When this is the case, you may see your Python code in the text of the webpage, and the browser developer console may show an error like «Cross origin requests are only supported for HTTP.» The fix for this is to use a simple local server to make your html file available to the browser.
If you have python installed on your system, you can use it’s basic built-in server for this purpose via the command line. Change the current working directory of your terminal or command line to the folder where your HTML file is stored. From this folder, run python -m http.server 8080 —bind 127.0.0.1 in your terminal or command line. With the server program running, point your browser to http://localhost:8080 to view the contents of that folder. (If a file in that folder is called index.html , it will be displayed by default.)
A more complex example
Now that we know how you can create a simple ‘Hello, World!’ example, let’s see a more complex example. This example will use the Demo created by Cheuk Ting Ho. In this example, we will use more features from PyScript.
Setting up the base index file
Let’s create a new file called index.html and add the following content:
In this first step, we have created the index file, imported pyscript.css and pyscript.js . We are ready to start adding the elements we need for our application.
Importing the needed libraries
For this example, we will need to install pandas and matplotlib . We can install libraries using the <py-config> tag so we can import them later. Please refer to the <py-config> documentation for more information.
Importing the data and exploring
Now that we have installed the needed libraries, we can import and explore the data. In this step, we need to create a <py-script> tag to import our dependencies, read the data with pandas and then use py-repl to explore the data.
You may want to read the <py-script> and <py-repl> documentation for more information about these elements.
Note that we are adding ice_data to py-repl to pre-populate the REPL with this variable, so you don’t have to type it yourself.
Creating the plot
Now that we have the data, we can create the plot. We will use the matplotlib library to make the plot. We will use the display API to display the plot on the page. You may want to read the display documentation for more information.
Select specific flavours
Now that we have a way to explore the data using py-repl and a way to create the plot using all of the data, it’s time for us to add a way to select specific flavours.
Run Python in HTML

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.
Please enable JavaScript
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 File — index.html
Python File — script.py
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 File — index.html
Now, the Python script will look as follows.
Python File — script.py
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.
Inside the templatetags folder, create a Python file named my_custom_tags.py .
Inside this file, add the following code.
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.
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.