logo

Run Python Code in Your Browser with Brython

O

Ohidur Rahman Bappy

MAR 22, 2025

Introduction

Brython is a powerful tool that allows developers to run Python directly in the browser, leveraging the existing web architecture without the need for server-side computation.

Setting Up Brython

Here's a simple example demonstrating how to use Brython to execute Python code within a web page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython.js" integrity="sha256-rA89wPrTJJQFWJaZveKW8jpdmC3t5F9rRkPyBjz8G04=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython_stdlib.js" integrity="sha256-Gnrw9tIjrsXcZSCh/wos5Jrpn0bNVNFJuNJI9d71TDs=" crossorigin="anonymous"></script>

    <style>
        /* Add necessary styles here */
    </style>
    <title>Brython Demo</title>
</head>
<body onload="brython()">

    <h1>Brython Crash Course</h1>

    <!-- Add your HTML content here -->

    <!-- Alert & DOM insert -->
    <script type="text/python" id="script0">
        from browser import document, console, alert

        def show(e):
            console.log(e)
            alert('Hello World')
            document['hello'] <= 'Hello World'

        document['alert-btn'].bind('click', show)
    </script>

    <!-- More scripts -->
</body>
</html>

Features Implemented in the Example

  • Alert & DOM Insert: Create an alert and insert text into the document.
  • Text Binding: Capture text input and display it instantly.
  • Template and Variable: Utilize templates to render dynamic data.
  • AJAX Calls: Fetch data from an API and display it.
  • File Read: Read and display text files.
  • Style Manipulation: Rotate elements using style transforms.
  • Local Storage: Store data in the browser's local storage.

Conclusion

Brython simplifies the process of integrating Python into your web applications. By utilizing its capabilities, developers can take advantage of Python's simplicity and community while building interactive web applications.

Explore Brython's documentation further for more advanced use cases and get started on your Python-based web projects today!