Client side web programming with Brython

Introduction

In this lecture we will learn how to put in place a program with Brython, a client side web programming tool. Brython is a JavaScript library that interprets Python code, but not only. Its goals are mainly:

Python is more fun to write and is more readable than JavaScript. However the JavaScript specification is still evolving and it is part of a very large growing ecosystem (asm, dart (see also a comparison between Dart and JavaScript), typescript). Note that there exists many projects for Python-to-JavaScript compilers:

A client side web application means that you download an html page containing all the information to compute and to display the result of your problem. There is no server, except a repository for your html file. Your browser interprets the code inside the html file, and solve the problem!

The magic part is that the html file is divided into (virtual) sections of code as follows:

This type of organization is known under the vocabulary of MVC (Model View Controller). It is placed at the methodological level regarding the development of applications and may be useful for developing database applications (MySQL, MariaDB, Postgresql...) or GUI (Graphical User Interface) with JavaFX and Swing (Java tools), or in many other situations. The following frameworks also use an MVC approach: Angular (becoming very popular), Backbone, Ember, Knockout. Some complementary explanations about MVC can be found on this page.

Working with examples

We recommend to download all the examples and to inspect the codes. We put some comments inside the codes in order to discuss the limitations of Brython. The portions of codes with a comment (# is used in Python to introduce a comment) show alternatives that are theoretically possible but, in general, not implemented yet with Brython (for good and maybe for bad reasons too).

The reader of this lecture is now invited to review, in depth, the codes inside the following three examples in order to understand them according to the MVC principles:

  1. The Multiset example. A multiset is a set with multiple occurences, if any, of the same elements. The implementation allows to add an element, to cancel one occurence, to cancel all the occurences... and to represent the multiset as a drawing. The multiset is initialized randomly with five integers. A Python class is introduced in order to group the methods for adding, cancelling...
  2. This example demonstrates how to fill a table and to play with a table;
  3. The Weather Station example demonstrates:
    1. how to post an ajax query to get information about the weather in different cities
    2. how to draw tables, in a dynamic way, acconding to the number of days, per city, for the forecast
    3. how to react the an event i.e. to bind an action to a list of checked buttons
    One problem with this application is that we can't POST a request outside our domain i.e. on the web, because of the sandboxing mechanism for the browser. Your browser and javascript follow the CORS (Cross Origin Resource Sharing) specification to protect against bad behaviors or intrusions. More information about CORS can be found on the web, in particuar the way to set up your server to accept multi-domains requests. See also this excellent post or this one on the Mozilla web site. So, to download, from the web, the information about the weather, we developed a Python 3 script that you have to install on your machine and to lanch before going to the Weather Station example. The code of the Python program is in using the requests interface, for all the cities, and to store locally the results, on your local disk. The main loop is:
      for i,_ in dico.items():
          print('We are creating the file named ',dico[i]+'_fr.xml -- Please wait!')
          data = requests.get('http://worldweather.wmo.int/fr/json/'+dico[i]+'_fr.xml')
          dataa=data.text
          j = json.loads(dataa)
          # Open a file
          fo = open(dico[i]+'_fr.xml', "w")
          foo = str(j)
          foo=foo.replace(": None", ": 'None'")
          foo=foo.replace(": False", ": 'False'")
          foo=foo.replace(": True", ": 'True'")
          # we put the anchor  in order to pre-build
          # an XML object that will be read by an ajax request in the
          # weather-station.html file. This is a Tip!
          fo.write(""+foo+"")
          # Close opend file
          fo.close()
    
    To conclude, we obtain two independant programs, that do not really cooperate (only through files). The Python program generates the data for the HTML code. The communication between the HTML code and the 'outside' of the browser is accomplished with an ajax POST request. The Python program needs to be started daily if you want fresh information about the weather!

Home work / exercices

NodejS

Use a NodeJS server to implement the dialog with your HTML/python application regarding the POST requests over the Internet that is necessary to download information from http://worldweather.wmo.int

Redis

Use a Redis server to implement the dialog with your HTML/python applicationregarding the POST requests over the Internet that is necessary to download information from http://worldweather.wmo.int



Special note: the Brython web site contains also many demos that can be considered to capture the main facilities to implement user interfaces.


Special note: the following post contains interesting information about client side web programming, notably a general discussion of issues, technical solution for implementing data science librairy inside the browser i.e. Bringing the scientific Python stack to the browser according to the viion of the Pyodide project. Pyodide is the Python scientific stack, compiled to WebAssembly. WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is a core technology for Iodide. Iodide is a modern, literate, and interactive programming environment that uses the strengths of the browser to let scientists work flexibly and collaboratively with minimal friction. In the same vein, the Nexedi team uses all of these technologies for the OfficeJS Iodide project, which is an ubiquitous Data Science Notebooks for Business and Education, running in the browser.