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.
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
Please enable JavaScript
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.
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.
Как работать с 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 развивается, мы поможем прокачать ваши навыки или с самого начала освоить профессию, актуальную в любое время:
PyScript: Loading Python Code in the Browser
Today, you can now use Pyscript to run Python code in the web browser. This has enormous potential for AI, ML, Data Scientists, and regular Python developers. I often develop backend applications in Django and Flask, and the possibilities of writing both frontend and backend code in Python are intriguing.
This article is about how to load Python code in the web browser. There are a number of methods. Knowing these methods can improve development and debugging. I will also show methods of loading Python modules.
At this time, Pyscript is in alpha.
Including Python in the browser is amazingly simple. Include two tags in the HTML head:
In this article I will discuss the following methods:
- Include Python with HTML
- Load Python from a file
- Load Python from multiple source files
- Load Python and execute Python after a page is displayed
- Load Python using Pyodide
HTML and JavaScript:
- Write your own Pyscript Replacement
History
It has been possible to run Python in the browser for several years (2018). Pyscript does not actually interpret Python code. Pyodide (Pie-O-Dide) is the magic behind Pyscript. In my fifth method in this article, I will show an example that does not use Pyscript and directly loads Python using JavaScript and the Pyodide library.
Understanding Pyodide is important to understanding how to use Pyscript. Pyscript’s genius is wrapping Pyodide to completely hide it for most HTML/Python applications. However, you will import some functions from Pyodide. Example: from pyodide.http import pyfetch . I use that import to provide a replacement for requests which is not available in Webassembly based Python (Python in the browser).
Be sure to read the last section “Write your own Pyscript”.
Method 1 – Include Python with HTML
This method uses the <py-script> tags just like the <script> tags. Insert your Python code between the <py-script> and </py-script> tags.
You must correctly format the Python code just like a normal .py file. Indentation matters.
Notice that I am wrapping the Python code in a main() function. In a future article when I discuss async Python in the web browser, the reason will become apparent.
example1.html
This example loads in the web browser and displays “Loading page …”. Once the Python code executes, the page changes to “Hello world”. The entire process takes about two seconds. I expect this time to decrease significantly as Pyscript reaches production quality.
This example demonstrates how to get a DOM element by ID:
and then write to that element:
Pyscript has a library named pyscript that has built-in functions to make this easy. The following one line of code replaces the two previous lines.
The source code for pyscript.write() is here. The signature is:
Notice append . If true you can append a <div> as a child to the specified element ID.
Another interesting item is the class Element (link):
With those improvements, the updated example becomes:
example1.html version 2
The key is to understand how to get DOM elements and then modify them. This is an important concept for code that runs in the browser.
Benefits:
- This example can be loaded into the web browser from a local file.
Drawbacks:
- Mixing HTML, JavaScript, and Python in the same file is hard to manage.
Method 2 – Load Python from a file
This method uses the <py-script src=»https://www.jhanley.com/blog/pyscript-loading-python-code-in-the-browser/filename.py»> style to load Python from a separate file. To the untrained eye, you might not even notice that Python is being loaded into the web browser.
example2.html
This example loads the Python as a separate step similar to loading CSS or JavaScript resources. This example displays “Loading page …”. Once the Python code load and executes, the page changes to “Hello world”. The entire process takes about two seconds. I expect this time to decrease significantly as Pyscript reaches production quality.
At this time, the defer keyword is not supported. This example will not work:
As Pyscript becomes popular, this would be a nice feature to lazy load Python while the DOM is generated.
Benefits:
- Separating Python from HTML simplifies development and testing.
Drawbacks:
- This example cannot be loaded into the web browser from a local file. This method requires a web server.
Simple web server for local Pyscript development:
Method 3 – Load Python from multiple source files
Typical applications are split into multiple source files. Pyscript supports including multiple files. There is a limitation where the files cannot have the same name even if located in different directories.
Once the source files are declared, you can then import functions from those files.
Method 4 – Load Python and execute Python after a page is displayed
This method uses pyfetch() to download a file containing Python code from a web server. An important undocumented detail is that you must import the asyncio package, otherwise, you will get unusual errors. This took me a while to figure out. Once the code is downloaded, it is executed.
Benefits:
- Separating Python from HTML simplifies development and testing.
- This method permits executing Python on demand instead of when the page loads.
- Demonstrates how to use pyfetch() and the asyncio package
Drawbacks:
- This example cannot be loaded into the web browser from a local file. This method requires a web server.
Method 5 – Load Python using Pyodide
Pyodide is the magic behind Pyscript. In this example, I will show how to load and execute Python without loading Pyscript.
This is a simple example of how easy it is to load a Python source file from a web server and run that Python code in the web browser.
Importing Python Packages
Pyscript defines the tag <py-env> which defines the Python packages your program requires.
You can also declare the package version:
In some cases, you do not need to use <py-env> . I have not figured out yet when using <py-env> is required. My examples above, do not use <py-env> , they just import the packages from the Python code. This might be because the packages are already part of the Pyscript downloads. numpy is an example that requires declaration in <py-env> . Pyscript is brand new and my knowledge is limited but I am digging into everything.
Read Method 3 – Load Python from multiple source files for details on how to include multiple source files.
Write your own Pyscript Replacement
If you want to surprise a few developers, try this example. Here I show you how to create your own DOM tag element using, for example, your name. In this example, I use jhanley-python to signify the Python code to execute:
If you study that example, you will see how easy it is to implement Python in the browser using Pyodide. Pyscript offers many more features than my simpleton example, but with this, you might be able to contribute to Pyscript by knowing how some things are done.
Move the Javascript to a separate file and few would notice how this is done.
Pyscript Issue
Pyscript has one issue that my example could be used to fix. For a brief period of time, the Python code is visible in the browser window. This can be fixed by using Javascript and my section that hides a custom DOM element tag. For example:
This code needs to run before the Pyscript libraries start loading.
Summary
I am very intrigued with Pyscript. Writing frontend and backend applications in Python can be very useful. Today, the browser is often used as a display device. I want to use the browser to distribute processing power and move some activity from the server to the browser.
A simple example is uploading a large file for processing such as a spreadsheet. Now the spreadsheet can be processed and displayed in the browser, while only uploading the required rows and columns to the backend for storage. This saves a roundtrip where large amounts of data are transferred over the network.
One can argue that JavaScript does that today. That is true, but there are applications that are very difficult or impossible with JavaScript that is a walk in the park for Python.
The spreadsheet is a simplification of a common problem, but take this to the next step, which is AI, ML, and Data Science. These are areas where Python blows JavaScript away. Importing libraries such as numpy have enormous potential.
More Information
Photography Credits
Heidi Mustonen just started a new photography company in Seattle, WA. Her company in-TENSE Photography has some amazing pictures. I asked her for some images to include with my new articles. Check out her new website.
I design software for enterprise-class systems and data centers. My background is 30+ years in storage (SCSI, FC, iSCSI, disk arrays, imaging) virtualization. 20+ years in identity, security, and forensics.
For the past 14+ years, I have been working in the cloud (AWS, Azure, Google, Alibaba, IBM, Oracle) designing hybrid and multi-cloud software solutions. I am an MVP/GDE with several.
Как связать html и python
Создание игр на Unreal Engine 5
Данный курс научит Вас созданию игр на Unreal Engine 5. Курс состоит из 12 модулей, в которых Вы с нуля освоите этот движок и сможете создавать самые разные игры.
В курсе Вы получите всю необходимую теоретическую часть, а также увидите массу практических примеров. Дополнительно, почти к каждому уроку идут упражнения для закрепления материала.
Помимо самого курса Вас ждёт ещё 8 бесплатных ценных Бонусов: «Chaos Destruction», «Разработка 2D-игры», «Динамическая смена дня и ночи», «Создание динамической погоды», «Создание искусственного интеллекта для NPC», «Создание игры под мобильные устройства», «Создание прототипа RPG с открытым миром» и и весь курс «Создание игр на Unreal Engine 4» (актуальный и в 5-й версии), включающий в себя ещё десятки часов видеоуроков.
Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.
Подписаться
Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.
Подписаться
Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.