Coding your first Flask Application

  1. Install flask
pip install flask

2. Check if it’s successfully installed

flask --version

II) Basic Flask App

  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/

III) Passing parameters from a URL to our code

  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> '''

IV) Linking Python and HTML

  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.

V) Bonus Section

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 %}

Render data from Flask to html:

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why I love Jenkins so much

Build your personal website without spending any money

Choosing the Right Cloud Provider

READ/DOWNLOAD![ Computer Animation: Algorithms and Techniques FULL BOOK PDF & FULL AUDIOBOOK

4 lessons learnt the hard way in my first year as an Android Developer

Crumbled paper — trial and error

Implementing GStreamer Webcam(USB & Internal) Streaming[Mac & C++ & CLion]

Flutter : Login/Sign Up UI Designs.

Top 10 HTML and CSS Interview Questions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soni Pinjala

Soni Pinjala

Developer | Explorer

More from Medium

Python Web Development

A quick hack to share non-input data between templates in a Flask app

Building your first REST API: Python and Flask

Choosing What to Learn Next