是否有在 Google Colab 上运行 Web 应用程序的通用方法?

新手上路,请多包涵

我想在 Google colab 中开发网络应用程序。唯一的问题是你需要一个连接到本地主机的浏览器来查看网络应用程序,但 Google colab 在笔记本中没有浏览器。

但似乎有办法解决这个问题。例如 run_with_ngrok 是一个用于在 colab/jupyter 笔记本中运行 flaks 应用程序的库

https://github.com/gstaff/flask-ngrok#inside-jupyter–colab-notebooks

当你使用它时,它会给出一个随机地址,“Running on http://.ngrok.io”

不知何故,在 Google colab 上运行的 webapp 正在该地址上运行。

这是 Flask 应用程序的一个很好的解决方案,但我希望在 Google Colab 上运行一般的网络应用程序,而不仅仅是 Flask 的。是否有在 colab/jupyter notebooks 中运行 webapps 的通用方法?

原文由 SantoshGupta7 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

您可以计划在某个端口上启动服务器,例如 port=8000。找到要使用这种方式的 URL。

 from google.colab.output import eval_js
print(eval_js("google.colab.kernel.proxyPort(8000)"))
# https://z4spb7cvssd-496ff2e9c6d22116-8000-colab.googleusercontent.com/

然后,启动服务器,例如

!python -m http.server 8000

然后单击上面的第一个链接(而不是 localhost 或 127.0.0.1),它将在新选项卡中打开。

在单元格中显示

您可以在输出部分的 iframe 中显示结果。我把它变成了一个易于调用的函数。

 from IPython.display import Javascript

def show_port(port, height=400):
  display(Javascript("""
  (async ()=>{
    fm = document.createElement('iframe')
    fm.src = await google.colab.kernel.proxyPort(%s)
    fm.width = '95%%'
    fm.height = '%d'
    fm.frameBorder = 0
    document.body.append(fm)
  })();
  """ % (port, height) ))

现在你可以在后台启动一个 webapp(这里是 http.server)。并将结果显示为它下方的 iframe。

 get_ipython().system_raw('python3 -m http.server 8888 &')
show_port(8888)

要停止服务器,您可以调用 ps 并终止进程。

原文由 korakot 发布,翻译遵循 CC BY-SA 4.0 许可协议

在这里找到答案

在 Google Colab Notebook 中启动 Dash 应用程序

### Install ngrok
!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip

### Run ngrok to tunnel Dash app port 8050 to the outside world.
### This command runs in the background.
get_ipython().system_raw('./ngrok http 8050 &')

### Get the public URL where you can access the Dash app. Copy this URL.
! curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

然后在端口 8050 上启动你的 webapp

原文由 SantoshGupta7 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题