flask response跳转页面

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)

 

posted @ 2021-09-08 15:45  fat_girl_spring  阅读(526)  评论(0编辑  收藏  举报