How to Add a Favicon in Flask

how to add a favicon in flask

Introduction

Install modules

To begin we will first need to install Flask on our computer. To do so open your terminal and run the command below.

pip3 install Flask

File structure

Let’s create a folder called favicon which will contain our project. Inside the favicon folder create a folder called templates and insert a file called index.html. Now inside the favicon folder create a folder called static and add the icon you intend to use for your project as a png or ico format.

Import modules

Now let’s create a file called app.py inside the favicon folder and import the following modules as shown below.

from flask import Flask, render_template

Initialize our application

Next, we need to initialize our application, to do so let’s add the code below


app = Flask(__name__)

Create our main view

Now let’s create a basic view to render a basic template with a favicon.

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

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

Create a basic template

Now let’s create a basic template, inside the index.html add the code below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Website</title>
    <link rel="shortcut icon" href="../static/elephant.png">
  </head>
  <body>
    <main>
        <h1>Welcome to how to make a favicon on flask</h1>  
    </main>
  </body>
</html>

Run

Now let’s start our application, to do so open your terminal and run the command below.

python3 app.py

Results

After running the command above your application should be available at the address [ http://127.0.0.1:5000 ]. Here is our favicon displayed at the top left of the browser as shown below.

There you have it, Thanks for reading. Happy Coding.

Leave a Comment

Your email address will not be published. Required fields are marked *