Use Pyodide's WebAssembly module to run Python code on a web page.
To test locally we'll need a web server to serve our test html file and the Pyodide WebAssembly file. We'll spin-up a basic Python web server so you will need to have at least version 2.7 of Python installed.
Naturally, you will also need a browser capable of running WebAssembly. Any post-2017 browser should work.
Grab the latest release tarball from the Pyodide releases page and expand its contents into a pyodide_local
directory.
Create and save a test index.html
page (in the pyodide_local directory) with the following contents:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.languagePluginUrl = 'http://localhost:8000/'; // set the pyodide support files (packages.json, pyodide.asm.data etc) url
</script>
<script src="pyodide.js"></script>
</head>
<body>
Pyodide test page <br>
Open your browser console to see pyodide output
<script type="text/javascript">
languagePluginLoader.then(function () {
console.log(pyodide.runPython('import sys\nsys.version'));
console.log(pyodide.runPython('help("modules")'));
});
</script>
</body>
Unfortunately, because browsers require WebAssembly files to have a mime-type of application/wasm
we're unable to serve our files using Python's built-in SimpleHTTPServer
module.
So, let's wrap Python's Simple HTTP Server and provide the appropiate mime-type for WebAssembly files into a pyodide_server.py
file (in the pyodide_local directory):
import BaseHTTPServer, SimpleHTTPServer
SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm'
httpd = BaseHTTPServer.HTTPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
Let's test it out. In your favourite shell, let's start our WebAssembly aware web server:
python pyodide_server.py
Point your WebAssembly aware browser to http://localhost:8000/index.html and open your browser console to see the output from Python!
Using WebAssembly, Pyodide brings real Python code execution to your client-side browser. It showcases the potential of WebAssembly and how it can be used to expand the capabilities of front-end development.
What do you think?
Do you have any examples of other cool uses of WebAssembly?
Get in touch via twitter.
Read more articles and tutorials about WebAssembly.