Building a Blog Website Using Flask-Python

Building a Blog Website Using Flask-Python

Introduction to flask

Flask is a lightweight Python web framework that provides useful tools and features for creating web applications. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

In this article, we will highlight how to use Flask to build a blog application which can perform the CRUD operations: creating, reading, updating, and deleting posts

Flask is easy to get started with, and it is a great choice for small projects or prototypes.

Steps involved in building a blog application using Flask

Here is a high-level outline of the steps we will need to follow to build a blog application using Python-Flask with SQLAlchemy:

  1. Set up a development environment: You'll need to install Python and Flask on your computer, as well as any other dependencies such as SQLAlchemy.

  2. Create a new Flask project: You can do this by creating a new directory for your project and creating an app.py file, which will contain the code for your Flask app.

  3. Define your database model: You'll need to decide what kind of data your blog will store (e.g. posts, comments, users) and how it will be structured. You can use SQLAlchemy to define your model by creating classes that correspond to the tables in your database.

  4. Set up your database: You'll need to create a database to store your data. If you're using SQLAlchemy, you can use its create_all function to create the necessary tables in your database.

  5. Write your Flask views: A view is a Python function that will be called when a user visits a particular URL on your site. You'll need to write a view function for each page on your blog, such as the homepage, individual post pages, and the page for creating new posts.

  6. Set up URL routes: You'll need to define the URLs for your site and map them to the appropriate view functions. You can do this using the @app.route decorator in Flask.

  7. Test your app: You can use Flask's built-in development server to test your app locally. Make sure to test all of the different views and functionality to ensure that everything is working as expected.

  8. Deploy your app: Once you're happy with your app, you'll need to deploy it so that it can be accessed by others. There are many ways to do this, but some popular options include using a platform-as-a-service provider like Heroku or deploying to a virtual private server.

Now let's get deeper into the details

How to install Flask

To set up a development environment for a Python-Flask project, you'll need to follow these steps:

  1. Install Python: You can download the latest version of Python from the official Python website (https://www.python.org/downloads/). Make sure to choose the correct version for your operating system and follow the prompts to install it.

  2. Install Flask: Once you have Python installed, you can use the pip package manager to install Flask. Open a terminal window and run the following command:

     pip install flask (for windows)
     pip3 install flask (for Linux and Mac)
    
  3. Install any other dependencies: for the project, other requires i.e. other libraries or dependencies, you can install them using pip as well. For example, to install SQLAlchemy, you would run the following command:

      pip install sqlalchemy (for windows)
      pip3 install sqlalchemy (for Linux and Mac)
    
  4. Create a new project directory: Create a new directory for your project and navigate to it using the terminal. This will be the root directory for your project.

How to set up a flask app for a project

To create a new Flask project, follow these steps:

  1. Create a new directory for your project: Open a terminal window and navigate to the location where you want to create your project. Run the following command to create a new directory for your project:
mkdir MyBlogApp

Replace "MyBlogApp" with the desired name for your project directory.

2. Navigate to the new directory: Change into the new directory by running the following command:

cd MyBlogApp

3. Create a virtual environment: It's a good idea to create a virtual environment for your project to isolate it from the rest of your system. To do this, you can use the venv module that comes with Python. In your terminal, run the following command to create a new virtual environment:

python -m venv env

This will create a new directory called "env" in your project root. To activate the virtual environment, run the following command:

source env/bin/activate

4. Create a requirements.txt file: It's a good practice to create a requirements.txt file that lists all of your project's libraries and dependencies. This makes it easy to install all of the necessary packages when you deploy your app or share it with others. To create a requirements.txt file, run the following command in your terminal:

pip freeze > requirements.txt

This will create a requirements.txt file in your project root that lists all of the packages that are currently installed in your virtual environment.

That's it! You should now have a development environment set up for your Python-Flask project. You can start working on your project by creating an app.py file in your project root and adding your Flask code to it.

5. Create a new file called app.py: You can create a new file using a text editor or by running the following command in your terminal:

touch app.py

This will create an empty app.py file in your project directory.

6. Add the following code to the app.py file to create a basic Flask app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

if name == '__main__':
    app.run(debug=true)

This code creates a new Flask app and defines a single route at the root URL (/) that returns the string "Hello, World!"

7. Run the app: You can run the app by executing the app.py file. In your terminal, run the following command:

python app.py (for windows) or 
python3 app.py (for mac and Linux)

This will start the Flask development server, and your app will be available at localhost:5000. You should see the "Hello, World!" message when you visit this URL in your web browser.

That's it! You've successfully created a new Flask project. You can now start building out your blog site by defining your database model, writing your views, and setting up your URL routes.

Creating database models

To create a database model for a blog site using SQLAlchemy, you'll need to define the following classes:

  1. Posts: This class will represent the posts table in your database and will contain fields such as the title, content, and author of each post. For example:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Posts(Base):

    tablename = 'posts'

    id = Column(Integer, primary_key=True)

    title = Column(String)

    content = Column(String)

    author = Column(String)

2. Comments: This class will represent the comments table in your database and will contain fields such as the content, author, and post ID of each comment. For example:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Comments(Base):

    tablename = 'comments'

    id = Column(Integer, primary_key=True)

    content = Column(String)

    author = Column(String)

    post_id = Column(Integer)

3. Users: This class will represent the users' table in your database and will contain fields such as the username and password of each user. For example:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    username = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    date_created = db.Column(db.DateTime(timezone=True),           default=func.now())
    posts = db.relationship('Post', backref='user', passive_deletes=True)
    comments = db.relationship('Comment', backref='user', passive_deletes=True)
    likes = db.relationship('Like', backref='user', passive_deletes=True)

These are just examples, and you can customize the fields and data types to suit your needs. Once you've defined your database model, you can use SQLAlchemy's create_all function to create the necessary tables in your database.

from flask_sqlalchemy import SQLAlchemy


app.config ["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + \
 os.path.join(base_dir, 'blog.db')
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False 

db = SQLAlchemy(app)
db.init_app(app)



@app.before_first_request
def create_tables():
    db.create_all()

This will create the Posts, Comments, and Users tables in a SQL database called "blog.db." You can use a different database engine by specifying a different connection string.

Creating Flask views

To create Flask views for a blog site, you'll need to do the following:

  1. Import the necessary modules: At the top of your app.py file, add the following lines to import the required modules:
from flask import render_template, request, redirect, url_for
from models import session, Posts, Comments, Users

Replace "models" with the name of the module that contains your database model classes (e.g., modules, databases, etc.).

2. Define the view functions: View functions are Python functions that are called when a user visits a particular URL on your site. You can define a view function using the @app.route decorator. For example:




@app.route('/')
def index():
    posts = Post.query.all()

    context = {
        'posts':posts
    }
    return render_template("index.html",**context )

This view function will retrieve all of the posts from the database and render the index.html template, passing in the posts variable.

Here are some other view functions you might want to define for your blog site:

  • base: This function could render the base template for your site, which could include the navigation menu and footer.

  • register: This function could handle user registration by adding a new user to the users table and logging the user in.

  • login: This function could handle user login by authenticating the user and setting the appropriate session variables.

  • edit: This function could handle the editing of posts or comments by updating the relevant entries in the database.

  • deleting: This function could handle deleting a particular user, posts or comments

3. Create the templates: For each view function, you'll need to create a corresponding template file in the templates directory. The templates can use the Jinja2 template language to insert dynamic content into the HTML. For example, the index.html template for the index view function could look like this:

<!-- templates/index.html -->
{% extends 'base.html' %}

{% block content %}

    {% for post in posts %}

        <h2>{{ post.title }}</h2>

        <p>{{ post.content }}</p>

        <p>By {{ post.author }}</p>

    {% endfor %}

{% endblock %}

This template extends the base.html template and defines a content block that iterates over the posts variable and displays the title, content, and author of each post.

That's it! You should now have a basic set of views for your blog site. You can customize the views and templates to suit your needs and add additional functionality as needed.

Authentication

To build an authentication system for a blog application using Flask and Python, you will need to do the following:

  1. REGISTER:
  • Create a route for the registration page and a template for the registration form.

  • When the form is submitted, validate the form data (e.g. ensure that the username is unique and the password meets certain criteria).

  • If the form data is valid, hash the password and store the username and hashed password in a database (e.g. using SQLAlchemy).

2. LOGIN:

  • Create a route for the login page and a template for the login form.

  • When the form is submitted, look up the user's hashed password in the database and use a password hashing function to check if the provided password matches the hashed password in the database.

  • If the password matches, log the user in by creating a session for the user.

3. LOG OUT:

  • Create a route for logging out.

  • Destroy the user's session when they log out.

4. UPDATE:

  • Create a route for the account settings page and a template for the account settings form.

  • Allow users to update their account information (e.g. password, email address).

  • Validate the new information and update the database with the new information.

5. DELETE:

  • Create a route for deleting the account.

  • Remove the user's information from the database.

Here is some sample code for the registration and login routes using Flask and SQLAlchemy:

from flask import Flask, render_template, request, session, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = '<your database URI>'

db = SQLAlchemy(app)


# create a model for storing user information

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    username = db.Column(db.String(80), unique=True, nullable=False)

    password_hash = db.Column(db.String(128), nullable=False)





@auth.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form.get("email")
        password = request.form.get("password")

        user = User.query.filter_by(email=email).first()
        if user:
            if check_password_hash(user.password, password):
                flash("Logged in!", category='success')
                login_user(user, remember=True)
                return redirect(url_for('views.home'))
            else:
                flash('Password is incorrect.', category='error')
        else:
            flash('Email does not exist.', category='error')

    return render_template("template/login.html", user=current_user)


@auth.route("/sign-up", methods=['GET', 'POST'])
def sign_up():
    if request.method == 'POST':
        email = request.form.get("email")
        username = request.form.get("username")
        password1 = request.form.get("password1")
        password2 = request.form.get("password2")

        email_exists = User.query.filter_by(email=email).first()
        username_exists = User.query.filter_by(username=username).first()

        if email_exists:
            flash('Email is already in use.', category='error')
        elif username_exists:
            flash('Username is already in use.', category='error')
        elif password1 != password2:
            flash('Password don\'t match!', category='error')
        elif len(username) < 2:
            flash('Username is too short.', category='error')
        elif len(password1) < 6:
            flash('Password is too short.', category='error')
        elif len(email) < 4:
            flash("Email is invalid.", category='error')
        else:
            new_user = User(email=email, username=username, password=generate_password_hash(
                password1, method='sha256'))
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user, remember=True)
            flash('User created!')
            return redirect(url_for('auth.login'))

    return render_template("signup.html", user=current_user)


@auth.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for("views.home"))

Thank you for taking the time to read this article. I hope it has been useful to you.

Below is the link to the repository of the blog website:

https://github.com/SuaveDeveloper/-SuaveDeveloper-AltSchool_BlogPost_Project.git