Published on

Building a Simple Blog Website with Flask

Authors
  • avatar
    Name
    codebuff
    Twitter

Introduction

In this tutorial, we will walk through the steps to create a simple blog website using Flask, a lightweight web framework for Python. The blog will allow you to display posts written in Markdown, convert them to HTML, and render them on your site.

Setting Up the Project

First, you'll need to create a basic Flask project. Install Flask via pip if you haven't already. I recommend using virtualenv to manage your environment.

pip install Flask

Next, set up the following directory structure for your project:

/my-flask-blog
├── app.py
├── posts/
│   └── your-posts.md
├── templates/
│   ├── index.html
│   └── post.html
│   └── basic.html
└── static/
  • app.py: This is the main application file.
  • posts/: This folder will contain your blog posts in Markdown format.
  • templates/: This folder will contain your HTML templates.
  • static/: This folder can contain your static files like CSS, JavaScript, and images.

Writing the Flask Application

Here's a basic implementation of app.py:

from flask import Flask, render_template

The Flask application consists of several key components:

  1. Getting the List of Posts:

    • The get_post_list() function scans the posts folder, reads all Markdown files, and returns a list of available posts.
  2. Loading and Converting Markdown:

    • The load_post() function reads a Markdown file, converts it to HTML, and returns the rendered content.
  3. Previewing Posts:

    • The get_post_preview() function provides a short preview of each post by stripping HTML tags and truncating the text to a set length.
  4. Routing:

    • The / route displays a list of all posts with previews.
    • The /post/<filename> route displays the full content of a specific post.
  5. Error Handling:

    • The @app.errorhandler(404) decorator is used to define a custom 404 page.

Running the Application

To run the application, use the following command:

python app.py

The application will be accessible at http://localhost:5000. You can navigate to the homepage to see a list of blog posts and click on any post title to view the full content.

Running the Application inside a docker container

docker run -d -p 5000:5000 --name my-flask-blog-container my-flask-blog

GitHub Repository

For a complete reference and to see the full project structure, you can check out the GitHub repository for this Flask blog project:

Simple Flask Blog on GitHub

Feel free to clone, fork, or star the repository if you find it helpful. If you encounter any issues or have suggestions for improvements, please don't hesitate to open an issue or submit a pull request.

Conclusion

This basic Flask blog website is a great starting point for learning how to work with Flask, Markdown, and web templates. You can expand this project by adding features like user authentication, a database, or a WYSIWYG editor for creating posts.