Python in a Node app? Let’s play with Zerorpc!

Ahmed Sayeed Wasif
3 min readSep 8, 2020

When coding a javascript function with a lot of matrix and string manipulations, ever wished if you could just ‘import’ python to use its libraries? I’ve been there too. Especially when I was writing a desktop application and I couldn’t use my favorite language python. It got me wondering, would it be possible to do the interface designing with html/css/js and write the business logic in python? How will you hook up the python routines in js? In this article, I tried to find an answer using Zerorpc.

The full code for this project is open-sourced and maintained in https://github.com/aswasif007/pyjs

Let’s give a brief intro to Zerorpc first. Its an RPC (Remote Procedure Call) library that enables you to call a function not necessarily from even the same computer. It creates a bridge between the caller and the callee using TCP protocol. You can call a function that is physically in another part of the world if the host computer has a public IP address. (Eh 😧? Why not do that instead of REST API? Let’s have that discussion on another day 😀)

For this experiment, there is no need to go international ✈️. Our objective here is simple: we have a function called hello_world in a python file, which we want to import and use in a node script. Simply put, this is how our py and js files should look like:

So, how do we do this? First of all, we need to create a server in python to receive calls and transmit return-values. We also need to tell the server which functions to allow js to call. In our case, it is only the hello_world function.

Now, we need to create a client in node to transmit the calls and receive return-values. This will give us the interface we need to create the bridge between the two worlds.

Finally, we are ready to create the bridge and make the call!

How do you feel about this so far? I know right, exhausting 😫! Too much work. We need it to be simpler. Like, you write the function in python and boom, it is ready to be used in node. No hunky punky!

You’ve probably already noticed, the client written in javascript is pretty static. So, how about we get the server to generate the client? And the bridges too? 😁

The trick is to stringify the client code and writing it from server.py.

We can also keep the exported functions to an array in main.py file and auto-generate the bridges.

We are almost done! The last thing to do is to add exported array in main.py file and append our exportable functions to it.

Aaaand we are finished! Add any function to the exported array and you will be able to import it in your node script 👌.

The code fragments provided in this article are scattered. I have compiled them in a repository as well as refactored and romanticized them a bit, here. I also included setup-guide and how-to-use instructions. Be sure to check it out! 😃

--

--

Ahmed Sayeed Wasif
Ahmed Sayeed Wasif

No responses yet