Python Flask之留言板(无数据库)

时间:2022-06-26 11:47:22

一个py文件,一个html文件,可以直接运行

py文件

 from flask import Flask, request, render_template, redirect, url_for
import time app = Flask(__name__) users = [] # 这里存放所有的留言 @app.route('/say/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html', says=users) else:
title = request.form.get('say_title')
text = request.form.get('say')
user = request.form.get('say_user')
date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) users.append({"title": title,
"text": text,
"user": user,
"date": date})
return redirect(url_for('index')) if __name__ == '__main__':
app.run(debug=True, )

index.html:

 <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>留言板</title>
</head>
<body>
<center><h1>留言</h1></center>
<center>
<form action="{{ url_for('index') }}" method="POST">
用户名: <input type="text" name="say_user"><br>
留言标题: <input type="text" name="say_title"><br>
留言内容: <input type="text" name="say"><br>
<button>提交留言</button>
</form>
</center>
<center>
<table border="2">
<thead>
<tr>
<th>标题</th>
<th>内容</th>
<th>用户</th>
<th>留言时间</th>
</tr>
</thead>
<tbody>
{% for say in says %}
<tr>
<td>{{ say['title'] }}</td>
<td>{{ say['text'] }}</td>
<td>{{ say['user'] }}</td>
<td>{{ say['date'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</center>
</body>
</html>

结果:

Python Flask之留言板(无数据库)