analitics

Pages

Saturday, February 15, 2020

Python 3.7.5 : Use Brython in web development to avoid javascript.

The tutorial for today is about how can avoid the javascript and use python script in webdevelopment using the Brython.
Brython's goal is to replace Javascript with Python, as the scripting language for web browsers. see the official webpage.
It is necessary to include brython.js and to run the brython() function upon page load using the onload attribute of the BODY tag.
You can use python language in the HTML file or you can write it in a separate file, and to load it using the src attribute of the script tag:
<html>
<head>
<script src="/brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python" src="test.py"></script>
<input id="zone" autocomplete="off">
<button id="mybutton">click!</button>
</body>
</html>
Let's see one simple example with one edit and button bind
<html>
<head>
<script src="/brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document, alert
def echo(ev):
 alert(document["zone"].value)
document["mybutton"].bind("click", echo)
</script>
<input id="zone">
<button id="mybutton">click !</button>
</body>
</html>
When I click on the button, the onclick event calls and run the echo() function and gets the value of the INPUT element, through its id named zone and show the message.
Is fast and works great with javascripts libraries, see the example with THREE demo.
from browser import document, window

THREE = window.THREE

camera = THREE.PerspectiveCamera.new(75, 1, 1, 10000)
camera.position.z = 1000
scene = THREE.Scene.new()
geometry = THREE.CubeGeometry.new(200, 200, 200)
material = THREE.MeshBasicMaterial.new({"color": "#ff0000", "wireframe": True})
mesh = THREE.Mesh.new(geometry, material)
scene.add(mesh)

renderer = THREE.WebGLRenderer.new()
renderer.setSize(444, 444)

document <= renderer.domElement
renderer.render(scene, camera)

def animate(i):
    # note: three.js includes requestAnimationFrame shim
    window.requestAnimationFrame(animate)

    mesh.rotation.x += 0.01
    mesh.rotation.y += 0.02

    renderer.render(scene, camera)   

animate(0)