I have a python script which resides on a web-server (running node.js) and does some machine learning computation. The data has to be supplied to the python script using javascript running in web-browser. How can this be done? I want to know the complete setup. For now, the server is the localhost only.
-
One way to do it is to have your browser-side JavaScript send over the data to your server through an API. And then have your server-side JavaScript call the Python script and pass in the data as if it were a Bash command by using exec.Dan Mandel– Dan Mandel2017-09-07 14:14:02 +00:00Commented Sep 7, 2017 at 14:14
Add a comment
|
2 Answers
The best way is to use zerorpc, a socket server and client for both Python and Node.js.
Installing on Python:
pip install zerorpc
Installing on Node:
npm install zerorpc
Python server file:
import zerorpc
class HelloRPC(object):
def hello(self, name):
print "message from host: %s" % name
return raw_input("Enter your message: ")
s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()
Node.js client file:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var zerorpc = require("zerorpc");
var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/myaction', function(req, res) {
client.invoke("hello", "RPC", function(error, res, more) {
console.log(res);
res.send(req.body.name);
});
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
While the example code here is relatively simple, it should get you started. The overall logic of this setup is as follows:
- Use express to get data from webpage (stored as
req.body.name) - Take this data and send it via
zerorpcto your Python server, which can process the data and send it back to the Node.jszerorpcclient.