displaypub.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """An interface for publishing rich data to frontends.
  2. There are two components of the display system:
  3. * Display formatters, which take a Python object and compute the
  4. representation of the object in various formats (text, HTML, SVG, etc.).
  5. * The display publisher that is used to send the representation data to the
  6. various frontends.
  7. This module defines the logic display publishing. The display publisher uses
  8. the ``display_data`` message type that is defined in the IPython messaging
  9. spec.
  10. """
  11. # Copyright (c) IPython Development Team.
  12. # Distributed under the terms of the Modified BSD License.
  13. import sys
  14. from traitlets.config.configurable import Configurable
  15. from traitlets import List
  16. # This used to be defined here - it is imported for backwards compatibility
  17. from .display_functions import publish_display_data
  18. #-----------------------------------------------------------------------------
  19. # Main payload class
  20. #-----------------------------------------------------------------------------
  21. class DisplayPublisher(Configurable):
  22. """A traited class that publishes display data to frontends.
  23. Instances of this class are created by the main IPython object and should
  24. be accessed there.
  25. """
  26. def __init__(self, shell=None, *args, **kwargs):
  27. self.shell = shell
  28. super().__init__(*args, **kwargs)
  29. def _validate_data(self, data, metadata=None):
  30. """Validate the display data.
  31. Parameters
  32. ----------
  33. data : dict
  34. The formata data dictionary.
  35. metadata : dict
  36. Any metadata for the data.
  37. """
  38. if not isinstance(data, dict):
  39. raise TypeError('data must be a dict, got: %r' % data)
  40. if metadata is not None:
  41. if not isinstance(metadata, dict):
  42. raise TypeError('metadata must be a dict, got: %r' % data)
  43. # use * to indicate transient, update are keyword-only
  44. def publish(self, data, metadata=None, source=None, *, transient=None, update=False, **kwargs) -> None:
  45. """Publish data and metadata to all frontends.
  46. See the ``display_data`` message in the messaging documentation for
  47. more details about this message type.
  48. The following MIME types are currently implemented:
  49. * text/plain
  50. * text/html
  51. * text/markdown
  52. * text/latex
  53. * application/json
  54. * application/javascript
  55. * image/png
  56. * image/jpeg
  57. * image/svg+xml
  58. Parameters
  59. ----------
  60. data : dict
  61. A dictionary having keys that are valid MIME types (like
  62. 'text/plain' or 'image/svg+xml') and values that are the data for
  63. that MIME type. The data itself must be a JSON'able data
  64. structure. Minimally all data should have the 'text/plain' data,
  65. which can be displayed by all frontends. If more than the plain
  66. text is given, it is up to the frontend to decide which
  67. representation to use.
  68. metadata : dict
  69. A dictionary for metadata related to the data. This can contain
  70. arbitrary key, value pairs that frontends can use to interpret
  71. the data. Metadata specific to each mime-type can be specified
  72. in the metadata dict with the same mime-type keys as
  73. the data itself.
  74. source : str, deprecated
  75. Unused.
  76. transient : dict, keyword-only
  77. A dictionary for transient data.
  78. Data in this dictionary should not be persisted as part of saving this output.
  79. Examples include 'display_id'.
  80. update : bool, keyword-only, default: False
  81. If True, only update existing outputs with the same display_id,
  82. rather than creating a new output.
  83. """
  84. handlers = {}
  85. if self.shell is not None:
  86. handlers = getattr(self.shell, 'mime_renderers', {})
  87. for mime, handler in handlers.items():
  88. if mime in data:
  89. handler(data[mime], metadata.get(mime, None))
  90. return
  91. if 'text/plain' in data:
  92. print(data['text/plain'])
  93. def clear_output(self, wait=False):
  94. """Clear the output of the cell receiving output."""
  95. print('\033[2K\r', end='')
  96. sys.stdout.flush()
  97. print('\033[2K\r', end='')
  98. sys.stderr.flush()
  99. class CapturingDisplayPublisher(DisplayPublisher):
  100. """A DisplayPublisher that stores"""
  101. outputs = List()
  102. def publish(self, data, metadata=None, source=None, *, transient=None, update=False):
  103. self.outputs.append({'data':data, 'metadata':metadata,
  104. 'transient':transient, 'update':update})
  105. def clear_output(self, wait=False):
  106. super(CapturingDisplayPublisher, self).clear_output(wait)
  107. # empty the list, *do not* reassign a new list
  108. self.outputs.clear()