Reputation: 4340
Given an iPython notebook running on an external server, is there a way to trigger a file download?
I would like to either be able to have the notebook be able to initiate the download of a file living on the the external server to the where the notebook is being rendered locally, or perform a direct string dump from the notebook workspace into a text file, downloaded locally.
I.E. a powerful and tool would be a Notebook that can query from a database, alter data, and download the query results as a CSV file.
A quick experiment showed that a cell containing the following renders a link which downloads a file. I'm hoping for a cleaner solution than rendering data into an html frame.
%%html
<a href="data:application/octet-stream,'string of things'">Download a file</a>
Upvotes: 25
Views: 12673
Reputation: 89
There's a short implementation in the hublib library
https://github.com/hubzero/hublib/blob/master/hublib/ui/download.py
They have several documented examples. (The cb
argument is used if you want to customize a callback function.)
https://github.com/hubzero/hublib/blob/master/examples/download.ipynb
Upvotes: 0
Reputation: 5645
Alternatively, if the file's aren't too large and hence suitable for base64 encoding. This only works in 'recent browsers', but ipynb users will likely have one. This example works with JSON data.
from IPython.display import display, HTML
import json
import base64
encoded = base64.b64encode(json.dumps(data).encode('utf-8')).decode('utf-8')
HTML(f'<a href="data:application/json;base64,{encoded}" download="download.json">download</a>')
Upvotes: 2
Reputation: 6572
I got a working answer from the comments. FileLink
did the job, which was to be able to download a file from a notebook.
from IPython.display import display, FileLink
local_file = FileLink('./demo.xlsx', result_html_prefix="Click here to download: ")
display(local_file)
For the sake of completeness, here is a similar example with FileLinks
:
from IPython.display import display, FileLinks
local_file = FileLinks('./data/', result_html_prefix="Click here to download: ")
display(local_file)
It's not very pretty, so would love some advice for styling it..
Upvotes: 17
Reputation: 4821
You can use the urllib
library to download files or request URLs.
testfile = urllib.URLopener()
testfile.retrieve("http://exmaple.com/file.txt", "file.txt")
Upvotes: -5