Let's throw away JavaScript and write a web front end in Python!

Hi, my name is Kamibayashi, ryo_grid from Ory Lab (http://orylab.com).

Well, everyone! Do you write JavaScript! I also write it. However, I've been writing code in C, Java, Ruby, Python, etc. for a long time, so I'm not familiar with the JavaScript language specification.

So, when I searched for an option to use a language other than JS on the Web front end, I found a Python processing system implemented in the browser JS called Brython (= works in the browser), so I tried it. It was.

Brython - A Python 3 implementation for client-side web programming

Try it anyway

I wrote while wandering the sea of the net. The theme is BMI calculation, which is a common task for programming beginners.

HTML seems to be able to be written like this.

index.html


<!DOCTYPE html>
<html>
    <head>
        <title>Calculate BMI with Brython</title>
        <meta charset="utf-8">
        <script src="static/brython.js"></script>
        <script src="static/brython_stdlib.js"></script>	
    </head>
    <body onload="brython()">
     <script type="text/python" src="static/bmi.py"></script>
        <h1>Calculate BMI with Brython</h1>

        <p>height(Meter)
        <input type="text" id="height" />
        <p>body weight(kilogram)
        <input type="text" id="weight" />
        <br><button id="execute">It's a calculation!</button>

        <div id="result"></div>
    </body>
</html>

Load brython.js corresponding to the processing system and brython_stdlib.js which will correspond to the Python standard library in the head section. Then, let's call the brython () method in onload of the body section. After that, put an input form and a button, and put a div tag with id "result" to display the result by DOM operation.

Write the Python code in a separate file and load it with the type = "text / python" script tag. In addition, although it is a separate file here, it seems that you can also write Python code like writing JS solidly in HTML.

The Python file loaded above looks like this: Grammatically it is Python as it is.

bmi.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from browser import document

def calc_bmi():
    weight = float(document["weight"].value)
    height = float(document["height"].value)
    
    bmi = str(weight/(height*height))
    rslt = document["result"]
    rslt.text = bmi
    
execute_btn = document["execute"]
execute_btn.bind("click", calc_bmi)

The process we are doing is storing the DOM of the button with the id "execute" in the execute_btn variable, and registering the calc_bmi function as a process to fire at the "click" event via it. It seems that the DOM can be obtained with the document module of the browser package.

The calc_bmi function gets the input value from the form, calculates the BMI and sets the result at the id = "result" div tag.

And if you move this, brython.jpg

I feel like this. It worked!

I've put a set of this code at https://github.com/ryogrid/LearnBrython. I also included app.py, which provides the web server function, so if you have a python environment, you can run it immediately with the following.

git clone https://github.com/ryogrid/LearnBrython.git cd LearnBrython pip install flask python app.py => Let's access http://localhost:5000/

It's not like Python, right?

The code I wrote above isn't very Python-like, but officially it seems that all Python syntax is supported.

https://brython.info/static_doc/en/syntax.html

It seems that the standard library is also supported in a fair amount. It's amazing.

https://brython.info/static_doc/en/stdlib.html

Isn't it a performance?

I hope you take a look at the official Gallery,

Gallery

It seems that the heavy processing is working properly. So, I think it's okay if it's not an application that really cares about performance.

Also, it is mentioned at the beginning of the FAQ, so if you want to know more details, I think you should refer to it.

https://brython.info/static_doc/en/faq.html

What's the implementation

Looking at the implementation of Brython on github, it seems that it is not an interpreter, but JIT compilation (translation) to JS before running. Power technique!

https://github.com/brython-dev/brython/blob/master/www/src/py2js.js

If you compile!

Recently, asm.js and WebAssembly, which can be called assemblers for browsers, have appeared. By generating executable code with these, it seems that the performance is close to that when compiling to native code.

Detailed explanation of low-level language asm.js and WebAssembly

Brython may eventually support such things. Keep an eye on it in the future.

in conclusion

I tried Python (Brython) as a web front-end implementation language instead of JavaScript. I also dig a little deeper into Brython.

It's hard to judge whether it can be used in commercial products, but why not give it a try as a hobby professional? Let's enjoy!

PS: I didn't mention it this time, but there seems to be a Python implementation in the browser JS other than Brython, so if you are interested, please refer to the following.

http://stromberg.dnsalias.org/~strombrg/pybrowser/python-browser.html

Recommended Posts

Let's throw away JavaScript and write a web front end in Python!
Let's write a Python program and run it
I want to write in Python! (2) Let's write a test
Write a binary search in Python
Write A * (A-star) algorithm in Python
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
Differences in authenticity between Python and JavaScript
Write the test in a python docstring
Write a short property definition in Python
Write O_SYNC file in C and Python
Write a Caesar cipher program in Python
Scraping a website using JavaScript in Python
Read and write JSON files in Python
Write a simple greedy algorithm in Python
Write a simple Vim Plugin in Python 3
Let's make a web framework with Python! (1)
Let's make a combination calculation in Python
Let's make a web framework with Python! (2)
Write a basic headless web scraping "bot" in Python with Beautiful Soup 4
Put Docker in Windows Home and run a simple web server with Python
Organize python modules and packages in a mess
To execute a Python enumerate function in JavaScript
I wrote a class in Python3 and Java
Create a web map using Python and GDAL
Steps to develop a web application in Python
Launch a web server with Python and Flask
Created a Python library to write complex comprehensions and reduce in an easy-to-read manner
I want to write a triple loop and conditional branch in one line in python
Let's make a leap in the manufacturing industry by utilizing the Web in addition to Python
Write a super simple molecular dynamics program in python
Let's write python code that parses go code and generates go code
Let's make a simple game with Python 3 and iPhone
Read and write single precision floating point in Python
Write tests in Python to profile and check coverage
Write a log-scale histogram on the x-axis in python
Read and write NFC tags in python using PaSoRi
Write code to Unit Test a Python web app
Daemonize and persist Python web apps in Systemd-Ubuntu 18.04.3 LTS
Let's write Python, Ruby, PHP, Java, JavaScript side respectively
Write Python in MySQL
Achieve __END__ in Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
Temporarily save a Python object and reuse it in another Python
[Django3] Display a web page in Django3 + WSL + Python virtual environment
Let's create a script that registers with Ideone.com in Python.
[Python] Chapter 01-03 About Python (Write and execute a program using PyCharm)
Let's create a PRML diagram with Python, Numpy and matplotlib.
Let's make a spot sale service 4 (in Python mini Hack-a-thon)
Get a Python web page, character encode it, and display it
A standard way to develop and distribute packages in Python
Create code that outputs "A and pretending B" in python
I created a class in Python and tried duck typing
Remove leading and trailing whitespace in Python, JavaScript, or Java
How to write a metaclass that supports both python2 and python3
Just try to receive a webhook in ngrok and python
AtCoder ABC168 A case expression solved in Ruby and Python
Write a script in Shell and Python to notify you in Slack when the process is finished
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
A story about everything from data collection to AI development and Web application release in Python (3. AI development)