Cookie:是一种服务器存放在本地浏览器的一种状态标识,可以更加快速的确认用户的身份和状态。超过设定的时间便清除。
案例:
py代码:
from flask import Flask, render_template, request, redirect, url_for, make_response app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': ucookies = request.form.get('ucookie', "") # show_cookies:是路由里面的路径,这里专门使用showCookies区分开来
# redirect('show_cookies'):是跳转的路径 # make_response():响应
response = make_response(redirect('show_cookies')) response.set_cookie('ucookie', ucookies) # 设置cookie return response return render_template('index.html') @app.route('/show_cookies/') def showCookies(): return request.cookies.get('ucookie') # 获取cookie if __name__ == '__main__': app.run(debug=True)
HTML代码:
<!DOCTYPE html> <html> <head> <title>index</title> </head> <body> <form action="" method="POST"> cookie value:<input type="text" name="ucookie"><br> <input type="submit" value="sub"> </form> </body> </html>
Session:存放在服务器的一种标识,用户退出即删除。
案例:
from flask import Flask, render_template, request, redirect, url_for, session app = Flask(__name__) app.secret_key = "dnoadnddddascccdascccdnoadnddddascccdasccc" # session秘钥(随机字符串),随机秘钥可以使用os.urandom获取 @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': usession = request.form.get('usession', "") if usession: session['uname'] = usession # 设置session return redirect(url_for("showSession")) # 跳转,注:url_for里面接的是函数名 return render_template('index.html') @app.route('/show_session/') def showSession(): return session["uname"] # 获取Session @app.route("/del_session/") def delSession(): session.pop('uname', None) # 删除Session return "successful delete" if __name__ == '__main__': app.run(debug=True)
<!DOCTYPE html> <html> <head> <title>index</title> </head> <body> <form action="" method="POST"> session value:<input type="text" name="usession"><br> <input type="submit" value="sub"> </form> </body> </html>