Brython: Python in Your Browser – Real Python
Brython: Python in Your Browser by Andre Burgaud Updated Feb 24, 2021 Reading time estimate 1h 15m intermediate front-end web-dev Table of Contents Remove ads If you’re a web developer who prefers writing Python over JavaScript, then Brython , a Python implementation that runs in the browser, may be an appealing option. JavaScript is the de facto language of front-end web development . Sophisticated JavaScript engines are an inherent part of all modern Internet browsers and naturally drive developers to code front-end web applications in JavaScript.
Brython offers the best of both worlds by making Python a first-class citizen language in the browser and by having access to all the existing JavaScript libraries and APIs available in the browser. In this tutorial, you’ll learn how to: Install Brython in your local environment Use Python in a browser Write Python code that interacts with JavaScript Deploy Python with your web application Create browser extensions with Python Compare Brython with other Python implementations for web applications As an intermediate Python developer familiar with web development , you’ll get the most out of this tutorial if you also have some knowledge of HTML and JavaScript.
For a JavaScript refresher, check out Python vs JavaScript for Pythonistas . You can download the source material for the examples in this tutorial by clicking the link below: Get the Source Code: Click here to get the source code you’ll use to learn about using Brython to run Python in the browser in this tutorial. Running Python in the Browser: The Benefits Although JavaScript is the ubiquitous language of front-end web development, the following points may apply to you: You may not like writing code in JavaScript.
You may want to leverage your Python skills. You may not want to spend the time to learn JavaScript to explore browser technologies. You may not like being forced to learn and use JavaScript to implement a web application. Whatever the reason, many developers would prefer a Python-based alternative to JavaScript for leveraging the power of the browser. There are several benefits of running Python in the browser. It allows you to: Execute the same Python code in the server and the browser Work with various browser APIs using Python Manipulate the Document Object Model (DOM) with Python Use Python to interact with existing JavaScript libraries like Vue.js and jQuery Teach the Python language to Python students with the Brython editor Keep the sense of fun while programming in Python One side effect of using Python in the browser is a loss of performance compared to the same code in JavaScript.
However, this drawback doesn’t outweigh any of the benefits outlined above. Remove ads Implementing Isomorphic Web Development Isomorphic JavaScript , or Universal JavaScript , emphasizes that JavaScript applications should run on both the client and the server. This is assuming that the back end is JavaScript based, namely a Node server. Python developers using Flask or Django can also apply the principles of isomorphism to Python, provided that they can run Python in the browser.
Brython allows you to build the front end in Python and share modules between the client and the server. For example, you can share validation functions, like the following code that normalizes and validates US phone numbers: Language: Python 1 import re 2 3 def normalize_us_phone ( phone : str ) -> str : 4 """Extract numbers and digits from a given phone number""" 5 return re . sub ( r "[^\da-zA-z]" , "" , phone ) 6 7 def is_valid_us_phone ( phone : str ) -> bool : 8 """Validate 10-digit phone number""" 9 normalized_number = normalize_us_phone ( phone ) 10 return re . match ( r "^\d {10} $" , normalized_number ) is not None normalize_us_phone() eliminates any nonalphanumeric characters, whereas is_valid_us_phone() returns True if the input string contains exactly ten digits and no alphabetic characters.
The same code can be shared between processes running on a Python server and a client built with Brython. Accessing Web APIs Internet browsers expose standardized web APIs to JavaScript. These standards are part of the HTML Living Standard . Some web API examples include: Web Storage Web Crypto Web Workers History URL Brython allows you to both use the web APIs and interact with JavaScript. You’ll work with some of the web APIs in a later section .
Prototyping and JavaScript Libraries Python is often used to prototype snippets of code, language constructs, or bigger ideas. With Brython, this common coding practice becomes available in your browser. For example, you can use the Brython console or the interactive editor to experiment with a snippet of code. Open the online editor and type the following code: Language: Python 1 from browser import ajax 2 3 def on_complete ( req ): 4 print ( req . text ) 5 6 language = "fr" 7 8 ajax . get ( f "https://fourtonfish.com/hellosalut/?lang= { language } " , 9 blocking = True , 10 oncomplete = on_complete ) Here’s how this code works: Line 1 imports the ajax module.
Line 3 defines on_complete() , the callback function that’s invoked after getting the response from ajax.get() . Line 6 calls ajax.get() to retrieve the translation of “hello” in French using the HelloSalut API . Note that blocking can be True or False when you execute this code in the Brython editor. It needs to be True if you execute the same code in the Brython console. Click Run above the output pane to see the following result: Language: JSON { "code" : "fr" , "hello" : "Salut" } <comple te d i n 5.00 ms> Try modifying the language from fr to es and observe the result.
The language codes supported by this API are listed in the HelloSalut documentation . Note : HelloSalut is one of the public APIs available on the Internet and listed in the Public APIs GitHub project . You can modify the code snippet in the online editor to consume a different public API. For example, try to fetch a random public API from the Public APIs project : Language: Python 1 from browser import ajax 2 3 def on_complete ( req ): 4 print ( req . text ) 5 6 ajax . get ( "https://api.publicapis.org/random" , 7 blocking = True , 8 oncomplete = on_complete ) Copy the code above into the online Brython editor and click Run to display the result.
Here’s an example in JSON format: Language: JSON { "count" : 1 , "entries" : [ { "API" : "Open Government, USA" , "Description" : "United States Government Open Data" , "Auth" : "" , "HTTPS" : true , "Cors" : "unknown" , "Link" : "https://www.data.gov/" , "Category" : "Government" } ] } Because the endpoint fetches a random project, you’ll probably get a different result. For more information about the JSON format, check out Working With JSON Data in Python .
You can use prototyping to try out regular Python code as you would in the Python interpreter . Because you’re in the context of a browser, Brython also provides ways to: Learn how to use the web APIs Interact with the Document Object Model (DOM) Use existing JavaScript libraries like jQuery , D3 , and Bokeh as well as JavaScript UI frameworks like Vue.js As a shortcut, you can take advantage of most of the features described above by opening the console or editor available on the Brython website.
This doesn’t require you to install or run anything on your local computer. Instead, it gives you an online playground to interact with both Python and web technologies. Remove ads Teaching Python to Students Brython is both a Python compiler and an interpreter written in JavaScript. As a result, you can compile and run Python code in the browser. A good example of this feature is demonstrated by the online editor available on the Brython website.
With the online editor, Python is running in the browser. There’s no need to install Python on a machine, and there’s no need to send code to the server to be executed. The feedback is immediate for the user, and this approach doesn�
The rest of this page is on the live site.