What will you learn?

  1. Flask Introduction: Definition and how to install
  2. Get started with Flask: print Hello World
  3. Flask: Write HTML code
  4. Add multiple routes
  5. Add a login and a logout page
  6. Perform an action when a submit button is clicked
  7. Get the required image, CSS, and HTML file for this project

Flask Introduction: Definition and how to install

Flask is a Python-based web application framework i.e. it is a third-party Python package that is used to create web apps.

To install Flask:

pip install flask

Get started with Flask: print Hello World

Let's print "Hello World". 

'/' indicates our home page which we have to pass during routing. This code prints 'Hello World' on our main page or home page.

from flask import Flask
app = Flask(__name__)

@app.route("/")  # flask routing
def hello():
    return "Hello World…"

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

Flask: Write HTML code

We can also return html code as below.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World… <h1>Ishwar</h1>"

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

Add multiple routes

Now, the below code contains two routes: one is a home page, and another to display your name. When you write your name in the URL, it will display the output as "Hello {your name}! How are you?"

from flask import Flask  
app = Flask(__name__)  

@app.route("/")
def home():
    return "This is home page"

@app.route("/<name>")
def user(name):
    return f"Hello {name}! How are you?" 
  
if __name__ =="__main__":  
    app.run()

"/" indicates the home page, right? 

We can also pass two routes for the same function.

from flask import Flask  
app = Flask(__name__)  

@app.route("/")
@app.route("/home")
def home():
    return "This is home page"

@app.route("/home/<name>")
def user(name):
    return f"Hello {name}! How are you?" 
  
if __name__ =="__main__":  
    app.run()

Now, "/home" also indicates the home page.

We are not required to basically return messages; we are free to return HTML pages as well. For this, we have to import render_template from the flask, and then all we have to do is, pass the name of the HTML page in render_template.

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
@app.route("/home")
def home():
    return "This is home page"

@app.route("/html")
def html():
    return render_template("new.html")
  
if __name__ =="__main__":  
    app.run()

Add a login and a logout page

Let's add a login and logout page. The login page displays a message as "Login successfully" whereas the logout page redirects us to the home page.

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route("/")  
@app.route("/home")
def home():
    return "This is home page"

@app.route("/login")
def login():
    return ("Login successfully....")

@app.route("/logout")
def logout():
    return redirect(url_for("home"))
    

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

Let's add html file to our home page and login page. (The code for the HTML page is attached below)

from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)

@app.route("/")  
@app.route("/home")
def home():
    return render_template("home.html")

@app.route("/login")
def login():
    return render_template("login.html")

@app.route("/logout")
def logout():
    return redirect(url_for("home"))
    

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

Perform an action when a submit button is clicked

I have made a form on the login.html page. But what happens if I click the submit button?

I have to perform some action when I click the submit button, right?

Here, I have added a submit function to display messages as per our action.

from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)

@app.route("/")  
@app.route("/home")
def home():
    return render_template("home.html")

@app.route("/login")
def login():
    return render_template("login.html")

@app.route("/logout")
def logout():
    return redirect(url_for("home"))

@app.route('/submit',methods = ['POST', 'GET'])
def submit():
    if request.method == 'POST':
        user = request.form['nm']
        return f"Login successfully by post method, Hello {user}"
    else:
        user = request.args.get('nm')
        return f"Login successfully by get method, Hello {user}"


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

Get the required image, CSS, and HTML file for this project

static/img.jpg

static/style.css

body{
    color:orange;
}

templates/home.html

{% extends "layout.html" %}
{% block content %}
<image src="{{ url_for('static', filename='img.jpg') }}">
{% endblock %}

templates/layout.html

<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='style.css')}}">
        <title>Home </title>
    </head>
    <body>
     <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="/home">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/login">Login</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/logout">Logout</a>
      </li>
      
    </ul>
  </div>
</nav>
    <div class="container-fluid">
        {% block content %}
        
        {% endblock %}
    </div>
        
        https://code.jquery.com/jquery-3.5.1.slim.min.js
https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js
https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js
    </body>
</html>

templates/login.html

{% extends "layout.html" %}
{% block content %}

<form action="/submit" method="post">
    Username: <input type="text" name="nm" />
    <br><br>
    Password: <input type="password" name="pswd" />
    <br><br>
    <input type="submit" value="submit"/> 
</form>

{% endblock %}

templates/new.html

<html>
    <head>
        <title>This is my html file</title>
    </head>
    <body>
        <h2>Due to Corona Virus, there is lockdown in my locality....</h2>
    </body>
</html>

Conclusion:

This is the absolute Flask tutorial. In this tutorial, we simply learn how to get started with Flask, deal with routing, create a page, and so on. In the above video, you may noticed I have used Jupyter Notebook for writing code. This is not a good practice. For recording and for explaining purposes only, I chose Jupyter Notebook. You can try with other editors like Visual Studio or any other of your choice.

I hope this post is very helpful to you. If you have any questions, you can ask me in the comment section. I will back to you as soon as possible. Thanks.