@ -17,11 +17,10 @@
"cell_type": "code",
"collapsed": false,
"input": [
"from __future__ import print_function # py 2.7 compat\n",
"\n",
"import base64\n",
"from IPython.html import widgets # Widget definitions\n",
"from IPython.display import display # Used to display widgets in the notebook"
"from __future__ import print_function # py 2.7 compat.\n",
"from IPython.html import widgets # Widget definitions.\n",
"from IPython.utils.traitlets import Unicode # Traitlet needed to add synced attributes to the widget."
],
"language": "python",
"metadata": {},
@ -29,31 +28,44 @@
"prompt_number": 1
},
{
"cell_type": "heading",
"level": 1,
"cell_type": "markdown",
"metadata": {},
"source": [
"Custom Widget "
"This is a custom widget that allows the user to upload file data to the notebook server. The file data is sent via a statefull `value` attribute of the widget. The widget has an upload failed event that fires in the front-end and is echoed to the back-end using a custom msg. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Import the base Widget class and the traitlets Unicode class.\n",
"from IPython.html.widgets import Widget\n",
"from IPython.utils.traitlets import Unicode, Int\n",
"\n",
"# Define our FileWidget and its target model and default view.\n",
"class FileWidget(Widget):\n",
" target_name = Unicode('FileWidgetModel')\n",
" default_view_name = Unicode('FilePickerView')\n",
"class FileWidget(widgets.DOMWidget):\n",
" _view_name = Unicode('FilePickerView', sync=True)\n",
" value = Unicode(sync=True)\n",
" filename = Unicode(sync=True)\n",
" \n",
" # Define the custom state properties to sync with the front-end\n",
" _keys = ['value', 'filename']\n",
" value = Unicode('')\n",
" filename = Unicode('')\n",
" on_failed = Int(0)"
" def __init__(self, **kwargs):\n",
" \"\"\"Constructor\"\"\"\n",
" widgets.DOMWidget.__init__(self, **kwargs) # Call the base.\n",
" \n",
" # Allow the user to register error callbacks with the following signatures:\n",
" # callback()\n",
" # callback(sender)\n",
" self.errors = widgets.CallbackDispatcher(accepted_nargs=[0, 1])\n",
" \n",
" # Listen for custom msgs\n",
" self.on_msg(self._handle_custom_msg)\n",
"\n",
" def _handle_custom_msg(self, content):\n",
" \"\"\"Handle a msg from the front-end.\n",
"\n",
" Parameters\n",
" ----------\n",
" content: dict\n",
" Content of the msg.\"\"\"\n",
" if 'event' in content and content['event'] == 'error':\n",
" self.errors()\n",
" self.errors(self)\n",
" "
],
"language": "python",
"metadata": {},
@ -66,46 +78,50 @@
"input": [
"%%javascript\n",
"\n",
"require([\"notebook/js/widget\"], function(){\n",
" \n",
" // Define the FileModel and register it with the widget manager.\n",
" var FileModel = IPython.WidgetModel.extend({});\n",
" IPython.widget_manager.register_widget_model('FileWidgetModel', FileModel);\n",
" \n",
" // Define the FilePickerView\n",
"require([\"notebook/js/widgets/widget\"], function(WidgetManager){\n",
"\n",
" var FilePickerView = IPython.WidgetView.extend({\n",
" \n",
" render: function(){\n",
" var that = this;\n",
" this.$el = $('<input />')\n",
" .attr('type', 'file')\n",
" .change(function(evt){ that.handleFileChange(evt) });\n",
" // Render the view.\n",
" this.setElement($('<input />')\n",
" .attr('type', 'file'));\n",
" },\n",
" \n",
" // Handles: User input\n",
" handleFileChange: function(evt) { \n",
" events: {\n",
" // List of events and their handlers.\n",
" 'change': 'handle_file_change',\n",
" },\n",
" \n",
" handle_file_change: function(evt) { \n",
" // Handle when the user has changed the file.\n",
" \n",
" //Retrieve the first (and only!) File from the FileList object\n",
" var that = this;\n",
" var f = evt.target.files[0];\n",
" if (f) {\n",
" var r = new FileReader();\n",
" r.onload = function(e) {\n",
" // Retrieve the first (and only!) File from the FileList object\n",
" var file = evt.target.files[0];\n",
" if (file) {\n",
"\n",
" // Read the file's textual content and set value to those contents.\n",
" var that = this;\n",
" var file_reader = new FileReader();\n",
" file_reader.onload = function(e) {\n",
" that.model.set('value', e.target.result);\n",
" that.model.update_other_views(that);\n",
" that.touch( );\n",
" }\n",
" r.readAsText(f);\n",
" file_reade r.readAsText(file );\n",
" } else {\n",
" this.model.set('on_failed', this.model.get('on_failed') + 1);\n",
" this.model.update_other_views(this);\n",
"\n",
" // The file couldn't be opened. Send an error msg to the\n",
" // back-end.\n",
" this.send({ 'event': 'error' });\n",
" }\n",
" this.model.set('filename', f.name);\n",
" this.model.update_other_views(this);\n",
"\n",
" // Set the filename of the file.\n",
" this.model.set('filename', file.name);\n",
" this.touch();\n",
" },\n",
" });\n",
" \n",
" // Register the DatePickerView with the widget manager.\n",
" IPython.widget_m anager.register_widget_view('FilePickerView', FilePickerView);\n",
" WidgetM anager.register_widget_view('FilePickerView', FilePickerView);\n",
"});"
],
"language": "python",
@ -114,63 +130,66 @@
{
"javascript": [
"\n",
"require([\"notebook/js/widget\"], function(){\n",
" \n",
" // Define the FileModel and register it with the widget manager.\n",
" var FileModel = IPython.WidgetModel.extend({});\n",
" IPython.widget_manager.register_widget_model('FileWidgetModel', FileModel);\n",
" \n",
" // Define the FilePickerView\n",
"require([\"notebook/js/widgets/widget\"], function(WidgetManager){\n",
"\n",
" var FilePickerView = IPython.WidgetView.extend({\n",
" \n",
" render: function(){\n",
" var that = this;\n",
" this.$el = $('<input />')\n",
" .attr('type', 'file')\n",
" .change(function(evt){ that.handleFileChange(evt) });\n",
" // Render the view.\n",
" this.setElement($('<input />')\n",
" .attr('type', 'file'));\n",
" },\n",
" \n",
" // Handles: User input\n",
" handleFileChange: function(evt) { \n",
" events: {\n",
" // List of events and their handlers.\n",
" 'change': 'handle_file_change',\n",
" },\n",
" \n",
" handle_file_change: function(evt) { \n",
" // Handle when the user has changed the file.\n",
" \n",
" //Retrieve the first (and only!) File from the FileList object\n",
" var that = this;\n",
" var f = evt.target.files[0];\n",
" if (f) {\n",
" var r = new FileReader();\n",
" r.onload = function(e) {\n",
" // Retrieve the first (and only!) File from the FileList object\n",
" var file = evt.target.files[0];\n",
" if (file) {\n",
"\n",
" // Read the file's textual content and set value to those contents.\n",
" var that = this;\n",
" var file_reader = new FileReader();\n",
" file_reader.onload = function(e) {\n",
" that.model.set('value', e.target.result);\n",
" that.model.update_other_views(that);\n",
" that.touch( );\n",
" }\n",
" r.readAsText(f);\n",
" file_reade r.readAsText(file );\n",
" } else {\n",
" this.model.set('on_failed', this.model.get('on_failed') + 1);\n",
" this.model.update_other_views(this);\n",
"\n",
" // The file couldn't be opened. Send an error msg to the\n",
" // back-end.\n",
" this.send({ 'event': 'error' });\n",
" }\n",
" this.model.set('filename', f.name);\n",
" this.model.update_other_views(this);\n",
"\n",
" // Set the filename of the file.\n",
" this.model.set('filename', file.name);\n",
" this.touch();\n",
" },\n",
" });\n",
" \n",
" // Register the DatePickerView with the widget manager.\n",
" IPython.widget_m anager.register_widget_view('FilePickerView', FilePickerView);\n",
" WidgetM anager.register_widget_view('FilePickerView', FilePickerView);\n",
"});"
],
"metadata": {},
"output_type": "display_data",
"text": [
"<IPython.core.display.Javascript at 0x7f14f1c78c d0>"
"<IPython.core.display.Javascript at 0x22870 d0>"
]
}
],
"prompt_number": 3
},
{
"cell_type": "heading",
"level": 1,
"cell_type": "markdown",
"metadata": {},
"source": [
"Usage "
"The following shows how the file widget can be used. "
]
},
{
@ -178,22 +197,28 @@
"collapsed": false,
"input": [
"file_widget = FileWidget()\n",
"display(file_widget)\n",
"\n",
"# Register an event to echo the filename when it has been changed.\n",
"def file_loading():\n",
" print(\"Loading %s\" % file_widget.filename)\n",
"file_widget.on_trait_change(file_loading, 'filename')\n",
"\n",
"# Register an event to echo the filename and contents when a file\n",
"# has been uploaded.\n",
"def file_loaded():\n",
" print(\"Loaded, file contents: %s\" % file_widget.value)\n",
"file_widget.on_trait_change(file_loaded, 'value')\n",
"\n",
"def file_failed(name, old_value, new_value):\n",
" if new_value > old_value:\n",
" print(\"Could not load file contents of %s\" % file_widget.filename)\n",
"\n",
"# Register an event to print an error message when a file could not\n",
"# be opened. Since the error messages are not handled through\n",
"# traitlets but instead handled through custom msgs, the registration\n",
"# of the handler is different than the two examples above. Instead\n",
"# the API provided by the CallbackDispatcher must be used.\n",
"def file_failed():\n",
" print(\"Could not load file contents of %s\" % file_widget.filename)\n",
"file_widget.errors.register_callback(file_failed)\n",
"\n",
"file_widget.on_trait_change(file_loading, 'filename')\n",
"file_widget.on_trait_change(file_loaded, 'value')\n",
"file_widget.on_trait_change(file_failed, 'on_failed')"
"file_widget"
],
"language": "python",
"metadata": {},