今天给大家说说flask页面跳转的方法,话不多说直接上代码:
1,redirect()
from flask import Flask
from flask import make_response, request, render_template,redirect,url_for
import setting,json
app = Flask(__name__)
app.config.from_object(setting)
@app.route('/')
def index():
return render_template("index.html")
users=[]
@app.route('/register',methods = ["Post","Get"])
def register():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
repassword = request.form.get("repassword")
if password == repassword:
user = {"username":username,"password":password}
users.append(user)
print(users)
return redirect('/') #两次响应 1、302 + location:/ 2、根据location返回需要的值
else:
return '密码不一致'
else:
return render_template("register.html")
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
2,url_for() 通过endpoing在route路由中设置别名来进行跳转
from flask import Flask
from flask import make_response, request, render_template,redirect,url_for
import setting,json
app = Flask(__name__)
app.config.from_object(setting)
@app.route('/',endpoint='index')
def index():
return render_template("index.html")
users=[]
@app.route('/register',methods = ["Post","Get"])
def register():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
repassword = request.form.get("repassword")
if password == repassword:
user = {"username":username,"password":password}
users.append(user)
print(users)
return redirect(url_for('index')) # url_for
else:
return '密码不一致'
else:
return render_template("register.html")
@app.route('/test')
def test():
url = url_for('index') #路径反向解析
print(url) #打印出来是'/'
return 'test'
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
以上便是关于flask页面跳转,两种方法你知道吗的全部内容,更多内容干货可关注慕课网~
共同学习,写下你的评论
评论加载中...
作者其他优质文章