Python Flask Blog Application Tutorial

Written by

in

Welcome to our step‑by‑step Python Flask blog application tutorial! Whether you’re a beginner eager to launch your first web app or an experienced developer looking for a quick refresher, this guide will walk you through everything you need—from setting up the development environment to deploying a fully functional blog. By the end of this article, you’ll have a clean, scalable Flask blog that supports posts, comments, and user authentication, all while following best practices for security and SEO.

Why Choose Flask for a Blog?

Flask is a lightweight, micro‑framework that gives you the flexibility to build exactly what you need without the overhead of a full‑stack solution. Here are a few reasons why Flask shines for blog projects:

  • Simple and intuitive: Minimal boilerplate lets you focus on core features.
  • Extensible: A rich ecosystem of extensions (e.g., Flask‑SQLAlchemy, Flask‑Login) makes adding functionality straightforward.
  • SEO‑friendly: Full control over URLs, metadata, and template rendering helps you rank higher in search results.
  • Pythonic: Leverage Python’s readability and powerful libraries for data handling and testing.

Prerequisites

Before diving into code, make sure you have the following installed on your machine:

  1. Python 3.9+ (download from python.org)
  2. Virtualenv or venv for isolated environments
  3. Git (optional but recommended for version control)
  4. A code editor such as VS Code, PyCharm, or Sublime Text

Project Setup

1. Create a Virtual Environment

mkdir flask_blog_tutorial
cd flask_blog_tutorial
python -m venv venv
source venv/bin/activate   # On Windows use: venv\Scripts\activate

2. Install Flask and Essential Extensions

pip install Flask Flask‑SQLAlchemy Flask‑Migrate Flask‑Login Flask‑WTF email‑validator

3. Initialize the Project Structure

Organize your files for clarity and scalability:

flask_blog_tutorial/
│
├─ app/
│   ├─ __init__.py
│   ├─ models.py
│   ├─ routes.py
│   ├─ forms.py
│   └─ templates/
│       ├─ base.html
│       ├─ index.html
│       ├─ post.html
│       └─ login.html
│
├─ migrations/
├─ static/
│   └─ style.css
├─ config.py
└─ run.py

Configuring Flask and the Database

config.py

import os

class Config:
    SECRET_KEY = os.getenv('SECRET_KEY', 'you-will-never-guess')
    SQLALCHEMY_DATABASE_URI = os.getenv(
        'DATABASE_URL',
        'sqlite:///site.db'
    )
    SQLALCHEMY_TRACK_MODIFICATIONS = False

app/__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config

db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'login'   # endpoint name for @login_required redirects

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)

    from . import routes
    app.register_blueprint(routes.bp)

    return app

Defining the Data Models

Our blog will need three core models: User, Post, and Comment. They live in app/models.py.

from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from . import db, login

@login.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy=True)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(140), nullable=False)
    body = db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    comments = db.relationship('Comment', backref='post', lazy=True)

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

Creating Forms with Flask‑WTF

Forms handle user input safely and include built‑in CSRF protection.

from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from .models import User

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password',
                                     validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Sign Up')

    def validate_username(self, username):
        if User.query.filter_by(username=username.data).first():
            raise ValidationError('That username is already taken.')

    def validate_email(self, email):
        if User.query.filter_by(email=email.data).first():
            raise ValidationError('An account with this email already exists.')

class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Login')

class PostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired(), Length(max=140)])
    body = TextAreaField('Content', validators=[DataRequired()])
    submit = SubmitField('Publish')

Routing and View Functions

All routes are defined in app/routes.py. We’ll use a Flask Blueprint to keep the code modular.

from flask import Blueprint, render_template, flash, redirect, url_for, request
from flask_login import current_user, login_user, logout_user, login_required
from . import db
from .models import User, Post, Comment
from .forms import RegistrationForm, LoginForm, PostForm

bp = Blueprint('main', __name__)

@bp.route('/')
@bp.route('/index')
def index():
posts = Post.query.order_by(Post.timestamp.desc()).all()
return render_template('index.html', posts=posts)

@bp.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Your account has been created! You can now log in.', 'success')
return redirect(url_for('main.login'))
return render_template('register.html', form=form)

@bp.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.check_password(form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('main.index'))
else:
flash('Login failed. Check email and password.', 'danger')
return render_template('login.html', form=form)

@bp.route('/logout')
def logout():
logout_user()
return redirect(url_for('main.index'))

@bp.route('/post/new', methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, body=form.body.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been published!', 'success')
return redirect(url_for('main.index'))
return render_template('create_post.html', form=form)

@bp.route('/post/', methods=['GET', 'POST'])
def post_detail(post_id):
post = Post.query.get_or_404(post_id)
if request.method == 'POST' and current_user.is_authenticated:
comment_body = request.form.get('comment')
if comment_body:
comment = Comment(body=comment_body, post=post, user_id=current_user.id)
db.session.add(comment)
db.session.commit()
flash('Comment added.', 'success')
return redirect(url_for('main.post_detail', post_id=post.id))
comments = Comment.query.filter_by(post_id=post.id

Comments

Leave a Reply

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