[IPython-dev] custom mime types in the notebook
Andrew Payne
andy at payne.org
Fri Jul 11 07:34:30 EDT 2014
On Thu, Jul 10, 2014 at 8:15 AM, Cyrille Rossant <cyrille.rossant at gmail.com>
wrote:
>
> Let's say I have a Javascript application that can read files in a
> custom JSON format. I want to create an IPython extension where:
>
> * some Python functions may return objects in this format
> * the notebook understands this format and uses my JS app to display them
> * cell outputs in that format are saved in the JSON notebook, along
> with other representations (text, image)
if I understand what you're trying to do, you should be able to get *part*
of this by having your Python code return Javascript fragments for
rendering in the notebook cell.
Your fragments would be your (a) JSON data combined with (b) whatever JS
invocation you need to display it or interact with it in the cell.
For example:
from IPython.display import Javascript
Javascript("
var data = {*your JSON data here*};
*invoke_your_function*(data);
")
You can also have your objects implement _repr_javascript_() which would
generate the above fragment.
In addition, you will want to make sure your Javascript library is loaded.
There are subtleties here, including lots of possible race conditions
where your cell is executed before your libraries are fully loaded. To
avoid this case, preface your fragments with the right calls to
'require.js', see: http://requirejs.org/
For detailed examples of most of this, see my notebook:
http://nbviewer.ipython.org/github/payne92/notebooks/blob/master/00%20Javascript%20In%20Notebooks.ipynb
> What's the best way to do it? Should I create a custom mime type
> "application/myapp", and extend the notebook to use the JS app for
> that mime type (if that's even possible)?
I think this opens up a can of worms (certainly relative to the approach
above). Going this route, you start to introduce dependencies on how the
notebook is served, and you make the notebook itself less portable.
I hope this is helpful. (and if you have any feedback on my example
notebook, please let me know).
-andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20140711/ef0eb221/attachment.html>
More information about the IPython-dev
mailing list