Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Flask in Google Colaboratory Python Notebook?

I am trying to build a website using Flask, in a Google Colab Python notebook. However, running a regular Flask code that works on a regular Python, fails to work on Google Colab. I need code that will work it out please.. :)

like image 330
Daniel Shemesh Avatar asked Jan 31 '19 17:01

Daniel Shemesh


People also ask

Can we run Flask code in Google Colab?

This entire code can be run on Google Colab, without installing anything on our local machine. Google Colab provides a virtual machine environment, so unlike when running Flask on our local machine, we cannot access localhost.

Can we use Flask in Jupyter Notebook?

It's a library you can pip install on your computer or wherever your Notebook is running. It works for any Python process - this happens to be a Jupyter Notebook, but it could be an ordinary Python script, a Flask app, even the Python REPL!


3 Answers

from flask_ngrok import run_with_ngrok
from flask import Flask

app = Flask(__name__)

run_with_ngrok(app)  
@app.route("/")

def home():
    return f"Running Flask on Google Colab!"

app.run()
like image 113
Aryan Gupta Avatar answered Sep 20 '22 06:09

Aryan Gupta


The server code:

import socket
print(socket.gethostbyname(socket.getfqdn(socket.gethostname())))

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

import threading
threading.Thread(target=app.run, kwargs={'host':'0.0.0.0','port':80}).start() 

Client code:

import requests
r = requests.get("http://172.28.0.2/")
print(r.status_code)
print(r.encoding)
print(r.apparent_encoding)
print(r.text)

To restart Flask you may click menu: runtime->restart runtime

Share link here :

enter image description here

like image 45
tinyhare Avatar answered Sep 19 '22 06:09

tinyhare


The server side code AKA: backend

from flask import Flask
import threading

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

threading.Thread(target=app.run, kwargs={'host':'0.0.0.0','port':6060}).start()

Rendering the server inside the colab

import IPython.display

def display(port, height):
    shell = """
        (async () => {
            const url = await google.colab.kernel.proxyPort(%PORT%, {"cache": true});
            const iframe = document.createElement('iframe');
            iframe.src = url;
            iframe.setAttribute('width', '100%');
            iframe.setAttribute('height', '%HEIGHT%');
            iframe.setAttribute('frameborder', 0);
            document.body.appendChild(iframe);
        })();
    """
    replacements = [
        ("%PORT%", "%d" % port),
        ("%HEIGHT%", "%d" % height),
    ]
    for (k, v) in replacements:
        shell = shell.replace(k, v)

    script = IPython.display.Javascript(shell)
    IPython.display.display(script)

display(6060, 400)
like image 33
isnvi23h4 Avatar answered Sep 20 '22 06:09

isnvi23h4