[IPython-dev] Download a Python-generated file over the web through IPython Notebook

Andrew Payne andy at payne.org
Mon Aug 4 18:41:15 EDT 2014


On Mon, Aug 4, 2014 at 2:18 PM, Alessandro Gagliardi <
alessandro.gagliardi at glassdoor.com> wrote:

>  I’d like to allow users to generate a CSV in a notebook that is hosted
> remotely and download that file to their local machine, perhaps through a
> widget (or some other way that doesn’t require the command line).
>

Another approach is to use a data URI
<https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs>, where a link
is specified "by value" (e.g. the target file contents)  *vs* "by
reference" where the URL points to a server.

For example, this cell presents a link in the output area that downloads a
small CSV file:

%%html
<a href="data:text/csv,1,2,3,4" target="_blank">Click here to download</a>


Generalizing, you should be able to get from (say) a Pandas Dataframe to a
HTML() IPython display object with a "click to download" link in a few
lines of Python.  Or, subclass the dataframe so that all of your dataframe
objects offer a "click to download" option.

Pros:

   - Entirely self-contained, doesn't depend on how/where IPython notebooks
   are served
   - Doesn't require kernel and web server on same machine
   - [90% certain] A published notebook (e.g. nbconvert) will work exactly
   as expected

Cons:

   - Entire CSV content embedded in cell (may be an issue for large files)
   - There are corner cases of lacking or partial browser support (notably,
   old IE)
   - The file is always called "download", unless you do Javascript tricks
   (e.g. see:
   http://stackoverflow.com/questions/833015/does-execcommand-saveas-work-in-firefox/13696029#13696029
   )

Also note there is a new "download" attribute in <a> tags that makes this
even easier.  See:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
Unfortunately, the tag is not (yet) in all major browsers.

-andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20140804/332912d5/attachment.html>


More information about the IPython-dev mailing list