Introduction to Brython

Brython is made to develop applications for the browser in Python. To enable it, the HTML page must have this structure :
<html>
<head>
<script src="/brython.js"></script>
<script src="/brython_modules.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
# python code here
</script>
</body>
</html>

brython.js is the Brython engine. brython_modules.js includes all the modules in the standard distribution.

The function brython(), defined in brython.js, is executed when the page has finished loading : it scans the Python scripts in the page, ie the code inside script tags with the attribute type="text/python", and runs them.

Here are a few examples of how you can use Brython to interact with a web page.

Initial content

    
    browser is a Python-specific module that defines the objects used to interact with the page ; it is included in brython_modules.js. 

document is an object representing the HTML document ; document[element_id] is the element with attribute id equal to element_id. In these examples, document["buttonN"] is a reference to the button you click on, and document["zoneN"] is the bordered zone at the right of the button.

Setting the attribute text of an element changes its text content.

bind() is a method that defines the function to call when an event occurs on the element. When the user clicks on the element, this event is called "click". The last line means : when the user clicks on the element (here, the button with the text "change the text of an element"), call the function change(). The function takes one argument, an object representing the event.

coloured content


    
    The attributes and methods of the elements are described in the Document Object Model (DOM), which is abundantly documented. One of these attributes is style, which itself has (among many others) the attributes color (text color), backgroundColor (background color), fontWeigth ("bold" or "normal"), fontSize (size of the letters, in pixels).
    

on / off


    
    display is another attribute of DOM elements. Setting it to "none" hides the element.
    


    
    alert is used to display small popup windows.
    

Note that here, since the callback function is short, it is defined in a lambda function.



    
    By default, print() writes message in the browser console window (to open it, do Ctrl+Maj+K on Firefox, Ctrl+Maj+J on Chrome, F12 on IE, etc).
    

Like in Python, the output can be reset by setting sys.stdout to an object with a method write().

initial content


    
    To create DOM elements, Brython provides the module browser.html. It defines classes with the name of all the valid HTML tags in uppercase ; html.B("message") creates the element <B>message<B>
    

To include an element inside another one, Brython uses the operator <= : think of it as a left arrow, not as "inferior or equal". The use of an operator is more concise and avoids having to use a function call.

initial content


    This is the same as the previous example ; Brython provides an alternative syntax, but supports all the standard DOM features.
    



    
    To build a table, we use the tags TABLE, TR, TH and TD. The first attribute passed to the classes defined in browser.html is either a string, another instance of a class, or an iterator on such elements. Here we use a Python generator expression to include several headers (TH) in the first row (TR) of the table, and the same for the table cells (TD) in the next rows.
    

clear() is a method that removes all the element contents.


    
    
    We build the dropdown menu by a SELECT element, using a generator expression with the OPTION elements displayed in the menu.
    

When the user changes the selected option in the menu, the event "change" is triggered on the SELECT box. The function show(event) is called ; event.target is the element itself. A SELECT element has an attribute selectedIndex, the rank of the selected item in the list of options, available by its attribute options. The OPTION element itself has an attribute value, here the option text.



    
    We start by importing the module math, the same as in the Python standard distribution.
    

Canvas allows drawing geometric forms in the page. There again you can easily find documentation and examples.


    
    
    This example uses other mouse events than "click" : "mousedown", "mousemove" and "mouseup". 
    

The mouse position is available by the attributes x, y of the event object.

The position of an element can be changed by defining its attributes left and top.


    
    
    We have seen how to get an element by its id : document[element_id]. 
    

The method get(selector=css_selector) provides a way to select elements based on the CSS selector syntax. Passing the name of a tag returns a list of all the elements with this tag ; passing .zone returns a list of all the elements whose attribute class is set to "zone". You can easily find external resources on CSS selectors.


    
    
    transform is another attribute of style that can make changes to the element, including a rotation by a specified angle.
    


    
    
    The browser window provides 2 functions to start and stop an animation : requestAnimationFrame and cancelAnimationFrame.
    

When the user clicks on the button, the animation is started by calling the function animloop with an arbitrary argument. window.requestAnimationFrame, called with the function itself as argument, returns a reference to the animation. The drawing function, render() is called ; the loop is then executed repeatedly under the control of the animation loop.

In render(), to put the element at a specific location, we use another transform function, translate(x, y). The moving element bounces, and its shape changes, when its position reaches the box borders.

If the user clicks the button again, calling window.cancelAnimationFrame on the animation object stops the animation.




    

Position of the International Space Station


    
    The module browser.ajax allows sending Ajax calls, ie sending HTTP requests to a URL and handle the reply without having to reload the page. 
    

Here we use a public API that gives the current position of the International Space Station. The callback function complete() is called when the Ajax call has completed ; its argument has an attribute responseText, the response sent by the server. In this case, the API tells us that it's a JSON string. We decode it with the module json of the standard distribution.


    
    
    Brython provides the modules time and datetime of the standard distribution, but it can also interact with the objects defined by Javascript.
    

To use such objects, import the object window from module browser : it is used to get a reference to all the objects defined in the Javascript global namespace. Because the Javascript object Date is a constructor (ie a function that returns new objects with the syntax var date = new Date()) we create the equivalent function in Brython with the function JSConstructor defined in module javascript.

We then use the attributes of the Javascript instance of Date() such as getFullYear with the usual Python syntax.