Create a SimpleHTTPServer to use the python code as API

1.3k Views Asked by At

Is there a way to make my python script served by a Simple HTTP server and call the script functions from the outside (in an other program) in a API philosophy?

EDIT

Ok, thanks to @upman's answer, I know that I can use SimpleXMLRPCServer for that, the question still: how to listen to the XML-RPC Server in an other program written with an other language than python (Node.js for example )

1

There are 1 best solutions below

2
upman On BEST ANSWER

What you're asking for is called Remote Procedure Calls (RPCs)

You can Look into the SimpleXMLRPCServer module in Python

Server code

from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2','/')

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name
def adder_function(x,y):
    return x + y
server.register_function(adder_function, 'add')

# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
    def div(self, x, y):
        return x // y

server.register_instance(MyFuncs())

# Run the server's main loop
server.serve_forever()

Python Client

import xmlrpclib

s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.pow(2,3)  # Returns 2**3 = 8
print s.add(2,3)  # Returns 5
print s.div(5,2)  # Returns 5//2 = 2

# Print list of available methods
print s.system.listMethods()

Source: https://docs.python.org/2/library/simplexmlrpcserver.html

EDIT

XMLRPC is a standard protocol, so there are implementations for it in most of the popular languages. There's a package for node as well. You can install with npm like so

npm install xmlrpc

You can make calls to the above python server with it

Javascript Client

var xmlrpc = require('xmlrpc')
var client = xmlrpc.createClient({ host: 'localhost', port: 8000, path: '/'})

// Sends a method call to the XML-RPC server
client.methodCall('pow', [2,2], function (error, value) {
  // Results of the method response
  console.log('Method response for \'anAction\': ' + value)
})

There's a jQuery implementation xmlrpc as well. So you can make RPCs from the browser.