Как работать с 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 развивается, мы поможем прокачать ваши навыки или с самого начала освоить профессию, актуальную в любое время:
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.
Getting started with PyScript#
This page will guide you through getting started with PyScript.
Development setup#
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.
Trying before installing#
If you’re new to programming and know nothing about HTML or just want to try some of PyScript features, we recommend using the REPL element in the PyScript REPL example instead so you can have a programming experience in a REPL that doesn’t require any setup. This REPL can be used to have an interactive experience using Python directly.
Alternatively, you can also use an online editor like W3School’s TryIt Editor and just plug the code below into it, as shown in the example page and click the run button.
You could try changing the code above to explore and play with pyscript yourself.
Installation#
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.
Notice the use of the <py-script> tag in the HTML body. This is where you’ll write your Python code. In the following sections, we’ll introduce the eight tags provided by PyScript.
The py-script tag#
The <py-script> tag lets you execute multi-line Python scripts and print back onto the page. For example, we can compute π.
Writing into labeled elements#
In the example above, we had a single <py-script> tag printing one or more lines onto the page in order. Within the <py-script> , you have access to the pyscript module, which provides a .write() method to send strings into labeled elements on the page.
For example, we’ll add some style elements and provide placeholders for the <py-script> tag to write to.
The py-config tag#
Use the <py-config> tag to set and configure general metadata along with declaring dependencies for your PyScript application. The configuration has to be set in either TOML or JSON format. If you are unfamiliar with JSON, consider reading freecodecamp’s JSON for beginners guide for more information. And for TOML, consider reading about it here.
The ideal place to use <py-config> in between the <head>. </head> tags.
The <py-config> tag can be used as follows:
Alternatively, a JSON config can be passed using the type attribute.
Besides passing the config as inline (as shown above), one can also pass it with the src attribute. This is demonstrated below:
where custom.toml contains
This can also be done via JSON using the type attribute. By default, type is set to "toml" if not supplied.
where custom.json contains
One can also use both i.e pass the config from src attribute as well as specify it as inline . So the following snippet is also valid:
This can also be done via JSON using the type attribute.
Note: While the <py-config> tag supports both TOML and JSON, one cannot mix the type of config passed from 2 different sources i.e. the case when inline config is in TOML format while config from src is in JSON format is NOT allowed. Similarly for the opposite case.
This is helpful in cases where a number of applications share a common configuration (which can be supplied via src ), but their specific keys need to be customised and overridden.
The keys supplied through inline override the values present in config supplied via src .
One can also declare dependencies so as to get access to many 3rd party OSS packages that are supported by PyScript. You can also link to .whl files directly on disk like in our toga example.
OR in JSON like
If your .whl is not a pure Python wheel, then open a PR or issue with pyodide to get it added here. If there’s enough popular demand, the pyodide team will likely work on supporting your package. Regardless, things will likely move faster if you make the PR and consult with the team to get unblocked. For example, NumPy and Matplotlib are available. Notice here we’re using <py-script output="plot"> as a shortcut, which takes the expression on the last line of the script and runs pyscript.write(‘plot’, fig) .
Local modules#
In addition to packages, you can declare local Python modules that will be imported in the <py-script> tag. For example, we can place the random number generation steps in a function in the file data.py .
In the HTML tag <py-config> , paths to local modules are provided in the paths: key.
The following optional values are supported by <py-config> :
Name of the user application. This field can be any string and is to be used by the application author for their own customization purposes.
Description of the user application. This field can be any string and is to be used by the application author for their own customization purposes.
Version of the user application. This field can be any string and is to be used by the application author for their own customization purposes. It is not related to the PyScript version.
The version of the config schema which determines what all keys are supported. This can be supplied by the user so PyScript knows what to expect in the config. If not supplied, the latest version for the schema is automatically used.
Type of the project. The default is an “app” i.e. a user application
Name of the author.
Email of the author.
License to be used for the user application.
If false, PyScript will not close the loading splash screen when the startup operations finish.
List of Packages
Dependencies on 3rd party OSS packages are specified here. The default value is an empty list.
Local Python modules are to be specified here. The default value is an empty list.
List of Plugins
List of Plugins are to be specified here. The default value is an empty list.
List of Runtimes
List of runtime configurations, described below. The default value contains a single Pyodide based runtime.
A runtime configuration consists of the following:
URL to the runtime source.
Name of the runtime. This field can be any string and is to be used by the application author for their own customization purposes
Programming language supported by the runtime. This field can be used by the application author to provide clarification. It currently has no implications on how PyScript behaves.
Besides the above format, a user can also supply any extra keys and values that are relevant as metadata information or perhaps are being used within the application.
For example, a valid config could also be with the snippet below:
OR in JSON like
If this "magic" key is present in config supplied via src and also present in config supplied via inline , then the value in the inline config is given priority i.e. the overriding process also works for custom keys.
The py-env tag (Deprecated)#
tag is deprecated as of 2022.09.1 release but you can still use the functionality explained below. It will be removed in the next release. To specify packages in the recommended way, please see the
In addition to the Python Standard Library and the pyscript module, many 3rd-party OSS packages will work out-of-the-box with PyScript.
In order to use them, you will need to declare the dependencies using the <py-env> tag in the HTML head. You can also link to .whl files directly on disk like in our toga example.
If your .whl is not a pure Python wheel, then open a PR or issue with pyodide to get it added here. If there’s enough popular demand, the pyodide team will likely work on supporting your package. Regardless, things will likely move faster if you make the PR and consult with the team to get unblocked.
For example, NumPy and Matplotlib are available. Notice here we’re using <py-script output="plot"> as a shortcut, which takes the expression on the last line of the script and runs pyscript.write(‘plot’, fig) .
Local modules with py-env (Deprecated)#
tag is deprecated as of 2022.09.1 release but you can still use the functionality explained below. It will be removed in the next release. To specify local modules in the recommended way, please see the
In addition to packages, you can declare local Python modules that will be imported in the <py-script> tag. For example, we can place the random number generation steps in a function in the file data.py .
In the HTML tag <py-env> , paths to local modules are provided in the paths: key.
The py-repl tag#
The <py-repl> tag creates a REPL component that is rendered to the page as a code editor, allowing you to write executable code inline.
Visual component tags#
The following tags can be used to add visual attributes to your HTML page.
Adds an input box that can be used to prompt users to enter input values.
Creates a container object that can be used to host one or more visual components that define how elements of <py-box> should align and show on the page.
Adds a button to which authors can add labels and event handlers for actions on the button, such as on_focus or on_click .
Adds a static text title component that styles the text inside the tag as a page title.
All the elements above are experimental and not implemented at their full functionality. Use them with the understanding that the APIs or full support might change or be removed until the visual components are more mature.
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.