Run python script server-side from P5.js sketch

I’m a bit of a noob when it comes to P5.js and web stuff so apologies in advance for the possibly dumb question:

I have p5.js sketch that I have online a hosted linux server. I want this p5.js app to call a python script that will run on the server. Just wondering how I go about this?

The python script is not a processing.py script, it’s another script to do some machine vision.

Hi @bananana,

First you need to understand that even if your p5js sketch is hosted on a server it is executed on client side, which of course have no access to your server.
To do things you probably imagine you need a way to call s.th. on your server, which usually is done by ie. RestAPI calls to a service (running on your server), which executes code on the server and is called from your p5js sketch and returns the result to your P5 sketch.

Here are some starting points …

Hope that helps!

Cheers
— mnse

2 Likes

First of all, not a dumb question at all! The problem is that there are millions of ways to achieve this, and you need to find the right framework that suits your use case and skillset.

First you need to set up the web server so that you can listen to the call from p5.js front end if you are planning to expose the page on a global domain. You mentioned a linux server, so I assume you have a sudo access (and you are familar with setting up the server). Are you using Apache/httpd or nginx? You would need to set up reverse proxy on httpd or nginx so that the request to your domain will be proxied to the port of your back end application. Note that starting from global domain may be a bit painful because you may need to set up https. I suggest trying localhost first or you can always use ssh port forwarding for testing.

For the back end application, there are various options such as nodejs and go. If you are comfortable writing python, you may want to try django or Flask mentioned above. You can either host your p5.js page separately or as a static site within those frameworks (perhaps the latter is better as you don’t face the cross origin problem).

Then you have to establish a connection between your p5.js app (front end) and your server. In “creative coding”, you might see a lot of examples using websockets because the idea is similar to OSC communication. Most of the back end framework have websocket packages. But this is not the only option, and I found that often making a REST API is simpler, like mentioned above. Basically you make an endpoint on your server (for example, https://example.com/api/runpython), and p5.js app makes a GET or POST request to “trigger” an event on the server either httpDo mentioned above or standard fetch (it seems httpDo is a thin wrapper of the fetch API).

Feel free to post the progress when you are stuck - I hope you find your way!

2 Likes

thanks for the fast replies mnse and micaut. I managed to work it out by following the geekforgeeks pages you suggested :+1:

1 Like