Flask框架 之重定向、cookie和session

一、URL重定向(redirect)

@app.route("/login")
def login():
    # 使用url_for函数通过视图函数的名字找到url路径
    url = url_for("index")
    return redirect(url)

二、cookie操作

@app.route("/")
def index():
    resp = make_response("set cookie is ok")
    # 设置cookie
    resp.set_cookie("name", "yy")
    # 通过max_age设置过期时间,单位秒
    resp.set_cookie("age", "18", max_age=3600)
    return resp


@app.route("/cookie")
def cookie():
    # 获取cookie
    name = request.cookies.get("name")
    return name

@app.route("/delete")
def delete_cookie():
    resp = make_response("delete ok")
    # 删除cookie
    resp.delete_cookie("name")
    return resp

三、session操作

# flask中的session会用到的密钥字符串
app.config['SECRET_KEY'] = os.urandom(24)
# 默认session过期时间为30天,下面代码设置为5小时过期
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=5)


@app.route("/login")
def login():
    # 设置session
    session["username"] = "yy"
    session["password"] = "admin"
    session["data"] = {"a": 1, "b": 2}
    return redirect(url_for("index"))


@app.route("/index")
def index():
    data = session.get("data")
    if data is None:
        return "None"
    return str(data)


@app.route("/delete")
def delete():
    # 删除session
    # del session['username']
    session.clear()
    return "ok"

 

posted @ 2019-06-12 23:01  样子2018  阅读(574)  评论(0编辑  收藏  举报