共计 3948 个字符,预计需要花费 10 分钟才能阅读完成。
一个简单的 Flask 博客系统的开发过程。
步骤 1:安装 Flask
首先,我们需要安装 Flask。可以使用 pip 命令进行安装:
pip install flask
步骤 2:创建 Flask 应用
在你的代码文件夹中,创建一个名为 app.py 的文件,并在其中编写以下代码:
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
这段代码会创建一个 Flask 应用实例,并在本地服务器上启动应用。
步骤 3:创建主页路由
在 app.py 文件中添加一个路由,用于显示网站的主页:
@app.route('/')defindex():
return'Hello, world!'
这个路由将返回一个简单的“Hello, world!”字符串,当用户访问网站主页时将会显示出来。
步骤 4:创建博客文章路由
接下来,我们将添加一个路由,用于显示所有博客文章的列表,并提供一个界面,使用户能够添加新的博客文章。
@app.route('/posts')defposts():
return'List of all blog posts'@app.route('/posts/new')defnew_post():
return'Form to create a new blog post'
这里我们定义了两个路由。第一个 /posts 路由将返回所有博客文章的列表,而第二个 /posts/new 路由则会提供一个表单,允许用户创建一个新的博客文章。
步骤 5:渲染 HTML 模板
现在,我们需要为每个路由创建一个 HTML 模板。创建一个名为 templates 的文件夹,并在其中添加两个模板文件:index.html 和 new_post.html。代码如下:
index.html
My Blog
Welcome to my blog!
All Posts
New Post
new_post.html
New Blog Post
Create a new blog post
Title:
Content:
现在我们需要在路由中使用这些模板。更改 app.py 中的路由代码如下:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')defindex():
return render_template('index.html')
@app.route('/posts')defposts():
return render_template('posts.html')
@app.route('/posts/new')
步骤 7:创建博客文章页面
现在我们已经能够创建和更新博客文章了,我们需要添加一个页面来显示博客文章的详细信息。我们将在这个页面中显示文章的标题、作者、日期和内容。
在 app.py 文件中添加以下代码:
@app.route('/post/')
def post(post_id):
post = Post.query.filter_by(id=post_id).one()
return render_template('post.html', post=post)
这个函数将获取给定 post_id 的博客文章,并将其传递给 post.html 模板进行渲染。
在 templates 文件夹中创建一个名为 post.html 的文件,并添加以下代码:
{% extends 'base.html' %}
{% block content %}
{{post.title}}
By {{post.author}} on {{post.date.strftime('%Y-%m-%d') }}
{{post.content}}
{% endblock %}
这个模板将渲染博客文章的标题、作者、日期和内容。
步骤 8:创建博客首页
现在我们已经能够创建和更新博客文章,并能够显示单篇文章的详细信息,我们需要添加一个博客首页来显示所有文章的列表。我们将在这个页面中显示文章的标题、作者、日期和一部分内容。
在 app.py 文件中添加以下代码:
@app.route('/')
def index():
posts = Post.query.order_by(Post.date.desc()).all()
return render_template('index.html', posts=posts)
这个函数将获取所有博客文章,并将它们按照日期的倒序进行排序,然后将它们传递给 index.html 模板进行渲染。
在 templates 文件夹中创建一个名为 index.html 的文件,并添加以下代码:
{% extends 'base.html' %}
{% block content %}
{% for post in posts %}
{% endfor %}
{% endblock %}
这个模板将渲染所有博客文章的标题、日期和一部分内容,并为每篇文章创建一个链接,指向文章的详细信息页面。
步骤 9:添加样式
现在我们已经创建了博客系统的主要功能,我们需要添加一些样式来让它看起来更好看。我们将使用 Bootstrap 框架来添加样式。
在 static 文件夹中创建一个名为 css 的文件夹,在其中创建一个名为 main.css 的文件,并添加以下代码:
body {font-family: Arial, sans-serif;}
.post {margin-bottom: 30px;}
.post h2 {margin-bottom: 5px;}
.post .date {
color: #999;
margin-bottom: 5px;
}
.post .content {
margin-top: 10px;
步骤 10:在博客首页添加分页功能
我们需要在首页上显示多篇文章,所以需要为我们的博客系统添加分页功能。
在 app/main/views.py 中添加以下代码:
@main.route('/')
def index():
page = request.args.get('page', 1, type=int)
pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
return render_template('index.html', posts=posts, pagination=pagination)
在 app/templates/index.html 中修改以下代码:
{% extends 'base.html' %}
{% block content %}
{% include 'sidebar.html' %}
{% endblock %}
我们将首页的文章列表改成了动态生成的,每页显示 POSTS_PER_PAGE 篇文章,我们还添加了一个分页链接。
现在我们需要设置每页显示的文章数量,在 config.py 中添加以下配置:
class Config:
# ...
POSTS_PER_PAGE = 10
步骤 11:添加文章分类和标签功能
我们需要为文章添加分类和标签,这样我们的读者就可以通过分类或标签找到他们感兴趣的文章。
首先在 app/models.py 中添加 Category 和 Tag 模型:
class Category(db.Model):
__tablename__ = 'categories'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
def __repr__(self):
return '' % self.name
class Tag(db.Model):
__tablename__ = 'tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
def __repr__(self):
return '' % self.name
我们还需要为 Post 模型添加外键,使得文章可以关联到分类和标签:
class Post(db.Model):
__tablename__ = 'posts'# ...
category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
tag_id = db.Column(db.Integer, db.ForeignKey('tags.id'))
接下来在 app/main/forms.py 中添加以下表单:
class PostForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
body = TextAreaField('Body', validators=[DataRequired()])
category = SelectField('Category', coerce=int, default=1)
原文地址: Python Flask 从零开始开发博客网站