Coding your first Flask Application

  1. Install flask
pip install flask

2. Check if it’s successfully installed

flask --version
  1. Create a new python file and write a Hello World code, let’s say app.py
from flask import Flask #Flask is an object#now we will create a flask app using that Flask object by calling the Flask constructor [Flask()]app = Flask(__name__) #in case you are not so well versed with py, then __name__ references this file#now the actual thing begins
#let's define a url
@app.route('/') #base url
def hello():
return "Hello World"
if __name__ == "__main__":
app.run(debug=True) #it's for devs who are running this code on the terminal so that if the code encounters some errors, they get to see them on the terminal

Read the comments in order to understand the code better. Now run your code. If you are using your terminal, then type in the following and hit Enter.

python app.py

As we don’t have our own domain name, we will be running on our localhost, which is, http://127.0.0.1:5000/

  1. Now let’s code to say personalized Hello by passing parameters, add the below snippet to app.py and play with it!
@app.route('/home/<string:name>')
def hello(name):
return "Hello, " + name

Know about the GET and POST requests(sounds scary?? No worries, it’s all in the name, will be quite simple to understand!), and also REMEMBER, the return statements simply spit whatever that is asked to return, for that sake even raw HTML code by using multi-line string, i.e

return ''' <h1> Hello World </h1>
<h2> Line 2 </h2> '''
  1. Create a new folder called ‘templates’ within the same folder as the app.py. After that, create a HTML file inside templates, let’s say ‘index.html’

Quick Tip: If you are using VSCode, then install HTML Boilerplate extension if you haven’t already, it will save some of your precious seconds

<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Hello World</h1></body>
</html>

2. Now we will render HTML file with flask, to do that we have to import render_template

from flask import Flask, render_template

And then make the below change in app.py,

@app.route('/')
def index():
return render_template('index.html')

Now, the flask application will be rendering with the HTML file, and feel free to make changes to your HTML file and check out the changes.

Now let’s try template inheritence so that we have all the commonly used blocks at the same place. We will be using something called jinja2(we can write loops in html file, cool right!!!!!!!!!), which comes with flask. Example of the current page using jinja2 syntax, let’s create another html page, ‘base.html’

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% block head %} {% endblock %}</head>
<body>
{% block body %} {% endblock %}</body>
</html>

Change the content of ‘index.html’ like below, connecting it with ‘base.html’

{% extends 'base.html' %}
{% block head %}<title>Home</title>{% endblock %}{% block body %}<h1>Home page</h1>{% endblock %}

First, create a list/dictionary, dictionary is preferable as it works very well with jinja. Let’s create a list of dictionary now,

students = [
{
'name': 'Arjun',
'remark': 'He is a good singer.'
},
{
'name': 'Harsh',
'remark': 'He is a good dancer.'
}
]

It’s just an example, feel free to create your own personalised list, with personalised attributes and size.

Add the below code, or modify the existing code accordingly,

@app.route('/students')
def students():
return render_template('students.html', school=students)

Add the below code to the body of your html page,

{% for post in posts %}
<h2>{{ school.name }}</h2>
<p>{{ school.remark }}</p>
{% endfor %}

Also, let’s say you have added some more attribites to each dictionary, like teacher, clubs, subjects etc, and one of the student isn’t part of any club so you exclude that attribute while creating the dictionary for him/her. Now, when you are trying to print all these attributes, jinja prints the data available and ignores if it is not, instead of throwing errors.

You can check if some data is missing though! Use If loop and check if the particular attribute is present and perform some actions accordingly. Eg,

{% if student.club %}
<h3>Part of: {{ student.club }}</h3>
{% else %}
<h3>Part of: N/A</h3>
{% endif %}

You can also link your css file to html using jinja, which is a more robust way. Systax to do it will be,

<link rel="stylesheet" href="{{ rl_for('static',filename='css/main.css') }}"> #path for css file is (./static/css/main.css)

Developer | Explorer