注意:本例的Flask后端代码位于:网站开发\Backend development 文件夹下;前端代码位于:网站开发\Front end development 文件夹下,请根据实际调整
这个例子在前端输入信息
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Form Example</title>
</head>
<body>
<h1>输入信息并提交</h1>
<form action="/submit" method="post">
<label for="inputText">文本:</label>
<input type="text" id="inputText" name="inputText">
<button type="submit">提交</button>
</form>
<!-- 显示提交的信息 -->
{% if data %}
<h2>提交记录</h2>
<table>
<tr>
<th>时间</th>
<th>内容</th>
</tr>
{% for item in data %}
<tr>
<td>{{ item.time }}</td>
<td>{{ item.content }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
</body>
</html>
后端:
import os
import json
from datetime import datetime
from flask import Flask, render_template, request
app = Flask(__name__, template_folder='../Front end development')
# 数据文件路径
DATA_FILE = '../Front end development/data/submissions.json'
def load_data():
"""加载已有的提交数据"""
if not os.path.exists(DATA_FILE):
with open(DATA_FILE, 'w') as file:
json.dump([], file)
with open(DATA_FILE, 'r') as file:
return json.load(file)
def save_data(data):
"""保存提交的数据"""
with open(DATA_FILE, 'w') as file:
json.dump(data, file, indent=4)
@app.route('/')
def form():
# 加载已有的提交数据
data = load_data()
return render_template('text1.html', data=data)
@app.route('/submit', methods=['POST'])
def submit():
input_text = request.form.get('inputText')
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 添加新数据
new_data = {'time': current_time, 'content': input_text}
data = load_data()
data.append(new_data)
save_data(data)
# 重新加载数据并返回页面
data = load_data()
return render_template('text1.html', data=data)
if __name__ == '__main__':
app.run(debug=True)