简介
在本实验中,我们将逐步介绍如何使用Python中流行的Web框架Flask创建一个博客应用程序。这个应用程序将列出所有博客文章,允许登录用户创建文章,并让作者编辑或删除自己的文章。
注意:你需要自己创建代码文件并在环境中运行它。你可以在Web 5000上预览Flask服务状态。
This tutorial is from open-source community. Access the source code
💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版
在本实验中,我们将逐步介绍如何使用Python中流行的Web框架Flask创建一个博客应用程序。这个应用程序将列出所有博客文章,允许登录用户创建文章,并让作者编辑或删除自己的文章。
注意:你需要自己创建代码文件并在环境中运行它。你可以在Web 5000上预览Flask服务状态。
首先,我们将为我们的博客定义一个蓝图。蓝图是一种组织一组相关视图和其他代码的方式。
## flaskr/blog.py
from flask import Blueprint, flash, g, redirect, render_template, request, url_for
from werkzeug.exceptions import abort
from flaskr.auth import login_required
from flaskr.db import get_db
## 蓝图名为 'blog'。它在同一个文件中定义。
## 蓝图需要知道它在哪里定义,所以将 __name__ 作为第二个参数传递。
bp = Blueprint('blog', __name__)
接下来,我们会将蓝图注册到我们的应用程序中。
## flaskr/__init__.py
def create_app():
app =...
## 省略现有代码
## 使用 app.register_blueprint() 从工厂函数中导入并注册蓝图
from. import blog
app.register_blueprint(blog.bp)
app.add_url_rule('/', endpoint='index')
return app
现在,让我们创建一个索引视图来显示所有博客文章。我们将使用SQL JOIN
来在结果中包含来自 user
表的作者信息。
## flaskr/blog.py
@bp.route('/')
def index():
db = get_db()
posts = db.execute(
'SELECT p.id, title, body, created, author_id, username'
' FROM post p JOIN user u ON p.author_id = u.id'
' ORDER BY created DESC'
).fetchall()
return render_template('blog/index.html', posts=posts)
接下来,我们将创建一个视图,允许已登录用户创建新的博客文章。
## flaskr/blog.py
@bp.route('/create', methods=('GET', 'POST'))
@login_required
def create():
if request.method == 'POST':
title = request.form['title']
body = request.form['body']
error = None
if not title:
error = '标题是必填项。'
if error is not None:
flash(error)
else:
db = get_db()
db.execute(
'INSERT INTO post (title, body, author_id)'
' VALUES (?,?,?)',
(title, body, g.user['id'])
)
db.commit()
return redirect(url_for('blog.index'))
return render_template('blog/create.html')
我们将添加让作者更新自己文章的功能。为避免重复代码,我们将创建一个辅助函数来获取一篇文章并检查当前用户是否为作者。
## flaskr/blog.py
@bp.route('/<int:id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
post = get_post(id)
if request.method == 'POST':
title = request.form['title']
body = request.form['body']
error = None
if not title:
error = '标题是必填项。'
if error is not None:
flash(error)
else:
db = get_db()
db.execute(
'UPDATE post SET title =?, body =?'
' WHERE id =?',
(title, body, id)
)
db.commit()
return redirect(url_for('blog.index'))
return render_template('blog/update.html', post=post)
最后,我们将添加让作者删除自己文章的功能。
## flaskr/blog.py
@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(id):
get_post(id)
db = get_db()
db.execute('DELETE FROM post WHERE id =?', (id,))
db.commit()
return redirect(url_for('blog.index'))
恭喜你,你已经使用Flask创建了一个简单的博客应用程序!这个应用程序支持用户认证,并允许用户创建、编辑和删除他们自己的博客文章。