DEV Community

Cover image for A GUIDE TO THE CREATION OF A BLOG APPLICATION USING THE PYTHON FLASK FRAMEWORK
Opeyemi Olaleye
Opeyemi Olaleye

Posted on

A GUIDE TO THE CREATION OF A BLOG APPLICATION USING THE PYTHON FLASK FRAMEWORK

Introduction
Flask is a lightweight Python web framework that provides useful tools and features that make creating web applications in Python easier. It gives developers flexibility and is a more accessible framework for new developers since you can build a web application quickly using only a single Python file. Flask is also extensible and doesn’t force a particular directory structure or require complicated boilerplate code before getting started.

As part of this tutorial, we’ll use the Bootstrap toolkit to style our application so it is more visually appealing. Bootstrap will help us incorporate responsive web pages in our web application so that it also works well on mobile browsers without writing our own HTML, CSS, and JavaScript code to achieve these goals. The toolkit will allow us to focus on learning how Flask works.

Flask uses the Jinja template engine to dynamically build HTML pages using familiar Python concepts such as variables, loops, lists, and so on. We’ll use these templates as part of the project.

In this tutorial, we are going to build a small web blog using Flask and SQLite in Python 3. Users of the application can view all the posts in our database and click on the title of a post to view its contents with the ability to add a new post to the database and edit or delete an existing post.

Basic Requirements
To follow this guide, the following basics are required:

A local Python 3 programming environment, follow the tutorial for distribution in How To Install and Set Up a Local Programming Environment for Python 3 series for your local machine. In this tutorial we’ll call our project directory flask_blog.
An understanding of Python 3 concepts, such as data types, conditional statements, for loops, functions, and other such concepts. If you are not familiar with Python, check out How To Code in Python 3 series.

Installing Flask
In this step, you’ll activate your Python environment and install Flask using the pip package installer.

If you haven’t already activated your programming environment, make sure you’re in your project directory (flask_blog) and use the following command to activate the environment:

source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Once your programming environment is activated, your prompt will now have an venv prefix that may look as follows:

(venv) PS C:\Users\hp\Desktop\AltSchool\blog> 
Enter fullscreen mode Exit fullscreen mode

This prefix is an indication that the environment venv is currently active, which might have another name depending on how you named it during creation.

Note: You can use Git, a version control system, to effectively manage and track the development process for your project. To learn how to use Git, you might want to check out the Introduction to Git Installation Usage and Branches article.

If you are using Git, it is a good idea to ignore the newly created venv directory in your .gitignore file to avoid tracking files not related to the project.

Now we’ll install Python packages and isolate our project code away from the main Python system installation. We’ll do this using pip and python.

To install Flask, we'll run the following command:

(venv) PS C:\Users\hp\Desktop\AltSchool\blog> pip install flask
Enter fullscreen mode Exit fullscreen mode

Once the installation is complete, we'll run the following command to confirm the installation:

(venv) PS C:\Users\hp\Desktop\AltSchool\blog> python -c "import flask; print(flask.__version__)"
Enter fullscreen mode Exit fullscreen mode

We use the python command line interface with the option -c to execute Python code. Next we import the flask package with import flask; then print the Flask version, which is provided via the flask.version variable.

The output will be a version number similar to the following:

Output
1.1.2
Enter fullscreen mode Exit fullscreen mode

We’ve created the project folder, a virtual environment, and installed Flask. We’re now ready to move on to setting up our base application.

Creating a Base Application
Now that we have our programming environment set up, we’ll start using Flask. In this step, we’ll make a small web application inside a Python file and run it to start the server, which will display some information on the browser.

In our flask_blog directory, we'll open a file named run.py for editing, use VS code or any other favorite text editor:

(venv) PS C:\Users\hp\Desktop\AltSchool\blog> vs code run.py
Enter fullscreen mode Exit fullscreen mode

This run.py file will serve as a minimal example of how to handle HTTP requests. Inside it, you’ll import the Flask object, and create a function that returns an HTTP response. Write the following code inside run.py:

from myblog import app

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

When we go to the browser and type in http://localhost:5000/, we should have our welcome page.

Home Page
Our home page should show the latest posts added by users. Since Flask looks for template files inside the templates folder. So, we need to create the folder and under that folder, we should create home.html that looks like this:

{% extends "layout.html" %}
{{ super() }}
{% block content %}

    {% for post in posts %}
        <article class="media content-section">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="#">{{ post.author.username }}</a>
              <small class="text-muted">{{ post.date_posted }}</small>
            </div>
            <h2><a class="article-title" href="post/{{ post.id }}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
        </article>
    {% endfor %}
{% endblock content %}
Enter fullscreen mode Exit fullscreen mode

We can use the CSS language to style the application and make it more appealing using our own design. However, if one is not a web designer, or if not familiar with CSS, then we can use the Bootstrap toolkit, which provides easy-to-use components for styling our application. In this project, we’ll use Bootstrap.

You might have guessed that making another HTML template would mean repeating most of the HTML code we already wrote in the home.html template. We can avoid unnecessary code repetition with the help of a base template file, which all of our HTML files will inherit from. See Template Inheritance in Jinja for more information.

To make a base template, we'll create a file called layout.html inside our templates directory.

Afterwards, we type the following code in our layout.html template:

<!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">

    {% if title %}
        <title>Obsidian Blog - {{ title }}</title>
    {% else %}
        <title>Obsidian Blog</title>
    {% endif %}
</head>
<body>
    <header class="site-header">
      <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
        <div class="container">
          <a class="navbar-brand mr-4" href="/">Flask Blog</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
              <a class="nav-item nav-link" href="{{ url_for('home') }}">Home</a>
              <a class="nav-item nav-link" href="{{ url_for('about') }}">About</a>
            </div>
            <!-- Navbar Right Side -->
            <div class="navbar-nav">
              {% if current_user.is_authenticated %}
                <a class="nav-item nav-link" href="{{ url_for('new_post') }}">New Blog Post</a>
                <a class="nav-item nav-link" href="{{ url_for('account') }}">Account</a>
                <a class="nav-item nav-link" href="{{ url_for('logout') }}">Logout</a>
              {% else %}
                <a class="nav-item nav-link" href="{{ url_for('login') }}">Login</a>
                <a class="nav-item nav-link" href="{{ url_for('register') }}">Register</a>
              {% endif %}
            </div>
          </div>
        </div>
      </nav>
    </header>
    <main role="main" class="container">
      <div class="row">
        <div class="col-md-8">
          {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
              {% for category, message in messages %}
                <div class="alert alert-{{ category }}">
                  {{ message }}
                </div>
              {% endfor %}
            {% endif %}
          {% endwith %}
          {% block content %}{% endblock content%}
        </div>
        <div class="col-md-4">
          <div class="content-section">
            <h3>Our Sidebar</h3>
            <p class='text-muted'>You can put any information here you'd like.
              <ul class="list-group">
                <li class="list-group-item list-group-item-light">Latest Posts</li>
                <li class="list-group-item list-group-item-light">Announcements</li>
                <li class="list-group-item list-group-item-light">Calendars</li>
                <li class="list-group-item list-group-item-light">etc</li>
              </ul>
            </p>
          </div>
        </div>
      </div>
    </main>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Setting up the Database
In this step, we’ll set up a database to store data, that is, the blog posts for our application. We’ll also populate the database with a few example entries.

We’ll use an SQLite database file to store our data because the sqlite3 module, which we will use to interact with the database, is readily available in the standard Python library. For more information about SQLite, check out this tutorial.

First, because data in SQLite is stored in tables and columns, and since our data mainly consists of blog posts, we first need to create a table called posts with the necessary columns. We’ll create a .sql file that contains SQL commands to create the posts table with a few columns. We’ll then use this file to create the database.

Displaying All Posts
Now that you’ve set up your database, you can now modify the index() view function to display all the posts you have in your database.

We open the run.py file to make the following modifications:

(venv) PS C:\Users\hp\Desktop\AltSchool\blog> .\run.py
Enter fullscreen mode Exit fullscreen mode

For our first modification, we’ll import the sqlite3 module at the top of the file:

import sqlite3
from flask import Flask, render_template

. . .
Enter fullscreen mode Exit fullscreen mode

Next, you’ll create a function that creates a database connection and return it. Add it directly after the imports:

. . .
from flask import Flask, render_template

def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn

. . .
Enter fullscreen mode Exit fullscreen mode

Conclusion
This tutorial introduced essential concepts of the Flask Python framework. You learned how to make a small web application, run it in a development server, and allow the user to provide custom data via URL parameters and web forms. You also used the Jinja template engine to reuse HTML files and use logic in them. At the end of this tutorial, you now have a fully functioning web blog that interacts with an SQLite database to create, display, edit, and delete blog posts using the Python language and SQL queries. If you would like to learn more about working with Flask and SQLite check out this tutorial on How To Use One-to-Many Database Relationships with Flask and SQLite.

You can further develop this application by adding user authentication so that only registered users can create and modify blog posts, you may also add comments and tags for each blog post, and add file uploads to give users the ability to include images in the post. See the Flask documentation for more information.

Flask has many community-made Flask extensions. The following is a list of extensions you might consider using to make your development process easier:

  • Flask-Login: manages the user session and handles logging in and logging out and remembering logged-in users.
  • Flask-SQLAlchemy: simplifies using Flask with SQLAlchemy, a Python SQL toolkit and Object Relational Mapper for interacting with SQL databases.
  • Flask-Mail: helps with the task of sending email messages in your Flask application.

Top comments (0)