Trigger File Download within iPython Notebook

别等时光非礼了梦想. 提交于 2020-02-21 10:19:06

问题


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>

回答1:


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..




回答2:


You can use the urllib library to download files or request URLs.

testfile = urllib.URLopener()
testfile.retrieve("http://exmaple.com/file.txt", "file.txt")


来源:https://stackoverflow.com/questions/26497912/trigger-file-download-within-ipython-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!