Problem: 使用 Python 的 Web 框架,做一个 Web 版本留言簿应用。

阅读资料: Python 有哪些 Web 框架

Solution: Message Board, Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-04-01 15:08:21
# @Author : NSSimacer
# @Version : 1.0
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
from datetime import date
DATABASE = 'message board.db'
DEBUG = True
SECRET_KEY = 'development key'
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('MB_SETTINGS', silent=True)
def connect_db():
'''
连接 SQLite 3 数据库
'''
conn = sqlite3.connect(app.config['DATABASE'])
conn.row_factory = sqlite3.Row
return conn
def get_db():
'''
在应用上下文环境中保持数据库连接
'''
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
@app.teardown_appcontext
def close_db(error):
'''
应用关闭时关闭数据库
'''
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
def init_db():
'''
初始化数据库
'''
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read()) # 执行 SQL 脚本
db.commit()
def get_user_name_by_id(user_id):
'''
根据用户 ID 查找用户名
'''
cursor = g.db.execute(
'select user_name from t_user where user_id=?', (user_id, ))
return cursor.fetchone()[0]
@app.before_request
def before_request():
g.db = connect_db()
@app.route('/')
def show_messages(messages=None):
'''
显示留言
'''
if not session.get('logged_in'): # 未登录则先跳到登录页面
return redirect(url_for('login'))
cursor = g.db.execute(
'select topic, message_content, message_time, \
user_id from t_messages order by message_id desc limit 5')
messages = [dict(user_name=get_user_name_by_id(row[3]),
topic=row[0],
message_content=row[1],
message_time=row[2]) for row in cursor.fetchall()]
# 传递留言列表到页面并对页面进行渲染
return render_template('index.html', messages=messages)
@app.route('/add_new_message', methods=['POST'])
def add_new_message():
'''
添加新的留言
'''
if not session.get('logged_in'):
abort(401) # 未登录验证用户
params = ([session['user']['user_id'],
request.form['topic'],
request.form['message'],
date.today()])
g.db.execute('insert into t_messages values(null, ?, ?, ?, ?)', params)
g.db.commit()
flash('New mesage was successfully posted!')
return redirect(url_for('show_messages'))
@app.route('/login', methods=['GET', 'POST'])
def login():
'''
登录留言板
'''
error = None
if request.method == 'POST':
params = (request.form['userName'], request.form['pwd'])
cursor = g.db.execute(
'select * from t_user where user_name=? and user_pwd=?', params)
row = cursor.fetchone()
if row is None:
error = 'Login failed!'
else:
user = dict(user_id=row[0], user_name=row[1])
session['user'] = user
session['logged_in'] = True
flash('You have logged in!')
return redirect(url_for('show_messages'))
return render_template('login.html', error=error)
@app.route('/logout')
def logout():
'''
退出留言板
'''
session.pop('logged_in', None)
session.pop('user', None)
flash('You have logged out!')
return redirect(url_for('login.html'))
@app.route('/register', methods=['GET', 'POST'])
def register():
'''
用户注册
'''
error = None
if request.method == 'POST':
user_name = request.form['userName']
pwd = request.form['pwd']
if user_name != '' and pwd != '':
params = (user_name, pwd)
g.db.execute('insert into t_user values(null, ?, ?)', params)
g.db.commit()
flash('Registered successfully!')
return redirect(url_for('login'))
else:
error = 'Invalid user name or password!'
return redirect(url_for('register'))
return render_template('register.html', error=error)
if __name__ == '__main__':
app.run()

这个题目的主要目的是练习 Python Web 框架的使用,比较常用的框架有 DjangoFlaskPyramid … 关于这几者的比较,可以参考 Django vs Flask vs Pyramid: Choosing a Python Web Framework,然后选择一个 Web 框架完成这道习题。

我选择了 Flask,因为它比较“轻量”,并且适合比较喜欢折腾的人。这道习题是参考 Flask 的文档写的,也可以参考翻译过来的 Flask 中文文档

关于数据存储,题目需求比较简单,可以选择 MySQL,SQLite,Shelve 或者 Redis … 完全看个人喜好。

题目来源:Python 练习册,每天一个小程序 THX!