使用 Flask 构建简易的博客系统:分步指南
liebian365 2024-11-13 13:24 20 浏览 0 评论
Flask 是一个轻量级且灵活的 Python Web 框架,是构建 Web 应用程序(包括博客)的绝佳选择。在本指南中,我们将介绍使用 Flask 创建简单博客的过程。我们将介绍设置环境、创建路由、处理用户输入和显示帖子等。让我们开始吧!
步骤 1:设置环境
首先,让我们设置一个虚拟环境并安装 Flask。
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate
# Install Flask
pip install Flask
步骤 2:创建 Flask 应用程序
接下来,我们将创建一个基本的 Flask 应用程序。
# app.py
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# In-memory storage for blog posts
posts = []
@app.route('/')
def index():
return render_template('index.html', posts=posts)
@app.route('/new', methods=['GET', 'POST'])
def new_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
posts.append({'title': title, 'content': content})
return redirect(url_for('index'))
return render_template('new_post.html')
if __name__ == '__main__':
app.run(debug=True)
步骤 3:创建模板
在与“app.py”相同的目录中创建一个名为“templates”的目录。在此目录中,创建两个 HTML 文件:“index.html”和“new_post.html”。
`index.html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Blog</title>
</head>
<body>
<h1>My Blog</h1>
<a href="{{ url_for('new_post') }}">New Post</a>
<ul>
{% for post in posts %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>
`new_post.html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Post</title>
</head>
<body>
<h1>New Post</h1>
<form action="{{ url_for('new_post') }}" method="POST">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required>
<br>
<label for="content">Content:</label>
<textarea id="content" name="content" required></textarea>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
步骤 4:运行应用程序
通过在终端中执行以下命令来运行 Flask 应用程序:
python app.py
打开 Web 浏览器并导航至`http://127.0.0.1:5000/`。您应该会看到博客主页,其中包含一个用于创建新帖子的链接。单击该链接添加新帖子,然后返回主页以查看显示的帖子。
步骤 5:添加更多功能
为帖子添加时间戳
让我们为博客帖子添加时间戳,以显示每篇帖子的创建时间。
首先,导入`datetime`模块并修改`app.py`中的`new_post`路由:
from datetime import datetime
@app.route('/new', methods=['GET', 'POST'])
def new_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
posts.append({'title': title, 'content': content, 'timestamp': timestamp})
return redirect(url_for('index'))
return render_template('new_post.html')
然后,更新`index.html`以显示时间戳:
<ul>
{% for post in posts %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<small>Posted on {{ post.timestamp }}</small>
</li>
{% endfor %}
</ul>
添加 CSS 样式
让我们添加一些基本的 CSS 样式,让我们的博客看起来更漂亮。
在与 `app.py` 相同的目录中创建一个名为 `static` 的目录。在此目录中,创建一个名为 `styles.css` 的文件并添加以下样式:
/* static/styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f9f9f9;
}
h1 {
text-align: center;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin: 20px;
}
input, textarea {
width: 300px;
margin: 10px 0;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
ul {
list-style-type: none;
padding: 0;
}
li {
background-color: white;
margin: 10px;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
small {
display: block;
margin-top: 10px;
color: #777;
}
在模板中链接 CSS 文件:
`index.html`
<head>
...
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
`new_post.html`
<head>
...
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
步骤 6:添加用户身份验证
让我们为博客添加一个简单的用户身份验证系统。我们将使用 Flask-Login 来管理用户会话。
首先,安装 Flask-Login:
pip install Flask-Login
接下来,更新你的 `app.py`:
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
app = Flask(__name__)
app.secret_key = 'supersecretkey'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
# Dummy user database
users = {'admin': User(id=1, username='admin', password='password')}
@login_manager.user_loader
def load_user(user_id):
return users.get('admin')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = users.get(username)
if user and user.password == password:
login_user(user)
return redirect(url_for('index'))
else:
flash('Invalid credentials')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/')
def index():
return render_template('index.html', posts=posts)
@app.route('/new', methods=['GET', 'POST'])
@login_required
def new_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
posts.append({'title': title, 'content': content, 'timestamp': timestamp})
return redirect(url_for('index'))
return render_template('new_post.html')
if __name__ == '__main__':
app.run(debug=True)
为登录页面创建一个新模板 `login.html`:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Login</h1>
<form action="{{ url_for('login') }}" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</body>
</html>
步骤 7:使用数据库
使用 SQLite 数据库替换内存列表以保存博客文章。
首先,安装 Flask-SQLAlchemy:
pip install Flask-SQLAlchemy
更新你的 `app.py`:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
db = SQLAlchemy(app)
class Post(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)
timestamp = db.Column(db.String(20), nullable=False)
# Initialize the database
with app.app_context():
db.create_all()
@app.route('/')
def index():
posts = Post.query.order_by(Post.id.desc()).all()
return render_template('index.html', posts=posts)
@app.route('/new', methods=['GET', 'POST'])
@login_required
def new_post():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
new_post = Post(title=title, content=content, timestamp=timestamp)
db.session.add(new_post)
db.session.commit()
return redirect(url_for('index'))
return render_template('new_post.html')
步骤 8:编辑和删除帖子
添加编辑和删除帖子的功能。
更新您的 `app.py`:
@app.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_post(id):
post = Post.query.get_or_404(id)
if request.method == 'POST':
post.title = request.form['title']
post.content = request.form['content']
db.session.commit()
return redirect(url_for('index'))
return render_template('edit_post.html', post=post)
@app.route('/delete/<int:id>', methods=['POST'])
@login_required
def delete_post(id):
post = Post.query.get_or_404(id)
db.session.delete(post)
db.session.commit()
return redirect(url_for('index'))
创建用于编辑帖子的模板:
`edit_post.html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Post</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<h1>Edit Post</h1>
<form action="{{ url_for('edit_post', id=post.id) }}" method="POST">
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="{{ post.title }}" required>
<br>
<label for="content">Content:</label>
<textarea id="content" name="content" required>{{ post.content }}</textarea>
<br>
<button type="submit">Save</button>
</form>
</body>
</html>
更新 `index.html` 以包含编辑和删除链接:
<ul>
{% for post in posts %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<small>Posted on {{ post.timestamp }}</small>
<br>
<a href="{{ url_for('edit_post', id=post.id) }}">Edit</a>
<form action="{{ url_for('delete_post', id=post.id) }}" method="POST" style="display:inline;">
<button type="submit">Delete</button>
</form>
</li>
{% endfor %}
</ul>
您现在已经使用 Flask 创建了一个简易的博客系统!我们已经介绍了如何设置环境、创建路由、处理用户输入、显示帖子、添加时间戳、应用基本 CSS 样式还包括了用户身份验证、使用数据库的持久存储以及编辑和删除帖子的功能。这些功能增强了博客的可用性和功能性,使其成为一个更完整、更强大的应用程序。如果你阅读过小编的其他文章,以上内容只是Flask框架的冰山一角,感兴趣的话,请结合着之前的介绍(部署、高阶用法、异步、定时任务以及安全和认证等),继续随意尝试并扩展此项目。祝您编码愉快!
相关推荐
- 4万多吨豪华游轮遇险 竟是因为这个原因……
-
(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...
- “菜鸟黑客”必用兵器之“渗透测试篇二”
-
"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...
- 科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白
-
作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...
- 麦子陪你做作业(二):KEGG通路数据库的正确打开姿势
-
作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...
- 知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势
-
智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...
- 每日新闻播报(September 14)_每日新闻播报英文
-
AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...
- 香港新巴城巴开放实时到站数据 供科技界研发使用
-
中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...
- 5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper
-
本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...
- Qt动画效果展示_qt显示图片
-
今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...
- 如何从0到1设计实现一门自己的脚本语言
-
作者:dong...
- 三年级语文上册 仿写句子 需要的直接下载打印吧
-
描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...
- C++|那些一看就很简洁、优雅、经典的小代码段
-
目录0等概率随机洗牌:1大小写转换2字符串复制...
- 二年级上册语文必考句子仿写,家长打印,孩子照着练
-
二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- wireshark怎么抓包 (75)
- qt sleep (64)
- cs1.6指令代码大全 (55)
- factory-method (60)
- sqlite3_bind_blob (52)
- hibernate update (63)
- c++ base64 (70)
- nc 命令 (52)
- wm_close (51)
- epollin (51)
- sqlca.sqlcode (57)
- lua ipairs (60)
- tv_usec (64)
- 命令行进入文件夹 (53)
- postgresql array (57)
- statfs函数 (57)
- .project文件 (54)
- lua require (56)
- for_each (67)
- c#工厂模式 (57)
- wxsqlite3 (66)
- dmesg -c (58)
- fopen参数 (53)
- tar -zxvf -c (55)
- 速递查询 (52)