This host call template is a simple implementation of Python based web server (tornado) whitch supports the direct calling of server Python methods from JavaScript on client side.
For data exchange JSON format is used.
The server side converts JSON input into Python dictionary structure, makes direct call of Python method and transforms call results back into JSON output.
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, also in JSON format.
The template is based on tornado web server
The parser is implemented as separate RequestHandler:
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 conversion JSON module output from unicode string to byte string was get from here
The HostCallHandler is built into into tornado web server as /call page
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()
JavaScript 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 JavaScript function can be called as following:
<button onclick="hostcall("setValue", {"value" : 1})">ON</button>
The server template and test HTML page can be found here: hostcall.zip
MD5 checksum: ae8bc39c3b206fab55819fa54720735d
Test web page: localhost:20080