← Back to list

Integrating Metamask with PyScript: Unlocking New Possibilities for Python in Front-End Development

One day, while scrolling through LinkedIn, a post about PyScript caught my attention. It highlighted a talk on PyScript at PyCon Hong Kong…

EvanW · 2023-11-01 20:03 · 11 claps · 3.7 min read
#python #web3 #front-end-development #pyscript #metamask
Open on Medium ↗
Wiki topics: CRY · Crypto & Web3

Integrating Metamask with PyScript: Unlocking New Possibilities for Python in Front-End Development

One day, while scrolling through LinkedIn, a post about PyScript caught my attention. It highlighted a talk on PyScript at PyCon Hong Kong 2023. I was pleasantly surprised to learn that Python could now be used for front-end development. It sparked an idea in my mind — what if PyScript could be integrated with Metamask to perform wallet actions seamlessly? Motivated by this vision, I embarked on exploring this protocol to unlock new possibilities for Python developers.

Although I had been using Python for years, PyScript was new to me. Despite not following the best practices, I was thrilled to discover that PyScript worked!

Quick intro about PyScript

Let’s quote a paragraph form PyScript official website as starting.

*PyScript is a platform for Python in the browser.*

PyScript brings together two of the most vibrant technical ecosystems on the planet. If the web and Python had a baby, you’d get PyScript.

PyScript works because modern browsers support WebAssembly (abbreviated to WASM) — an instruction set for a virtual machine with an open specification and near native performance. PyScript takes versions of the Python interpreter compiled to WASM, and makes them easy to use inside the browser.

PyScript, as described on its official website, we can inject our Python code into HTML <script> tags like javascript. PyScript enables interaction with the DOM and even integrates with the Metamask chrome extension.

Composition of basic PyScript

The simplest Pyscript application is composed of three files:

  1. index.html: This file contains all the HTML code and serves as the static website to be rendered in the browser.
  2. main.py: Here, we write our Python code that interacts with Metamask and performs wallet actions.
  3. pyscript.json / pyscript.toml: These files store Python environment configuration details, such as the required packages to be installed.

About my protocol

Demo

Demo

The screenshot above showcases the layout of my protocol, which offers several key features:

  1. Login with Metamask: Users can securely log in using their Metamask wallet.
  2. Sign Message with Metamask: The protocol enables users to sign messages using their Metamask wallet.
  3. Get ETH Balance from Metamask RPC (window.ethereum.request()): With this functionality, users can effortlessly retrieve their ETH balance directly from the Metamask RPC.
  4. Get ETH Balance from Etherscan API: In addition to the Metamask RPC, the protocol also integrates with the Etherscan API. This allows users to fetch their ETH balance from the Etherscan blockchain explorer via API calls.

Implementation and Code Explanation:

  1. Configure which python script to be used
<script type="py" src="./main.py" config="./pyscript.json"></script>

Inserting this line into <body> tag of the html page.

  1. Buttons on click events:
<button id="connect_wallet" 
        className="Login-button Login-mm" 
        py-click="connect_wallet_on_click">
Login with MetaMask
</button>

To enable the on-click event in PyScrip, we use the tag of py-click in stead of onclick

  1. Interact with your browser
from pyscript import document, window

async def connect_wallet_on_click(event):
    is_metamask: bool = window.ethereum.isMetaMask
    is_connected: bool = window.ethereum.isConnected()
    # connect metamask if not connected
    if not window.ethereum.selectedAddress:
        window.ethereum.enable()
    user_account = window.ethereum.selectedAddress
    wallet_element = document.getElementById("public_address")
    wallet_element.innerText = f"My public address is: {user_account}"

The same as Javascript. We can use document and window object to interact with the DOM or the Metamask plugin or pop an alert..

  1. Sending HTTP requests
async def get_wallet_balance_api(addr: str):
    # read api key from element with id "api-key"
    etherscan_api_key = document.getElementById("api-key").value
    if not etherscan_api_key:
        window.alert("Please enter your etherscan API key")
        return
    url = f"https://api.etherscan.io/api?module=account&action=balance&address={addr}&tag=latest&apikey={etherscan_api_key}"
    res = await pyfetch(url)
    data = await res.json()
    wallet_balance = data.get("result")
    return wallet_balance

Sadly, requests module is not supported in PyScript. We need to use pyfetch for HTTP request.

  1. Sending request to Metamask RPC
async def get_wallet_balance_js(addr: str):
    wallet_balance = await run_js("window.ethereum.request({method: 'eth_getBalance',params: ['" + addr + "', 'latest']})")
    return wallet_balance[2:]

Initially, my attempt to execute window.ethereum.request() directly resulted in a PyodideFuture without a set result. It led me to believe that PyScript might not currently have the capability to handle promises from JavaScript. In order to overcome this limitation, I devised a workaround by managing the promise in JavaScript.

  1. Full code!

For a detailed code example, you can refer to my GitHub repository: GitHub — evanwhl508/web3-pyscript.

Challenges and Limitations:

During the integration process, I encountered a few challenges and limitations:

  • Some common libraries, like requests, cannot be used because they cannot be implemented in a WebAssembly browser.
  • PyScript does not support non-pure Python libraries. Consequently, I couldn’t use web3.py, which relies on C language bindings.
  • PyScript cannot directly handle promises from JavaScript code. To overcome this, I utilized the run_js function to execute JavaScript functions when required.

Conclusion

While PyScript is still in its early stages, it has already shown great promise. Although it may not replace common JavaScript frameworks at the moment, I am optimistic about its potential. PyScript meets my initial expectations and offers a unique way to leverage Python in the web development domain. I look forward to witnessing its growth and development, as it continues to evolve and offer even more capabilities.

By integrating PyScript with Metamask, we open doors to a new era of front-end development possibilities for Python developers. Let us embrace this synergy and explore the exciting opportunities that lie ahead.


메타데이터
post_id
5db9dc751ddc
slug
integrating-metamask-with-pyscript-5db9dc751ddc
url
https://medium.com/@evvvv/integrating-metamask-with-pyscript-5db9dc751ddc
canonical_url
https://medium.com/@evvvv/integrating-metamask-with-pyscript-5db9dc751ddc
author_url
https://medium.com/@evvvv
status
ok
fetched_at
2026-06-10 08:17:25