Direct python methods calls from javascript

This hostcall template is a simple implementation of python based wabserver (tornado) with supports the direct colling of server python methods from javascript on client side.

The host call mechanism is implemented using GET method with two parameters:
First parameter method defines python function on host site. Second parameter arguments contains list of arguments and its values in json format.
The result of operation is a response - text content, alsow in json format.

HTTP request

This example converts json input into python dictionary structure, makes direct call of python method (if it exists) and transforms call results back into json output.

Server side implementation

The template is a implementated based on tornado wabserver
As following class:

class HostCallHandler(tornado.web.RequestHandler):
	"""
	Get method implementation
	"""
	def get(self):
		method = self.get_argument("method", default = None)
		arguments = self.get_argument("arguments", default = None)
		if method != None:
			if arguments != None:
				args = byteify(json_decode(arguments))
			else:
				args = {}
			try:
				print "calling:", method, "with", args
				if hasattr(self, method):
					result = getattr(self, method)(**args)
					resp = json_encode(result)
				else:
					resp = {"result" : -1, "error" : "method not exists"}
			except:
				resp = {"result" : -1, "error" : "execution exception"}
		else:
			resp = {"result" : -1, "error" : "method not defined"}
		print "result", resp
		self.finish(resp)

	"""
	User functions
	"""
	def ...

The byteify function for convertion json module output from unicode string to byte string was get from here

Integration the HostCallHandler into tornado web server:

if __name__ == "__main__":
	application = tornado.web.Application([
		...,
		(r"/call", HostCallHandler),
	])
	# Create server object
	http_server = tornado.httpserver.HTTPServer(application)
	#Starting server LOOP
	tornado.ioloop.IOLoop.instance().start()

Client side implementation

Java script on client side:

<script type="text/javascript">
	function hostcall(method, params) {
		var result;
		var xhttp = new XMLHttpRequest();
		xhttp.open("GET", "/call?method=" + method + ";arguments="+ JSON.stringify(params), false);
		xhttp.send();
		if(xhttp.status == 200) {
			result = JSON.parse(xhttp.responseText);
		}
		else {
			result = { "result" : -1, "error" : "cannot perform request, status: " + xhttp.status };
		}
		return result;
	}
<script>

The java function can be called as following:

<button onclick="hostcall("setValue", {"value" : 1})">ON</button>

Template

The server template and test HTML page can be found here: hostcall.zip
MDM5 checksum: 345345345345345

This implementation extends the HostCallHandler with additional setValue and getValue functions, which are dircect callable from web client.