class CommSocket(object): """ A websocket for interactive communication between the plot in the browser and the server. In addition to the methods required by tornado, it is required to have two callback methods: - ``send_json(json_content)`` is called by matplotlib when it needs to send json to the browser. `json_content` is a JSON tree (Python dictionary), and it is the responsibility of this implementation to encode it as a string to send over the socket. - ``send_binary(blob)`` is called to send binary image data to the browser. """ supports_binary = False def __init__(self, manager): self.manager = manager self.uuid = uuid() #display(HTML("<div id='%s'></div>"%self.uuid)) self.comm = Comm('matplotlib', data={'id': self.uuid}) def open(self): # Register the websocket with the FigureManager. self.manager.add_web_socket(self) self.comm.on_msg(self.on_message) def on_close(self): # When the socket is closed, deregister the websocket with # the FigureManager. self.manager.remove_web_socket(self) self.comm.close() def send_json(self, content): self.comm.send({'data': json.dumps(content)}) def send_binary(self, blob): data_uri = "data:image/png;base64,{0}".format(b64encode(blob)) self.comm.send({'data': data_uri}) def on_message(self, message): # The 'supports_binary' message is relevant to the # websocket itself. The other messages get passed along # to matplotlib as-is. # Every message has a "type" and a "figure_id". message = json.loads(message['content']['data']) if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: self.manager.handle_json(message)