flask提供的request请求对象可以实现获取url或表单中的字段值
GET请求
从URL中获取name、age两个参数
from flask import Flask,url_for,redirect,request
app=Flask(__name__)
@app.route('/')
def index():
name=request.args.get('name')
age=request.args.get('age')
message=f'姓名:{name}\n年龄:{age}'
return message
if __name__=='__main__':
app.run(
debug=True,
port=5000
)
POST请求
使用request.form可以接受表单数据
login.html模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="" method="post">
<div>
<label for="username">用户名</label>
<input type="text" id="username" name="username" value="">
</div>
<div>
<label for="password">密码</label>
<input type="password" id="password" name="password" value="">
</div>
<button type="submit">提交</button>
</form>
</body>
</html>
获取用户名称、密码
from flask import Flask,url_for,redirect,request,render_template
app=Flask(__name__)
@app.route('/login',methods=['GET','POST'])
def login():
if request.method=='POST':
username=request.form['username']
password=request.form['password']
message=f'姓名:{username}</br>密码:{password}'
return message
return render_template('login.html')
if __name__=='__main__':
app.run(
debug=True
)