In this tutorial, we will walk you through the process of creating a simple blog using Python and Flask. Flask is a lightweight web framework for Python that is easy to learn and use.
Table of Contents
- What Is Flask?
- Creating the Flask App
What Is Flask?
Python is used to create the Flask web application framework. It is categorized as a microframework since it doesn’t need any specific libraries or tools. It lacks any form validation, database abstraction layer, or other components where common functions are provided by pre-existing third-party libraries. On the other hand, Flask allows extensions to provide functionality to the application as though it were Flask native.
Here are some of the features of Flask:
- Lightweight and easy to learn
- Flexible and extensible
- Supports multiple templating engines
- Built-in development server
- Large and active community
Before you begin, you will need to have the following installed on your computer:
- Python 3
Creating the Flask App
Step 1: Setting Up Everything
- Create a new directory for your blog project.
- Open a terminal window and navigate to the project directory.
- Create a virtual environment for your project using the following command:
python3 -m venv venv
4. Activate the virtual environment using the following command:
5. Install the Flask framework using the following command:
pip install Flask
6. Create a new file named
Step 2: Defining the Blog Post Model
First, we’ll establish a model for our blog entries. The title, content, and author of each blog post will all be represented by this model.
1. Creating a Flask App
from flask import Flask app = Flask(__name__)
This code creates a new Flask application instance. The
Flask(__name__) constructor takes the name of the current module as its argument. This is used to identify the application when running multiple applications on the same server.
2. Defining the Blog Post Model
class BlogPost: def __init__(self, title, content, author): self.title = title self.content = content self.author = author
This code defines a class called
BlogPost. This class represents a blog post, and it has three attributes:
__init__ method is the constructor for the class, and it is used to initialize the attributes of a new
3. Creating a Database
import sqlite3 conn = sqlite3.connect('blog.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS blog_posts (title text, content text, author text)''') conn.commit() conn.close()
This code creates a new database named
blog.db. If the database already exists, the code will simply connect to it. The code then creates a cursor object, which is used to execute SQL statements against the database. The
CREATE TABLE statement creates a new table named
blog_posts. The table has three columns:
conn.commit() statement commits the changes to the database, and the
conn.close() statement closes the connection to the database.
4. Adding Blog Posts
@app.route('/add-post', methods=['GET', 'POST']) def add_post(): if request.method == 'POST': title = request.form['title'] content = request.form['content'] author = request.form['author'] new_post = BlogPost(title, content, author) conn = sqlite3.connect('blog.db') c = conn.cursor() c.execute('INSERT INTO blog_posts VALUES (?,?,?)', (title, content, author)) conn.commit() conn.close() return redirect('/') else: return render_template('add_post.html')
This code defines a route called
add_post. This route is responsible for handling requests to add new blog posts. The
request.method property is used to determine whether the request is a GET or POST request. If the request is a GET request, the code renders a template called
add_post.html. If the request is a POST request, the code extracts the title, content, and author from the request form. It then creates a new
BlogPost object and inserts it into the
blog_posts table. The
redirect() function is used to redirect the user back to the homepage of the blog.
5. Displaying Blog Posts
@app.route('/') def index(): conn = sqlite3.connect('blog.db') c = conn.cursor() c.execute('SELECT * FROM blog_posts') blog_posts = c.fetchall() conn.close() return render_template('index.html', blog_posts=blog_posts)
This code defines a route called
index. This route is responsible for handling requests to the homepage of the blog. The code connects to the database and retrieves all of the blog posts from the
blog_posts table. It then renders a template called
index.html and passes the list of blog posts to the template as a context variable.
6. Running the App
This command runs the Flask application. The application will listen for requests on port 5000 by default. You can access the application at http://localhost:5000.
This will start the app and run it on your local machine. You can then access the app at http://localhost:5000.
This is really a straightforward illustration of how to build a blog using Python and Flask. You could add a lot more features to your blog, such categories, comments, and user authentication.
Users might register for accounts and access your blog by logging in with user authentication. They would be able to write their own blog entries and leave comments on existing ones thanks to this. Users could interact with the blog post author and each other by leaving comments. You might divide up your blog content into distinct topics by using categories. Users would find it simpler to locate the blog posts that pique their interest as a result.
You can make an interesting and educational blog with a little imagination and work. With the robust and adaptable Flask framework, you may build a blog that suits your needs.