专项练习30
发布人:shili8
发布时间:2025-01-18 07:37
阅读次数:0
**专项练习30: 构建一个简单的博客系统**
在这个专项练习中,我们将构建一个简单的博客系统,包括用户注册、登录、文章发布、评论等功能。我们将使用 Python 和 Flask 框架来实现这个系统。
### 环境准备首先,我们需要安装必要的依赖包:
bashpip install flask flask_sqlalchemy
###项目结构我们的项目结构如下:
markdownblog_system/ app.pymodels.pyforms.pytemplates/ base.htmlindex.htmlregister.htmllogin.htmlarticle.htmlcomment.htmlstatic/ css/ style.cssjs/ script.jsrequirements.txtREADME.md
### 模型定义我们首先定义我们的模型:
# models.pyfrom flask_sqlalchemy import SQLAlchemydb = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(128), nullable=False) class Article(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) comments = db.relationship('Comment', backref='article', lazy=True) class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.String(200), nullable=False) article_id = db.Column(db.Integer, db.ForeignKey('article.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
### 表单定义我们定义我们的表单:
# forms.pyfrom flask_wtf import FlaskFormfrom wtforms import StringField, PasswordField, SubmitFieldfrom wtforms.validators import DataRequired, Email, EqualToclass RegisterForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Register') class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Login')
### 路由定义我们定义我们的路由:
# app.pyfrom flask import Flask, render_template, redirect, url_for, flashfrom forms import RegisterForm, LoginFormfrom models import User, Article, Commentapp = Flask(__name__) app.config['SECRET_KEY'] = 'secret_key' db.init_app(app) @app.route('/') def index(): return render_template('index.html') @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() flash('You have been registered successfully!', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form) @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 user.password == form.password.data: flash('You have been logged in successfully!', 'success') return redirect(url_for('index')) return render_template('login.html', title='Login', form=form) @app.route('/article/<int:article_id>') def article(article_id): article = Article.query.get_or_404(article_id) comments = Comment.query.filter_by(article_id=article_id).all() return render_template('article.html', title=article.title, article=article, comments=comments) @app.route('/comment/<int:article_id>', methods=['POST']) def comment(article_id): content = request.form['content'] user_id = current_user.id comment = Comment(content=content, article_id=article_id, user_id=user_id) db.session.add(comment) db.session.commit() return redirect(url_for('article', article_id=article_id)) if __name__ == '__main__': app.run(debug=True)
### 总结在这个专项练习中,我们构建了一个简单的博客系统,包括用户注册、登录、文章发布、评论等功能。我们使用 Python 和 Flask 框架来实现这个系统。