Python-based project to build a customizable blogging website using Flask and SQLite !
Abstract:
# app/# ├── __init__.py
# ├── models.py
# ├── routes.py
# ├── templates/
# │ ├── base.html
# │ ├── index.html
# │ ├── post.html
# │ └── ...
# ├── static/
# │ ├── style.css# │ └── ...
# 1. Install Flask and other dependencies
# pip install Flask Flask-SQLAlchemy
# 2. Create the Flask app and configure it (app/__init__.py)
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' db = SQLAlchemy(app) # 3. Create the database models (app/models.py)
class Post(db.Model): id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) # 4. Create the routes and views (app/routes.py) from flask import render_template, redirect, url_for
from .models import Post
@app.route('/')
def index():
posts = Post.query.all() return render_template('index.html', posts=posts)
@app.route('/post/<int:post_id>') def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', post=post) # ... (Add routes for creating, editing, deleting posts)
# 5. Create templates (app/templates/)
# base.html (layout)
# index.html (list of posts)
# post.html (single post)
# ...
# 6. Run the app
if __name__ == '__main__':
db.create_all() # Create the database tables
app.run(debug=True)
- User Authentication: Allow users to create accounts, login, and manage their posts.
- Custom Themes: Implement a way for users to select from different themes or customize the look of their blog.
- Rich Text Editor: Use a rich text editor (e.g., CKEditor, TinyMCE) to make creating posts easier.
- Categories and Tags: Allow users to categorize and tag their posts for better organization.
- Commenting System: Enable readers to leave comments on posts.
- Pagination: Implement pagination to handle large numbers of posts.
- Search: Add search functionality to help users find specific posts.
- Social Sharing: Integrate social media buttons for easy sharing.
- SEO: Optimize the website for search engines.
- Fill in the Missing Routes: Create routes and views for creating, editing, and deleting posts.
- Implement User Authentication: Add user registration, login, and logout functionality.
- Customize Templates: Design the look and feel of your blog using HTML, CSS, and JavaScript.
- Add Custom Features: Implement any additional features you desire.
Here’s a complete Python-based project to build a customizable blogging website using Flask (a lightweight web framework for Python) and SQLite (a database). This project will include essential features like user authentication, creating posts, editing posts, deleting posts, and displaying blog posts dynamically.
Project Setup
-
Install Dependencies: Install Flask and its extensions using
pip
:pip install flask flask_sqlalchemy flask_bcrypt
-
Project Structure:
blogging_website/ ├── static/ │ └── style.css ├── templates/ │ ├── base.html │ ├── home.html │ ├── login.html │ ├── register.html │ ├── create_post.html │ ├── post.html │ └── edit_post.html ├── app.py └── models.py
Code Implementation
1. app.py
(Main Application File)
from flask import Flask, render_template, redirect, url_for, request, flash, session
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from datetime import datetime
app = Flask(__name__)
app.secret_key = "your_secret_key"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
# Import models
from models import User, Post
@app.route('/')
def home():
posts = Post.query.order_by(Post.date_created.desc()).all()
return render_template('home.html', posts=posts)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = bcrypt.generate_password_hash(request.form['password']).decode('utf-8')
if User.query.filter_by(username=username).first():
flash('Username already exists!', 'danger')
return redirect(url_for('register'))
new_user = User(username=username, password=password)
db.session.add(new_user)
db.session.commit()
flash('Account created successfully!', 'success')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
if user and bcrypt.check_password_hash(user.password, password):
session['user_id'] = user.id
session['username'] = user.username
flash('Logged in successfully!', 'success')
return redirect(url_for('home'))
flash('Invalid credentials!', 'danger')
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
flash('Logged out successfully!', 'success')
return redirect(url_for('home'))
@app.route('/create', methods=['GET', 'POST'])
def create_post():
if 'user_id' not in session:
flash('You need to log in to create a post!', 'danger')
return redirect(url_for('login'))
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
post = Post(title=title, content=content, author_id=session['user_id'])
db.session.add(post)
db.session.commit()
flash('Post created successfully!', 'success')
return redirect(url_for('home'))
return render_template('create_post.html')
@app.route('/post/<int:post_id>')
def view_post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', post=post)
@app.route('/post/<int:post_id>/edit', methods=['GET', 'POST'])
def edit_post(post_id):
post = Post.query.get_or_404(post_id)
if 'user_id' not in session or session['user_id'] != post.author_id:
flash('Unauthorized access!', 'danger')
return redirect(url_for('home'))
if request.method == 'POST':
post.title = request.form['title']
post.content = request.form['content']
db.session.commit()
flash('Post updated successfully!', 'success')
return redirect(url_for('view_post', post_id=post_id))
return render_template('edit_post.html', post=post)
@app.route('/post/<int:post_id>/delete', methods=['POST'])
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if 'user_id' not in session or session['user_id'] != post.author_id:
flash('Unauthorized access!', 'danger')
return redirect(url_for('home'))
db.session.delete(post)
db.session.commit()
flash('Post deleted successfully!', 'success')
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)
2. models.py
(Database Models)
from app import db
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
3. Templates
base.html
: Base layout for other templates.home.html
: Display all blog posts.login.html
,register.html
: Authentication forms.create_post.html
,edit_post.html
: Post creation and editing.post.html
: Single post view.
4. Static Files
Create a static/style.css
file for styling.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background: #f4f4f4;
}
.container {
width: 80%;
margin: auto;
overflow: hidden;
}
header {
background: #333;
color: #fff;
padding: 10px 0;
text-align: center;
}
header a {
color: #fff;
text-decoration: none;
margin: 0 15px;
}
How to Run
-
Initialize the database:
python >>> from app import db >>> db.create_all()
-
Start the Flask development server:
python app.py
-
Open your browser and navigate to
http://127.0.0.1:5000
.
Enhancements to Consider
- Add tags/categories to posts.
- Implement image uploads.
- Add pagination to the homepage.
- Use a frontend framework like Bootstrap for better styling.
Conclusions:
Let me know if you'd like help with additional features!
Comments
Post a Comment
"Thank you for seeking advice on your career journey! Our team is dedicated to providing personalized guidance on education and success. Please share your specific questions or concerns, and we'll assist you in navigating the path to a fulfilling and successful career."