学习内容:①判断请求方式(request.method)
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
# 判断请求方式
if request.method=='POST':
return render_template('index.html')
if __name__ == '__main__':
app.run()
②获取表单信息(request.form.get())
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
# 判断请求方式
if request.method=='POST':
#获取请求参数
username=request.form.get('username')
password=request.form.get('password')
password2=request.form.get('password2')
print('username:',username)
print('password:',password)
print('password2:',password2)
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
③判断表但是否填写完整(if not all())
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
# 判断请求方式
if request.method=='POST':
#获取请求参数
username=request.form.get('username')
password=request.form.get('password')
password2=request.form.get('password2')
print('username:',username)
print('password:',password)
print('password2:',password2)
# 判断表但是否填完整
if not all([username,password,password2]):
print("表单未填完整")
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
④判断两次输入密码是否一致
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
# 判断请求方式
if request.method=='POST':
#获取请求参数
username=request.form.get('username')
password=request.form.get('password')
password2=request.form.get('password2')
print('username:',username)
print('password:',password)
print('password2:',password2)
# 判断表但是否填完整
if not all([username,password,password2]):
print("表单未填完整")
# 判断两次密码是否一致
if password!=password2:
print("两次密码不一致,请重新输入!")
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
完整代码:
app.py:
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
# 判断请求方式
if request.method=='POST':
#获取请求参数
username=request.form.get('username')
password=request.form.get('password')
password2=request.form.get('password2')
print('username:',username)
print('password:',password)
print('password2:',password2)
# 判断表但是否填完整
if not all([username,password,password2]):
print("表单未填完整")
# 判断两次密码是否一致
if password!=password2:
print("两次密码不一致,请重新输入!")
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/">
<label> 账号:</label><input type="text" name="username"><br>
<label> 密码:</label><input type="password" name="password"><br>
<label> 确认密码:</label><input type="password" name="password2"><br>
<input type="submit" name="submit" value="登录">
<input type="reset" name="reset" value="重置">
</form>
</body>
</html>
运行截图: