Render a Jupyter Notebook Iframe in Flask

2020-07-29 17:19发布

问题:

I'm using Flask to host a UI for a single user. Something I've been trying to do is setup a way for user to click a button that inserts some text and images in a pre-specified place in a document using markup language. I originally used Jinja2 for this but the issue is the user needs to be able to modify the document after the data is inserted in case they need to make small changes to the text or add a line etc... which to my knowledge can't be done with a flask-rendered template.

I understand it is possible to bring a Jupyter Notebook (Which is based on markup language) into the UI using an iframe but I haven't had success in doing that.

What I've tried:

  1. Configuring my Jupyter notebook to be public
  2. Placing an Iframe with my public Jupyter address <iframe width="400" height="400" src="http://10.33.75.112:8888/notebooks/Desktop/Tool/test.ipynb"/> into my HTML template file... which brings up a blank Iframe that I can't interact with
  3. Messed around with NBviewer and NBconvert to see if there was some way I could integrate that but haven't had any success.

Ideas?

回答1:

I found a solution.

In the Jupyter-notebook-config.py folder there are a couple options you need to uncomment and modify to get this going.

c.NotebookApp.allow_origin = '*' #Basic permission
c.NotebookApp.disable_check_xsrf = True #Otherwise Jupyter restricts you modifying the Iframed Notebook
c.NotebookApp.ip = 'ENTER_YOUR_JUPYTER_IP_ADDRESS' #Appears in the top browser bar when you launch jupyter
c.NotebookApp.port = 8888 #Your choice of port
c.NotebookApp.token = '' #In my case I didn't want to deal with security
c.NotebookApp.trust_xheaders = True #May or may not make a difference to you

c.NotebookApp.tornado_settings = {
'headers': {
'Content-Security-Policy': "frame-ancestors 'http://127.0.0.1:5000/' 'self' "
}
} #assuming your Flask localhost is 127.0.0.1:5000

Then in the HTML:

<iframe width="1000" height="1000"  src="http://ENTER_YOUR_JUPYTER_IP_ADDRESS:8888/notebooks/Desktop/test.ipynb"/>

Edit: Also Google Chrome has an error displaying iframes like this so use either Mozilla or IE.