displaypub.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. from __future__ import print_function
  14. import sys
  15. from traitlets.config.configurable import Configurable
  16. from traitlets import List
  17. # This used to be defined here - it is imported for backwards compatibility
  18. from .display import publish_display_data
  19. #-----------------------------------------------------------------------------
  20. # Main payload class
  21. #-----------------------------------------------------------------------------
  22. class DisplayPublisher(Configurable):
  23. """A traited class that publishes display data to frontends.
  24. Instances of this class are created by the main IPython object and should
  25. be accessed there.
  26. """
  27. def _validate_data(self, data, metadata=None):
  28. """Validate the display data.
  29. Parameters
  30. ----------
  31. data : dict
  32. The formata data dictionary.
  33. metadata : dict
  34. Any metadata for the data.
  35. """
  36. if not isinstance(data, dict):
  37. raise TypeError('data must be a dict, got: %r' % data)
  38. if metadata is not None:
  39. if not isinstance(metadata, dict):
  40. raise TypeError('metadata must be a dict, got: %r' % data)
  41. # use * to indicate transient, update are keyword-only
  42. def publish(self, data, metadata=None, source=None, **kwargs):
  43. """Publish data and metadata to all frontends.
  44. See the ``display_data`` message in the messaging documentation for
  45. more details about this message type.
  46. The following MIME types are currently implemented:
  47. * text/plain
  48. * text/html
  49. * text/markdown
  50. * text/latex
  51. * application/json
  52. * application/javascript
  53. * image/png
  54. * image/jpeg
  55. * image/svg+xml
  56. Parameters
  57. ----------
  58. data : dict
  59. A dictionary having keys that are valid MIME types (like
  60. 'text/plain' or 'image/svg+xml') and values that are the data for
  61. that MIME type. The data itself must be a JSON'able data
  62. structure. Minimally all data should have the 'text/plain' data,
  63. which can be displayed by all frontends. If more than the plain
  64. text is given, it is up to the frontend to decide which
  65. representation to use.
  66. metadata : dict
  67. A dictionary for metadata related to the data. This can contain
  68. arbitrary key, value pairs that frontends can use to interpret
  69. the data. Metadata specific to each mime-type can be specified
  70. in the metadata dict with the same mime-type keys as
  71. the data itself.
  72. source : str, deprecated
  73. Unused.
  74. transient: dict, keyword-only
  75. A dictionary for transient data.
  76. Data in this dictionary should not be persisted as part of saving this output.
  77. Examples include 'display_id'.
  78. update: bool, keyword-only, default: False
  79. If True, only update existing outputs with the same display_id,
  80. rather than creating a new output.
  81. """
  82. # These are kwargs only on Python 3, not used there.
  83. # For consistency and avoid code divergence we leave them here to
  84. # simplify potential backport
  85. transient = kwargs.pop('transient', None)
  86. update = kwargs.pop('update', False)
  87. # The default is to simply write the plain text data using sys.stdout.
  88. if 'text/plain' in data:
  89. print(data['text/plain'])
  90. def clear_output(self, wait=False):
  91. """Clear the output of the cell receiving output."""
  92. print('\033[2K\r', end='')
  93. sys.stdout.flush()
  94. print('\033[2K\r', end='')
  95. sys.stderr.flush()
  96. class CapturingDisplayPublisher(DisplayPublisher):
  97. """A DisplayPublisher that stores"""
  98. outputs = List()
  99. def publish(self, data, metadata=None, source=None, **kwargs):
  100. # These are kwargs only on Python 3, not used there.
  101. # For consistency and avoid code divergence we leave them here to
  102. # simplify potential backport
  103. transient = kwargs.pop('transient', None)
  104. update = kwargs.pop('update', False)
  105. self.outputs.append({'data':data, 'metadata':metadata,
  106. 'transient':transient, 'update':update})
  107. def clear_output(self, wait=False):
  108. super(CapturingDisplayPublisher, self).clear_output(wait)
  109. # empty the list, *do not* reassign a new list
  110. self.outputs.clear()