使用Python和Flask构建简单的博客后端
博客是一种常见的Web应用,用于个人或机构发布文章和内容。本文将介绍如何使用Python和Flask框架来构建一个简单的博客后端。我们将涵盖路由、模板、数据存储和身份验证等方面。
一、Python:编程语言
Python是一种流行的高级编程语言,以其易读性和简洁的语法而著称。Python具有强大的功能,适用于各种编程任务,包括Web开发、数据分析、人工智能等。
二、Flask:Web开发框架
Flask是一个轻量级的Web开发框架,基于Python。Flask提供了简单的路由、模板和数据存储等功能,易于上手和扩展。
安装Flask:
```
pip install Flask
```
创建一个新的Flask应用:
```python from flask import Flask, render_template, request, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.sqlite3' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) login_manager = LoginManager(app) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), unique=True, nullable=False) password = db.Column(db.String(100), nullable=False) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) @app.route('/') @login_required def index(): posts = db.session.query(Post).order_by(Post.created_at.desc()).all() return render_template('index.html', posts=posts) @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') new_user = User(username=username, password=password) db.session.add(new_user) db.session.commit() 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.get('username') password = request.form.get('password') user = User.query.filter_by(username=username, password=password).first() if user: login_user(user) return redirect(url_for('index')) else: flash('用户名或密码错误') return render_template('login.html') @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('login')) @app.route('/post/<int:post_id>') @login_required def post(post_id): post = db.session.query(Post).get_or_404(post_id) return render_template('post.html', post=post) @app.route('/create_post', methods=['GET', 'POST']) @login_required def create_post(): if request.method == 'POST': title = request.form.get('title') content = request.form.get('content') new_post = Post(title=title, content=content, author=current_user) db.session.add(new_post) db.session.commit() return redirect(url_for('index')) return render_template('create_post.html') @app.route('/delete_post/<int:post_id>')