Running Flask App with Google Colab

Devesh Surve
3 min readJun 7, 2020

--

Want to learn Flask, but do not want to set up a virtual environment, install packages and host a server ? Well, I had a similar problem. And Google Colab was the solution.

Since I couldn't find a simple tutorial to set up a flask application without installing stuff I have decided to make one.

And it’s pretty simple, so let’s get started !

The 2 main problems I had when creating a flask app on colab were as follows:

  1. First I could not access the localhost : 5000 url as Google Colab provides a VM(virtual machine) as we do on our local machine when running a local web server. What we can do however, is expose it to a public URL
from google.colab.output import eval_js
print(eval_js("google.colab.kernel.proxyPort(5000)"))

We get something like this. Now this is a proxy port url, basically means that whatever is happening in localhost:5000 is shown in this link.

https://c1qknz4fuo-496ff2e9c6d22116-5000-colab.googleusercontent.com/

Now that we are here, let’s create a simple Flask app !

from flask import Flaskapp = Flask(__name__)@app.route("/")
def home():
return "Hello, World!"

if __name__ == "__main__":
app.run()

So this is how it should look like :

Now, click on the generated link above and you shall get this page

Boom ! Here’s our flask app up and running. No installs required.

2. Remember the 2 problems I faced ? No ? Well here’s the second one what if I wanted to use my own template. My own html file ? Couldn’t find Here’s how to use render_template in google colab

First Mount your drive by clicking on the Mount Drive option on the left files panel.

It shall ask you to sign in and you will have all your drive files accessible.

Now, create a folder called templates and put your hello.html file in that folder

Here’s a basic hello.html for your reference

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<h1>Welcome to the Flask Tutorial !</h1>
<p>Let's begin !</p>
</body>
</html>

Now put this in your templates folder and you should something like this

drive > My Drive > templates > hello.html

Here’s the most important part. Add the following parameter to your flask app definition.

from flask import Flask, render_template
app = Flask(__name__, template_folder='drive/My Drive/templates')
@app.route("/")
def home():
return render_template('hello.html')

if __name__ == "__main__":
app.run()

Re run the cell and open the link and now, you now get this !

So that’s how you run a flask app on google colab without installing anything along with how to use render template in colab.

--

--

Devesh Surve
Devesh Surve

Written by Devesh Surve

Grad student by day, lifelong ML/AI explorer by night. I dive deep, then share easy-to-understand, step-by-step guides to demystify the complex.

Responses (2)