Table of Contents
- Overview
- Prerequisites
- Setup
- Creating the Flask App
- Adding Database Functionality
- Creating CRUD Operations
- Implementing User Authentication
- Conclusion
Overview
In this tutorial, we will build a simple Content Management System (CMS) using Python and Flask. A CMS allows users to create, edit, and manage digital content, such as articles, blog posts, and web pages. By the end of this tutorial, you will have a working CMS with basic CRUD (Create, Read, Update, Delete) operations and user authentication.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming language concepts. Familiarity with Flask framework and web development fundamentals would be beneficial but not mandatory.
Setup
To get started, make sure you have the following prerequisites:
- Python installed on your machine.
- Flask installed. You can install Flask using the following command:
pip install flask
- A relational database management system (RDBMS) installed. For this tutorial, we will use SQLite, which is a lightweight, file-based database system.
Now that we have everything set up, let’s start building our Content Management System step by step.
Creating the Flask App
- Create a new directory for your project and navigate to it using the terminal.
mkdir cms cd cms
- Create a new Python file called
app.py
and open it in your preferred code editor.touch app.py
- Import the necessary modules:
from flask import Flask
- Create a new Flask application instance:
app = Flask(__name__)
- Add a basic route and a home page view:
@app.route('/') def home(): return "Welcome to the CMS!"
- Start the Flask development server:
if __name__ == '__main__': app.run(debug=True)
- Save the changes and run the Flask app:
python app.py
- Open your web browser and navigate to
http://localhost:5000
. You should see the message “Welcome to the CMS!” displayed on the page.
Adding Database Functionality
- Install the necessary packages for database integration:
pip install flask-sqlalchemy pip install flask-migrate
- Import the required modules in your
app.py
file:from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate
- Configure the database settings:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cms.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
- Create a database instance:
db = SQLAlchemy(app) migrate = Migrate(app, db)
- Create a
User
model and aPage
model to represent the database tables: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(128), nullable=False) class Page(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) author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) author = db.relationship('User', backref=db.backref('pages', lazy=True))
- Create the database migration files:
flask db init flask db migrate flask db upgrade
Creating CRUD Operations
- Add the necessary routes and views for CRUD operations in your
app.py
file:@app.route('/pages') def list_pages(): pages = Page.query.all() return render_template('pages.html', pages=pages) @app.route('/pages/new', methods=['GET', 'POST']) def create_page(): if request.method == 'POST': title = request.form['title'] content = request.form['content'] author_id = 1 # Example, replace with actual user ID page = Page(title=title, content=content, author_id=author_id) db.session.add(page) db.session.commit() return redirect(url_for('list_pages')) return render_template('create_page.html') @app.route('/pages/<int:page_id>', methods=['GET', 'POST']) def edit_page(page_id): page = Page.query.get(page_id) if request.method == 'POST': page.title = request.form['title'] page.content = request.form['content'] db.session.commit() return redirect(url_for('list_pages')) return render_template('edit_page.html', page=page) @app.route('/pages/<int:page_id>/delete', methods=['POST']) def delete_page(page_id): page = Page.query.get(page_id) db.session.delete(page) db.session.commit() return redirect(url_for('list_pages'))
-
Create the necessary HTML templates for the views using Jinja templating engine.
- Test the CRUD operations by navigating to the appropriate URLs in your browser and verifying the functionality.
Implementing User Authentication
- Install the necessary packages for user authentication:
pip install flask-login pip install flask-wtf
- Add the required modules to your
app.py
file:from flask_login import LoginManager, login_user, logout_user, login_required, current_user from flask_wtf import FlaskForm from werkzeug.security import generate_password_hash, check_password_hash from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Length
- Configure the login manager and forms:
app.config['SECRET_KEY'] = 'your-secret-key' login_manager = LoginManager(app) login_manager.login_view = 'login' class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=4, max=50)]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Log In')
- Create the user login view:
@app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and check_password_hash(user.password, form.password.data): login_user(user) return redirect(url_for('list_pages')) return render_template('login.html', form=form)
- Add the user logout functionality:
@app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('login'))
- Protect the routes that require authentication:
@login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) @login_manager.unauthorized_handler def unauthorized(): return redirect(url_for('login'))
Great! You have successfully implemented user authentication in your CMS.
Conclusion
In this tutorial, you have learned how to build a Content Management System using Python and Flask. You have created a basic Flask application, integrated a database, implemented CRUD operations, and added user authentication. This tutorial serves as a starting point for building more complex CMS features and can be expanded to meet your specific requirements. Happy coding!
I hope you find this tutorial helpful. If you have any questions or face any issues, please feel free to ask.
Frequently Asked Questions:
Q: Can I use a different database system instead of SQLite? A: Yes, you can use any RDBMS supported by SQLAlchemy by changing the database URI in the app configuration.
Q: How can I deploy this CMS to a production server? A: You can deploy the Flask app to any server that supports WSGI applications, such as Apache or Nginx with uWSGI.