cookie的設定、獲取和刪除

sky-影發表於2019-03-22

 

1.

from flask import Flask,make_response

app = Flask(__name__)

@app.route("/set_cookie")
def set_cookie():
    resp = make_response("success!")
    #設定cookie,預設有效期是臨時,瀏覽器關閉就失效
    resp.set_cookie("itcase","python")
    resp.set_cookie("itcase2","python2")
    #max_age設定有效期,單位:秒
    resp.set_cookie("itcase3","python3",max_age=36000)

if __name__ == "__main__":
    app.run(debug=True)

 

2.get_cookie

from flask import request

@app.route("/get_cookie")
def get_cookie():
    c = request.cookies.get("itcase")
    return c
    

 

3.delete_cookie

@app.route("/delete_cookie")
def delete_cookie():
    resp = make_response("del success")
    resp.delete_cookie("itcase2")
    return resp

 

4. 自己設定響應頭

@app.route("set_cookie")
def set_cookie():
    resp = make_response("success")
    #resp.set_cookie("")
    resp.headers["Set-Cookie"]= "itcase3=python3; Expires=Fri, 22-Mar-2019 19:45:09 GMT; Max-Age=36000; Path=/"
    return resp

相關文章