首先,确保你已经安装了Flask。你可以使用以下命令安装:
pip install Flask
然后,创建一个Flask应用程序,其中包含一个简单的表单。假设你的项目结构如下:
pip install Flask
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# 获取表单数据
username = request.form['username']
password = request.form['password']
# 这里可以对数据进行处理,例如验证用户身份等
# 将数据传递给模板
return render_template('index.html', username=username, password=password)
# 如果是GET请求,直接渲染表单页面
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Form</title>
</head>
<body>
<h1>Flask Form</h1>
<form method="post" action="/">
<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">Submit</button>
</form>
{% if username and password %}
<h2>Submitted Data:</h2>
<p>Username: {{ username }}</p>
<p>Password: {{ password }}</p>
{% endif %}
</body>
</html>