是否有在 Google Colab 上运行 Web 应用程序的通用方法? [英] Is there a general way to run Web Applications on Google Colab?
问题描述
我想在 Google colab 中开发网络应用.唯一的问题是你需要一个连接到本地主机的浏览器来查看网络应用程序,但谷歌 colab 在笔记本中没有浏览器.
I would like to develop web apps in Google colab. The only issue is that you need a browser connected to local host to view the web app, but Google colab doesn't have a browser inside the notebook.
但似乎有办法解决这个问题.例如 run_with_ngrok 是一个用于在 colab/jupyter notebooks 中运行 flaks 应用程序的库
But it seems that there are ways around this. For example run_with_ngrok is a library for running flaks apps in colab/jupyter notebooks
https://github.com/gstaff/flask-ngrok#inside-jupyter--colab-notebooks
当你使用它时,它会给出一个随机地址,Running on http://.ngrok.io"
When you use it, it gives a random address , "Running on http://.ngrok.io"
不知何故,在 Google colab 上运行的网络应用程序正在该地址上运行.
And somehow the webapp that's running on Google colab is running on that address.
这对于 Flask 应用程序来说是一个很好的解决方案,但我希望在 Google Colab 上运行一般的 web 应用程序,而不仅仅是 Flask 应用程序.是否有在 colab/jupyter notebooks 中运行 webapps 的通用方法?
This is a great solution for Flask apps, but I am looking to run webapps in general on Google Colab, not just Flask ones. Is there a general method for running webapps in colab/jupyter notebooks?
推荐答案
您可以计划在端口上启动服务器,例如端口=8000.找到使用这种方式的网址.
You can plan to start a server on a port, e.g. port=8000. Find the URL to use this way.
from google.colab.output import eval_js
print(eval_js("google.colab.kernel.proxyPort(8000)"))
# https://z4spb7cvssd-496ff2e9c6d22116-8000-colab.googleusercontent.com/
然后,启动服务器,例如
Then, start the server, e.g.
!python -m http.server 8000
然后单击上面的第一个链接(而不是 localhost 或 127.0.0.1),它将在新选项卡中打开.
And click the first link above (instead of localhost or 127.0.0.1), it will open in a new tab.
您可以在输出部分的 iframe 中显示结果.我把它变成了一个容易调用的函数.
You can display the result in an iframe in the output part. I made it into an easy function to call.
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) ))
现在您可以在后台启动一个 web 应用程序(这里是 http.server).并将结果显示为它下方的 iframe.
Now you can start a webapp (here it is http.server) in a background. And display the result as an iframe below it.
get_ipython().system_raw('python3 -m http.server 8888 &')
show_port(8888)
要停止服务器,您可以调用 ps
并终止进程.
To stop the server, you can call ps
and kill the process.
这篇关于是否有在 Google Colab 上运行 Web 应用程序的通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!