{ "metadata": { "name": "download" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Creating a download link for in-memory data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We define a function that publishes as HTML,\n", "a link with a base64-encoded Data URI containing any string.\n", "This allows you to publish *any* data, of any kind,\n", "from memory as a downloadable link." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from base64 import encodestring\n", "from IPython.display import display, HTML\n", "\n", "def download_link(s, name=\"download\", mimetype=\"text/plain\"):\n", " \"\"\"publish the string `s` as a downloadable link in the notebook\"\"\"\n", " \n", " data = encodestring(s)\n", " display(HTML(\n", " \"{name}\".format(**locals())\n", " ))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The default behavior with a simple string" ] }, { "cell_type": "code", "collapsed": false, "input": [ "download_link(\"hello\")" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "download" ], "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "And we can publish in-memory CSV data, specifying the filename and the mime-type." ] }, { "cell_type": "code", "collapsed": false, "input": [ "my_csv_data = \"\"\"\n", "a b c\n", "1 2 3\n", "4 5 6\n", "7 8 9\n", "\"\"\"\n", "\n", "download_link(my_csv_data, name=\"abc.csv\", mimetype=\"text/csv\")" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "abc.csv" ], "output_type": "display_data", "text": [ "" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also publish binary data" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np\n", "x = np.linspace(0, 2 * np.pi)\n", "outer = np.outer(np.cos(x), np.sin(x))\n", "data = outer.tostring()\n", "download_link(data, name=\"outer_product.np\", mimetype=\"application/octet-stream\")\n", "print 'data = %s... (%.1f kB)' % (repr(data[:24])[1:-1], len(data) / 1024.)" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "outer_product.np" ], "output_type": "display_data", "text": [ "" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "data = \\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8f\\x8d\\xabaG^\\xc0?\\xee\\xcb\\x97o\\xe0;\\xd0?... (19.5 kB)\n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the data for all of these links is embedded into the notebook itself,\n", "so if you share the notebook, the data is included.\n", "\n", "Be careful with this, because if you embed large data in the notebook, it can take a long time to load." ] } ], "metadata": {} } ] }