It may be basic.
Why now? When I was communicating with WebSocket using tornado
Send callback method name with Javascript → Execute the method specified by tornado and send the callback function name to Javascript → Execute the callback function specified in Javascript
I wanted to call a method from a string.
First, connect to Javascript and WebSocket and send the calling method name and other parameters on the tornado side. The parameters are sent in JSON.
python
var ws = new WebSocket('ws://server/ws');
var p = {};
//callback method name
p['callback'] = 'wake_up';
//Other parameters
p['msg'] = 'Wake Up!!!!';
ws.send(JSON.stringify(p));
ws.onmessage = function(e) {
var data = JSON.parse(e.data);
console.log(data['message']);
};
The tornado side, getattr of on_message is the main part of this title.
app.py
from tornado import ioloop,web,websocket
import json
#callback class
from callback import Callback
class WSHandler(websocket.WebSocketHandler):
#When the message comes
def on_message(self, message):
data = json.loads(message)
#Instantiation of Callback class
cb = Callback(data)
#Method call
result = getattr(cb, data['callback'])()
#Value to return to Javascript
return_value = {}
return_value['message'] = result
#Send message with WebSocket
self.write_message(json.dumps(return_value))
handlers = [
(r'/ws', WSHandler),
]
settings = dict(
debug = False,
)
app = web.Application(handlers, **settings)
app.listen(sys.argv[1])
ioloop.IOLoop.instance().start()
The method to be called.
callback.py
class Callback(data):
def __init__(self, data):
self.data = data
def wake_up(self):
return self.data['msg']
You should now see'Wake Up !!!!'on your browser console.
The usage of getattr is as follows. Details are left to the official documentation.
python
cb = Callback(data)
result = cb.wake_up()
#The above is the same as the code below
result2 = getattr(cb, 'wake_up')()
#By the way, if you do as follows, the return value will not be returned and the object will be assigned.
result3 = getattr(cb, 'wake_up')
Did you do it like result3 above? ?? ?? But when you think about it, it's right. .. ..
2013-03-15 postscript Fixed a subtle mistake. Excuse me.
Recommended Posts