简介:
在 Web 开发中,表单处理是一项常见的任务。Flask 是一个轻量级的 Python Web 框架,它提供了简单而灵活的方式来处理表单数据、请求对象、重定向以及返回 JSON 数据给前端。
flask安装教程:通过命令行的方式快速创建一个flask项目
首先创建一个简单的 Flask 应用程序,包含两个路由:
/
:包含一个表单,用于用户输入用户名和密码。/welcome
:用于显示欢迎消息。from flask import Flask, request, redirect, jsonify, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# 在实际应用中,这里可以添加验证逻辑
return redirect('/welcome')
return render_template('index.html')
@app.route('/welcome')
def welcome():
return jsonify({'message': 'Welcome!'})
if __name__ == '__main__':
app.run(debug=True)
创建一个 HTML 模板,用于渲染表单。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Form Example</title>
</head>
<body>
<h1>Login Form</h1>
<form method="POST" action="/">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>