Is there a general way to run Web Applications on Google Colab?

前端 未结 4 1735
小蘑菇
小蘑菇 2020-12-29 13:06

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 bro

4条回答
  •  礼貌的吻别
    2020-12-29 13:46

    The below solution, explains

    1. running the python script/API in the background
    2. Get a web link to access the script output in browser tab
    3. Configure the script as web server on ip:port using cherrypy
    4. Create definitions(end points, ex: /index) within the script.

    To run the script in the background, use below code, that will output a link that looks like https://wrea1crizb-496ff2e9c6d22116-8888-colab.googleusercontent.com/ through which output can be seen on a web browser.

    !pip install CherryPy #webserver package
    
    #bind the port 8888 and get a weblink to access
    from google.colab.output import eval_js
    print(eval_js("google.colab.kernel.proxyPort(8888)"))
    
    #run the script/API in the background
    import subprocess
    subprocess.Popen(["python", "/content/test.py", "8888"]) 
    

    Create test.py file and add the below code,

    import cherrypy
    import sys
    
    class HelloWorld:
        def index(self):
            return "Hello World!"
        index.exposed = True
    if __name__ == '__main__':
       config = {'server.socket_host': '0.0.0.0','server.socket_port' : int(sys.argv[1])}
       cherrypy.config.update(config)
       cherrypy.quickstart(HelloWorld())
    

提交回复
热议问题