1 # Copyright (c) IPython Development Team. 2 # Distributed under the terms of the Modified BSD License. 3 4 """Publishing native (typically pickled) objects. 5 """ 6 7 import warnings 8 9 from traitlets import Any, CBytes, Dict, Instance 10 from traitlets.config import Configurable 11 12 from ipykernel.jsonutil import json_clean 13 14 try: 15 # available since ipyparallel 5.0.0 16 from ipyparallel.serialize import serialize_object 17 except ImportError: 18 # Deprecated since ipykernel 4.3.0 19 from ipykernel.serialize import serialize_object 20 21 from jupyter_client.session import Session, extract_header 22 23 warnings.warn( 24 "ipykernel.datapub is deprecated. It has moved to ipyparallel.datapub", 25 DeprecationWarning, 26 stacklevel=2, 27 ) 28 29 30 class ZMQDataPublisher(Configurable): 31 """A zmq data publisher.""" 32 33 topic = topic = CBytes(b"datapub") 34 session = Instance(Session, allow_none=True) 35 pub_socket = Any(allow_none=True) 36 parent_header = Dict({}) 37 38 def set_parent(self, parent): 39 """Set the parent for outbound messages.""" 40 self.parent_header = extract_header(parent) 41 42 def publish_data(self, data): 43 """publish a data_message on the IOPub channel 44 45 Parameters 46 ---------- 47 data : dict 48 The data to be published. Think of it as a namespace. 49 """ 50 session = self.session 51 assert session is not None 52 buffers = serialize_object( 53 data, 54 buffer_threshold=session.buffer_threshold, 55 item_threshold=session.item_threshold, 56 ) 57 content = json_clean(dict(keys=list(data.keys()))) 58 session.send( 59 self.pub_socket, 60 "data_message", 61 content=content, 62 parent=self.parent_header, 63 buffers=buffers, 64 ident=self.topic, 65 ) 66 67 68 def publish_data(data): 69 """publish a data_message on the IOPub channel 70 71 Parameters 72 ---------- 73 data : dict 74 The data to be published. Think of it as a namespace. 75 """ 76 warnings.warn( 77 "ipykernel.datapub is deprecated. It has moved to ipyparallel.datapub", 78 DeprecationWarning, 79 stacklevel=2, 80 ) 81 82 from ipykernel.zmqshell import ZMQInteractiveShell 83 84 ZMQInteractiveShell.instance().data_pub.publish_data(data) 85