current.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. """Deprecated API for working with notebooks
  2. - use nbformat for read/write/validate public API
  3. - use nbformat.vX directly for Python API for composing notebooks
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from __future__ import print_function
  8. import re
  9. import warnings
  10. warnings.warn("""nbformat.current is deprecated.
  11. - use nbformat for read/write/validate public API
  12. - use nbformat.vX directly to composing notebooks of a particular version
  13. """)
  14. from nbformat.v3 import (
  15. NotebookNode,
  16. new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
  17. parse_filename, new_metadata, new_author, new_heading_cell, nbformat,
  18. nbformat_minor, nbformat_schema, to_notebook_json,
  19. )
  20. from nbformat import v3 as _v_latest
  21. from .reader import reads as reader_reads
  22. from . import versions
  23. from .converter import convert
  24. from .validator import validate, ValidationError
  25. from traitlets.log import get_logger
  26. __all__ = ['NotebookNode', 'new_code_cell', 'new_text_cell', 'new_notebook',
  27. 'new_output', 'new_worksheet', 'parse_filename', 'new_metadata', 'new_author',
  28. 'new_heading_cell', 'nbformat', 'nbformat_minor', 'nbformat_schema',
  29. 'to_notebook_json', 'convert', 'validate', 'NBFormatError', 'parse_py',
  30. 'reads_json', 'writes_json', 'reads_py', 'writes_py', 'reads', 'writes', 'read',
  31. 'write']
  32. current_nbformat = nbformat
  33. current_nbformat_minor = nbformat_minor
  34. current_nbformat_module = _v_latest.__name__
  35. class NBFormatError(ValueError):
  36. pass
  37. def _warn_format():
  38. warnings.warn("""Non-JSON file support in nbformat is deprecated.
  39. Use nbconvert to create files of other formats.""")
  40. def parse_py(s, **kwargs):
  41. """Parse a string into a (nbformat, string) tuple."""
  42. nbf = current_nbformat
  43. nbm = current_nbformat_minor
  44. pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>'
  45. m = re.search(pattern,s)
  46. if m is not None:
  47. digits = m.group('nbformat').split('.')
  48. nbf = int(digits[0])
  49. if len(digits) > 1:
  50. nbm = int(digits[1])
  51. return nbf, nbm, s
  52. def reads_json(nbjson, **kwargs):
  53. """DEPRECATED, use reads"""
  54. warnings.warn("reads_json is deprecated, use reads")
  55. return reads(nbjson)
  56. def writes_json(nb, **kwargs):
  57. """DEPRECATED, use writes"""
  58. warnings.warn("writes_json is deprecated, use writes")
  59. return writes(nb, **kwargs)
  60. def reads_py(s, **kwargs):
  61. """DEPRECATED: use nbconvert"""
  62. _warn_format()
  63. nbf, nbm, s = parse_py(s, **kwargs)
  64. if nbf in (2, 3):
  65. nb = versions[nbf].to_notebook_py(s, **kwargs)
  66. else:
  67. raise NBFormatError('Unsupported PY nbformat version: %i' % nbf)
  68. return nb
  69. def writes_py(nb, **kwargs):
  70. """DEPRECATED: use nbconvert"""
  71. _warn_format()
  72. return versions[3].writes_py(nb, **kwargs)
  73. # High level API
  74. def reads(s, format='DEPRECATED', version=current_nbformat, **kwargs):
  75. """Read a notebook from a string and return the NotebookNode object.
  76. This function properly handles notebooks of any version. The notebook
  77. returned will always be in the current version's format.
  78. Parameters
  79. ----------
  80. s : unicode
  81. The raw unicode string to read the notebook from.
  82. Returns
  83. -------
  84. nb : NotebookNode
  85. The notebook that was read.
  86. """
  87. if format not in {'DEPRECATED', 'json'}:
  88. _warn_format()
  89. nb = reader_reads(s, **kwargs)
  90. nb = convert(nb, version)
  91. try:
  92. validate(nb)
  93. except ValidationError as e:
  94. get_logger().error("Notebook JSON is invalid: %s", e)
  95. return nb
  96. def writes(nb, format='DEPRECATED', version=current_nbformat, **kwargs):
  97. """Write a notebook to a string in a given format in the current nbformat version.
  98. This function always writes the notebook in the current nbformat version.
  99. Parameters
  100. ----------
  101. nb : NotebookNode
  102. The notebook to write.
  103. version : int
  104. The nbformat version to write.
  105. Used for downgrading notebooks.
  106. Returns
  107. -------
  108. s : unicode
  109. The notebook string.
  110. """
  111. if format not in {'DEPRECATED', 'json'}:
  112. _warn_format()
  113. nb = convert(nb, version)
  114. try:
  115. validate(nb)
  116. except ValidationError as e:
  117. get_logger().error("Notebook JSON is invalid: %s", e)
  118. return versions[version].writes_json(nb, **kwargs)
  119. def read(fp, format='DEPRECATED', **kwargs):
  120. """Read a notebook from a file and return the NotebookNode object.
  121. This function properly handles notebooks of any version. The notebook
  122. returned will always be in the current version's format.
  123. Parameters
  124. ----------
  125. fp : file
  126. Any file-like object with a read method.
  127. Returns
  128. -------
  129. nb : NotebookNode
  130. The notebook that was read.
  131. """
  132. return reads(fp.read(), **kwargs)
  133. def write(nb, fp, format='DEPRECATED', **kwargs):
  134. """Write a notebook to a file in a given format in the current nbformat version.
  135. This function always writes the notebook in the current nbformat version.
  136. Parameters
  137. ----------
  138. nb : NotebookNode
  139. The notebook to write.
  140. fp : file
  141. Any file-like object with a write method.
  142. """
  143. s = writes(nb, **kwargs)
  144. if isinstance(s, bytes):
  145. s = s.decode('utf8')
  146. return fp.write(s)