Flask — Zero to Hero in 15 Minute

Flask — Zero to Hero in 15 Minute

Hey guys !! Today we gonna learn about one popular python framework called flask. So before we get started let’s learn about what is flask? and when we should use it?

Introduction — A Flasky world

So as I told you before flask is a python framework used for creating web applications. These are some main reasons why Flask is one of the most popular framework.

  1. Lightweight — Flask uses the middleware approach. It means you can install new extension and functionality only when you need it. So it makes the overall size smaller resulting in a very good performance.
  2. Flexibility — Flask is very flexible by nature. It doesn’t force you to do anything in some specific way. For example, it comes with the jinja 2 template support but you can decide if you want to use it or not.
  3. Easy to learn — Because of not a lot of predefined rules and flexible nature it is very easy to get started with the flask and start building website.

All this feature makes flask a very good choice for deploying machine learning model because we need flexibility to make our model work as we want. It’s simple nature also helps us to be focused more on machine learning related stuff and not get lost in the framework.

Getting started — Installation and First Program

I would recommend you install flask in anaconda or virtual env. So it will not conflict with our other python related work( like ML). You can find the complete code written in this blog on this github repository.

After creating a new virtual environment, install flask by following command.

pip install Flask
or
conda install flask

now in your preferred directory. create a file called *app.py* and add following code to it.

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world!!'
if __name__ == "__main__":
app.run(debug=True)

Let’s understand what our code is doing.

In the first line we are importing our flask package then in the second line we are initializing our app. after that we are using @app.route() function what this will do is that when we will run our app and go to index route ( ‘/’) this will automatically trigger the function hello_world(). In the end we are setting debug to true so we can debug our code easily and see all the errors.

In the function, we can write any kind of logic but here we simply returning a string “hello world!!”. So now to run the app execute the following command.

$ python app.py

You will see something like this in the command prompt

Now simply go to your web browser and in address bar type following.

<http://localhost:5000/>
or
[<http://127.0.0.1:5000/>](<http://127.0.0.1:5000/>)

Your web application will open and it will show this simple message “hello world!!”.

Routes and Passing HTML Pages

Now we will learn how we can pass different HTML pages for different routes. First of all, create a templates folder in your working directory and add home.html in that folder.

Your folder structure will look something like this.

-[templates]
-home.html
-app.py

now we will add some this simple formatted message in our html page.

<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello World !!</h1>
</body>
</html>

now save everything and open app.py file and add following new method for home route.

from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world!!'
@app.route('/home')
def greetUser():
return render_template('home.html')

run the app with python app.py command and open you browser you will see output similar to this.

Hello world response from our flask application
Hello world response from our flask application

here as you can see we have used the render_template module for rendering out an HTML page. After importing it we have passed the name of the Html page in the double quote. We don’t have to include “templates/ “ before the name because it is handled by the flask.

We can also pass json object in the render_template() method as second parameter after the name.

Passing Data through Post Request

Now let’s learn how we can make a post request and pass the data to or flask application. For this purpose, I am creating a simple form with one text field. It will ask for mount Everest height and if the correct answer is given, It will show the success message otherwise failure.

Firstly create our test.html page.

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h3> How big is Mount Everest?(in meter) </h3>
<form method="POST" action="/test">
<input type="text" name="height" value="">
<button type="submit" value="submit"> Submit</button>
</form>
<br/>
<p>{{message}}</p>
</body>
</html>

Here we have created one text field with submit button. Look at the following line.

<p>{{message}}</p>

It is a jinja 2 syntax. It comes pre-built with the flask. “ {{ }} “ in this block, we can write any code. We will pass this message variable from the server and it will be shown in the paragraph tag.

We will setup our route. So open your app.py file and add following.

from flask import Flask,render_template,request@app.route('/test',methods=['GET', 'POST'])
def calculateResult():
if request.method == 'POST':
height=request.form['height']
message=''
if height == '8848': #8848 is actual height of mount everest
message="Your Answer:"+height+" You have passed the test,Keep it up."
else:
message="Your Answer:"+height+" You have failed the test, keep trying."
return render_template('test.html', message=message)
else:
return render_template('test.html', message='')

Here we are doing number of things. Lets’s look at all of it one by one.

@app.route('/test',methods=['GET', 'POST'])

We have passed the second parameter in the route which defines the method supported by the route. Here we are using both GET and POST.

After that, we are checking if our request is GET or POST. If it’s GET means our page is opened for the first time so we will simply return our html page with empty message.

height=request.form['height']

In this line of code, we are using request.form[param_name] method to get the value of the height text field.

After that, we are simply checking the value of height and if it is 8848 then we will return success message otherwise failure message.

failure message from server if entered height is wrong.
failure message from server if entered height is wrong.
Success message from server if entered height is correct.
Success message from server if entered height is correct.

Conclusion

In this article, we have learned about flask. We have learned how to install flask, routes, and making GET or POST requests. I hope you have found this article useful. If you have any suggestion or query, please mention them in comment section below or contact me at yash@gkmit.co

Thanks!!

🖋 Writer and Poet | 📙 Books | ✈ Travel | 🟡 Meditation