Serving an Iframe in Google Colab Notebook: localhost refused to connect

核能气质少年 提交于 2021-02-19 04:19:16

问题


I am trying to serve some HTML from a Google Colab notebook using the following:

from IPython.display import IFrame

IFrame(src='./output/index.html', width=700, height=600)

However, this throws localhost refused to connect:

Does anyone know how I can serve the html in index.html (which must load javascript) inside the Colab notebook? Any pointers would be hugely appreciated!


回答1:


You can serve content from the path /nbextensions/ which maps to /usr/local/share/jupyter/nbextensions.

So you can put content there.

!ln -s /usr/local/share/jupyter/nbextensions /nbextensions
%cd /nbextensions
!wget -q https://upload.wikimedia.org/wikipedia/commons/3/37/Youtube.svg

Then serve the image

%%html
<img src=/nbextensions/Youtube.svg>

I can't make it works with IFrame, thought. I don't know why.

Here's an example colab notebook.




回答2:


This built-in example notebook gives a demo: https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=R8ZvCXC5A0wT

Reproducing the example here of serving content from the backend:

import portpicker
import threading
import socket
import IPython

from six.moves import socketserver
from six.moves import SimpleHTTPServer

class V6Server(socketserver.TCPServer):
  address_family = socket.AF_INET6

class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    # If the response should not be cached in the notebook for
    # offline access:
    # self.send_header('x-colab-notebook-cache-control', 'no-cache')
    self.end_headers()
    self.wfile.write(b'''
      document.querySelector('#output-area').appendChild(document.createTextNode('Script result!'));
    ''')

port = portpicker.pick_unused_port()

def server_entry():
    httpd = V6Server(('::', port), Handler)
    # Handle a single request then exit the thread.
    httpd.serve_forever()

thread = threading.Thread(target=server_entry)
thread.start()

# Display some HTML referencing the resource.
display(IPython.display.HTML('<script src="https://localhost:{port}/"></script>'.format(port=port)))



来源:https://stackoverflow.com/questions/59091645/serving-an-iframe-in-google-colab-notebook-localhost-refused-to-connect

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