Flask-页面跳转-重定向

页面跳转和重定向
重定向分为永久性重定向和暂时性重定向,在页面上体现的操作就是浏览器会从一个页面自动跳转到另外一个页面。比如用户访问了一个需要权限的页面,但是该用户当前并没有登录,因此我们应该给他重定向到登录页面。
• 永久性重定向:http的状态码是301,多用于旧网址被废弃了要转到一个新的网址确保用户的访问,最经典的就是京东网站,你输入www.jingdong.com的时候,会被重定向到www.jd.com,因为jingdong.com这个网址已经被废弃了,被改成jd.com,所以这种情况下应该用永久重定向。
• 暂时性重定向:http的状态码是302,表示页面的暂时性跳转。比如访问一个需要权限的网址,如果当前用户没有登录,应该重定向到登录页面,这种情况下,应该用暂时性重定向。
在flask中,重定向是通过flask.redirect(location,code=302)这个函数来实现的,location表示需要重定向到的URL,应该配合之前讲的url_for()函数来使用,code表示采用哪个重定向,默认是302也即暂时性重定向,可以修改成301来实现永久性重定向

from flask import Flask,url_for,request,redirect

app = Flask(__name__)

@app.route("/")
def index():
    #
    # /article/2/ 只传一个aid
    # 根据函数的名字进行反转 得到函数对应的路由 重定向
    # /article/2/?page=2  aid=2,page=2  把不存在的数page=2当参数了
    # /article/2/?page=2&t=123 传多个不存在参数 后面用&连接
    print(url_for("article_list",aid=2,page=2,t=123))
    return "hello world"

# http://127.0.0.1:5000/article/2/ 如何通过函数名得到url地址?
@app.route("/article/<aid>/")
def article_list(aid):
    return "article list {}".format(aid)

@app.route("/detail/<did>/")
def article_detail(did):
    # print(url_for("index"))
    # /?next=%2F
    print(url_for("index",next="/"))
    # / => %2F
    return "article detail {}".format(did)

# 默认都是接收GET请求 想要接收POST请求 需要怎么办?定义methods
# @app.route("/login/",methods=["POST","GET"])
# def login():
    # get 参数直接在url中 一般都是获取数据
    # post 参数没有直接体现在URL地址中 一般都是提交表单数据
    # print(type(request.args))
    # print(request.args.get('username'))

    # 接收POST请求发送的参数如何接收
    # print(request.form.get("name"))
    # return "login"

# 页面重定向 登录
@app.route("/signin/")
def login():
    return "login"

@app.route("/profile/")
def profile():
    name = request.args.get("name")

    if name:
        return name
    else:
        # 重定向到登陆页面
        # return redirect(url_for("login"),code=301)
        return redirect(url_for("login"),code=301)



if __name__ == '__main__':
    app.run(debug=True)
发布了118 篇原创文章 · 获赞 0 · 访问量 2667

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/105420427