##// END OF EJS Templates
Update File Upload Widget.ipynb
epifanio -
Show More
@@ -1,248 +1,248 b''
1 {
1 {
2 "metadata": {
2 "metadata": {
3 "cell_tags": [
3 "cell_tags": [
4 [
4 [
5 "<None>",
5 "<None>",
6 null
6 null
7 ]
7 ]
8 ],
8 ],
9 "name": ""
9 "name": ""
10 },
10 },
11 "nbformat": 3,
11 "nbformat": 3,
12 "nbformat_minor": 0,
12 "nbformat_minor": 0,
13 "worksheets": [
13 "worksheets": [
14 {
14 {
15 "cells": [
15 "cells": [
16 {
16 {
17 "cell_type": "code",
17 "cell_type": "code",
18 "collapsed": false,
18 "collapsed": false,
19 "input": [
19 "input": [
20 "import base64\n",
20 "import base64\n",
21 "from __future__ import print_function # py 2.7 compat.\n",
21 "from __future__ import print_function # py 2.7 compat.\n",
22 "from IPython.html import widgets # Widget definitions.\n",
22 "from IPython.html import widgets # Widget definitions.\n",
23 "from IPython.utils.traitlets import Unicode # Traitlet needed to add synced attributes to the widget."
23 "from IPython.utils.traitlets import Unicode # Traitlet needed to add synced attributes to the widget."
24 ],
24 ],
25 "language": "python",
25 "language": "python",
26 "metadata": {},
26 "metadata": {},
27 "outputs": [],
27 "outputs": [],
28 "prompt_number": 1
28 "prompt_number": 1
29 },
29 },
30 {
30 {
31 "cell_type": "markdown",
31 "cell_type": "markdown",
32 "metadata": {},
32 "metadata": {},
33 "source": [
33 "source": [
34 "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."
34 "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."
35 ]
35 ]
36 },
36 },
37 {
37 {
38 "cell_type": "code",
38 "cell_type": "code",
39 "collapsed": false,
39 "collapsed": false,
40 "input": [
40 "input": [
41 "class FileWidget(widgets.DOMWidget):\n",
41 "class FileWidget(widgets.DOMWidget):\n",
42 " _view_name = Unicode('FilePickerView', sync=True)\n",
42 " _view_name = Unicode('FilePickerView', sync=True)\n",
43 " value = Unicode(sync=True)\n",
43 " value = Unicode(sync=True)\n",
44 " filename = Unicode(sync=True)\n",
44 " filename = Unicode(sync=True)\n",
45 " \n",
45 " \n",
46 " def __init__(self, **kwargs):\n",
46 " def __init__(self, **kwargs):\n",
47 " \"\"\"Constructor\"\"\"\n",
47 " \"\"\"Constructor\"\"\"\n",
48 " widgets.DOMWidget.__init__(self, **kwargs) # Call the base.\n",
48 " widgets.DOMWidget.__init__(self, **kwargs) # Call the base.\n",
49 " \n",
49 " \n",
50 " # Allow the user to register error callbacks with the following signatures:\n",
50 " # Allow the user to register error callbacks with the following signatures:\n",
51 " # callback()\n",
51 " # callback()\n",
52 " # callback(sender)\n",
52 " # callback(sender)\n",
53 " self.errors = widgets.CallbackDispatcher(accepted_nargs=[0, 1])\n",
53 " self.errors = widgets.CallbackDispatcher(accepted_nargs=[0, 1])\n",
54 " \n",
54 " \n",
55 " # Listen for custom msgs\n",
55 " # Listen for custom msgs\n",
56 " self.on_msg(self._handle_custom_msg)\n",
56 " self.on_msg(self._handle_custom_msg)\n",
57 "\n",
57 "\n",
58 " def _handle_custom_msg(self, content):\n",
58 " def _handle_custom_msg(self, content):\n",
59 " \"\"\"Handle a msg from the front-end.\n",
59 " \"\"\"Handle a msg from the front-end.\n",
60 "\n",
60 "\n",
61 " Parameters\n",
61 " Parameters\n",
62 " ----------\n",
62 " ----------\n",
63 " content: dict\n",
63 " content: dict\n",
64 " Content of the msg.\"\"\"\n",
64 " Content of the msg.\"\"\"\n",
65 " if 'event' in content and content['event'] == 'error':\n",
65 " if 'event' in content and content['event'] == 'error':\n",
66 " self.errors()\n",
66 " self.errors()\n",
67 " self.errors(self)\n",
67 " self.errors(self)\n",
68 " "
68 " "
69 ],
69 ],
70 "language": "python",
70 "language": "python",
71 "metadata": {},
71 "metadata": {},
72 "outputs": [],
72 "outputs": [],
73 "prompt_number": 2
73 "prompt_number": 2
74 },
74 },
75 {
75 {
76 "cell_type": "code",
76 "cell_type": "code",
77 "collapsed": false,
77 "collapsed": false,
78 "input": [
78 "input": [
79 "%%javascript\n",
79 "%%javascript\n",
80 "\n",
80 "\n",
81 "require([\"widgets/js/widget\"], function(WidgetManager){\n",
81 "require([\"widgets/js/widget\"], function(WidgetManager){\n",
82 "\n",
82 "\n",
83 " var FilePickerView = IPython.WidgetView.extend({\n",
83 " var FilePickerView = IPython.WidgetView.extend({\n",
84 " render: function(){\n",
84 " render: function(){\n",
85 " // Render the view.\n",
85 " // Render the view.\n",
86 " this.setElement($('<input />')\n",
86 " this.setElement($('<input />')\n",
87 " .attr('type', 'file'));\n",
87 " .attr('type', 'file'));\n",
88 " },\n",
88 " },\n",
89 " \n",
89 " \n",
90 " events: {\n",
90 " events: {\n",
91 " // List of events and their handlers.\n",
91 " // List of events and their handlers.\n",
92 " 'change': 'handle_file_change',\n",
92 " 'change': 'handle_file_change',\n",
93 " },\n",
93 " },\n",
94 " \n",
94 " \n",
95 " handle_file_change: function(evt) { \n",
95 " handle_file_change: function(evt) { \n",
96 " // Handle when the user has changed the file.\n",
96 " // Handle when the user has changed the file.\n",
97 " \n",
97 " \n",
98 " // Retrieve the first (and only!) File from the FileList object\n",
98 " // Retrieve the first (and only!) File from the FileList object\n",
99 " var file = evt.target.files[0];\n",
99 " var file = evt.target.files[0];\n",
100 " if (file) {\n",
100 " if (file) {\n",
101 "\n",
101 "\n",
102 " // Read the file's textual content and set value to those contents.\n",
102 " // Read the file's textual content and set value to those contents.\n",
103 " var that = this;\n",
103 " var that = this;\n",
104 " var file_reader = new FileReader();\n",
104 " var file_reader = new FileReader();\n",
105 " file_reader.onload = function(e) {\n",
105 " file_reader.onload = function(e) {\n",
106 " that.model.set('value', e.target.result);\n",
106 " that.model.set('value', e.target.result);\n",
107 " that.touch();\n",
107 " that.touch();\n",
108 " }\n",
108 " }\n",
109 " file_reader.readAsText(file);\n",
109 " file_reader.readAsText(file);\n",
110 " } else {\n",
110 " } else {\n",
111 "\n",
111 "\n",
112 " // The file couldn't be opened. Send an error msg to the\n",
112 " // The file couldn't be opened. Send an error msg to the\n",
113 " // back-end.\n",
113 " // back-end.\n",
114 " this.send({ 'event': 'error' });\n",
114 " this.send({ 'event': 'error' });\n",
115 " }\n",
115 " }\n",
116 "\n",
116 "\n",
117 " // Set the filename of the file.\n",
117 " // Set the filename of the file.\n",
118 " this.model.set('filename', file.name);\n",
118 " this.model.set('filename', file.name);\n",
119 " this.touch();\n",
119 " this.touch();\n",
120 " },\n",
120 " },\n",
121 " });\n",
121 " });\n",
122 " \n",
122 " \n",
123 " // Register the DatePickerView with the widget manager.\n",
123 " // Register the DatePickerView with the widget manager.\n",
124 " WidgetManager.register_widget_view('FilePickerView', FilePickerView);\n",
124 " WidgetManager.register_widget_view('FilePickerView', FilePickerView);\n",
125 "});"
125 "});"
126 ],
126 ],
127 "language": "python",
127 "language": "python",
128 "metadata": {},
128 "metadata": {},
129 "outputs": [
129 "outputs": [
130 {
130 {
131 "javascript": [
131 "javascript": [
132 "\n",
132 "\n",
133 "require([\"notebook/js/widgets/widget\"], function(WidgetManager){\n",
133 "require([\"widgets/js/widget\"], function(WidgetManager){\n",
134 "\n",
134 "\n",
135 " var FilePickerView = IPython.WidgetView.extend({\n",
135 " var FilePickerView = IPython.WidgetView.extend({\n",
136 " render: function(){\n",
136 " render: function(){\n",
137 " // Render the view.\n",
137 " // Render the view.\n",
138 " this.setElement($('<input />')\n",
138 " this.setElement($('<input />')\n",
139 " .attr('type', 'file'));\n",
139 " .attr('type', 'file'));\n",
140 " },\n",
140 " },\n",
141 " \n",
141 " \n",
142 " events: {\n",
142 " events: {\n",
143 " // List of events and their handlers.\n",
143 " // List of events and their handlers.\n",
144 " 'change': 'handle_file_change',\n",
144 " 'change': 'handle_file_change',\n",
145 " },\n",
145 " },\n",
146 " \n",
146 " \n",
147 " handle_file_change: function(evt) { \n",
147 " handle_file_change: function(evt) { \n",
148 " // Handle when the user has changed the file.\n",
148 " // Handle when the user has changed the file.\n",
149 " \n",
149 " \n",
150 " // Retrieve the first (and only!) File from the FileList object\n",
150 " // Retrieve the first (and only!) File from the FileList object\n",
151 " var file = evt.target.files[0];\n",
151 " var file = evt.target.files[0];\n",
152 " if (file) {\n",
152 " if (file) {\n",
153 "\n",
153 "\n",
154 " // Read the file's textual content and set value to those contents.\n",
154 " // Read the file's textual content and set value to those contents.\n",
155 " var that = this;\n",
155 " var that = this;\n",
156 " var file_reader = new FileReader();\n",
156 " var file_reader = new FileReader();\n",
157 " file_reader.onload = function(e) {\n",
157 " file_reader.onload = function(e) {\n",
158 " that.model.set('value', e.target.result);\n",
158 " that.model.set('value', e.target.result);\n",
159 " that.touch();\n",
159 " that.touch();\n",
160 " }\n",
160 " }\n",
161 " file_reader.readAsText(file);\n",
161 " file_reader.readAsText(file);\n",
162 " } else {\n",
162 " } else {\n",
163 "\n",
163 "\n",
164 " // The file couldn't be opened. Send an error msg to the\n",
164 " // The file couldn't be opened. Send an error msg to the\n",
165 " // back-end.\n",
165 " // back-end.\n",
166 " this.send({ 'event': 'error' });\n",
166 " this.send({ 'event': 'error' });\n",
167 " }\n",
167 " }\n",
168 "\n",
168 "\n",
169 " // Set the filename of the file.\n",
169 " // Set the filename of the file.\n",
170 " this.model.set('filename', file.name);\n",
170 " this.model.set('filename', file.name);\n",
171 " this.touch();\n",
171 " this.touch();\n",
172 " },\n",
172 " },\n",
173 " });\n",
173 " });\n",
174 " \n",
174 " \n",
175 " // Register the DatePickerView with the widget manager.\n",
175 " // Register the DatePickerView with the widget manager.\n",
176 " WidgetManager.register_widget_view('FilePickerView', FilePickerView);\n",
176 " WidgetManager.register_widget_view('FilePickerView', FilePickerView);\n",
177 "});"
177 "});"
178 ],
178 ],
179 "metadata": {},
179 "metadata": {},
180 "output_type": "display_data",
180 "output_type": "display_data",
181 "text": [
181 "text": [
182 "<IPython.core.display.Javascript at 0x36df2d0>"
182 "<IPython.core.display.Javascript at 0x36df2d0>"
183 ]
183 ]
184 }
184 }
185 ],
185 ],
186 "prompt_number": 3
186 "prompt_number": 3
187 },
187 },
188 {
188 {
189 "cell_type": "markdown",
189 "cell_type": "markdown",
190 "metadata": {},
190 "metadata": {},
191 "source": [
191 "source": [
192 "The following shows how the file widget can be used."
192 "The following shows how the file widget can be used."
193 ]
193 ]
194 },
194 },
195 {
195 {
196 "cell_type": "code",
196 "cell_type": "code",
197 "collapsed": false,
197 "collapsed": false,
198 "input": [
198 "input": [
199 "file_widget = FileWidget()\n",
199 "file_widget = FileWidget()\n",
200 "\n",
200 "\n",
201 "# Register an event to echo the filename when it has been changed.\n",
201 "# Register an event to echo the filename when it has been changed.\n",
202 "def file_loading():\n",
202 "def file_loading():\n",
203 " print(\"Loading %s\" % file_widget.filename)\n",
203 " print(\"Loading %s\" % file_widget.filename)\n",
204 "file_widget.on_trait_change(file_loading, 'filename')\n",
204 "file_widget.on_trait_change(file_loading, 'filename')\n",
205 "\n",
205 "\n",
206 "# Register an event to echo the filename and contents when a file\n",
206 "# Register an event to echo the filename and contents when a file\n",
207 "# has been uploaded.\n",
207 "# has been uploaded.\n",
208 "def file_loaded():\n",
208 "def file_loaded():\n",
209 " print(\"Loaded, file contents: %s\" % file_widget.value)\n",
209 " print(\"Loaded, file contents: %s\" % file_widget.value)\n",
210 "file_widget.on_trait_change(file_loaded, 'value')\n",
210 "file_widget.on_trait_change(file_loaded, 'value')\n",
211 "\n",
211 "\n",
212 "# Register an event to print an error message when a file could not\n",
212 "# Register an event to print an error message when a file could not\n",
213 "# be opened. Since the error messages are not handled through\n",
213 "# be opened. Since the error messages are not handled through\n",
214 "# traitlets but instead handled through custom msgs, the registration\n",
214 "# traitlets but instead handled through custom msgs, the registration\n",
215 "# of the handler is different than the two examples above. Instead\n",
215 "# of the handler is different than the two examples above. Instead\n",
216 "# the API provided by the CallbackDispatcher must be used.\n",
216 "# the API provided by the CallbackDispatcher must be used.\n",
217 "def file_failed():\n",
217 "def file_failed():\n",
218 " print(\"Could not load file contents of %s\" % file_widget.filename)\n",
218 " print(\"Could not load file contents of %s\" % file_widget.filename)\n",
219 "file_widget.errors.register_callback(file_failed)\n",
219 "file_widget.errors.register_callback(file_failed)\n",
220 "\n",
220 "\n",
221 "file_widget"
221 "file_widget"
222 ],
222 ],
223 "language": "python",
223 "language": "python",
224 "metadata": {},
224 "metadata": {},
225 "outputs": [
225 "outputs": [
226 {
226 {
227 "output_type": "stream",
227 "output_type": "stream",
228 "stream": "stdout",
228 "stream": "stdout",
229 "text": [
229 "text": [
230 "Loading test.txt\n"
230 "Loading test.txt\n"
231 ]
231 ]
232 },
232 },
233 {
233 {
234 "output_type": "stream",
234 "output_type": "stream",
235 "stream": "stdout",
235 "stream": "stdout",
236 "text": [
236 "text": [
237 "Loaded, file contents: Hello World!\n",
237 "Loaded, file contents: Hello World!\n",
238 "\n"
238 "\n"
239 ]
239 ]
240 }
240 }
241 ],
241 ],
242 "prompt_number": 4
242 "prompt_number": 4
243 }
243 }
244 ],
244 ],
245 "metadata": {}
245 "metadata": {}
246 }
246 }
247 ]
247 ]
248 }
248 }
General Comments 0
You need to be logged in to leave comments. Login now