Flask Cookies
Cookie 以文本文件的形式存储在客户端的计算机上。其目的是记住和跟踪与客户使用相关的数据,以获得更好的访问者体验和网站统计信息。
Request 对象包含 Cookie 的属性。它是所有 cookie 变量及其对应值的字典对象,客户端已传输。除此之外,cookie 还存储其网站的到期时间,路径和域名。
在 Flask 中,对响应对象设置 cookie。使用 make_response() 函数从视图函数的返回值获取响应对象。之后,使用响应对象的 set_cookie() 函数来存储 cookie。
读回 cookie 很容易。request.cookies 属性的 get() 方法用于读取 cookie。
在以下 Flask 应用程序中,当您访问 ‘/’ URL 时,会打开一个简单的表单。
@app.route('/')
def index():
return render_template('index.html')
此 HTML 页面包含一个文本输入。
<html>
<body>
<form action = "/setcookie" method = "POST">
<p><h3>Enter userID</h3></p>
<p><input type = 'text' name = 'nm'/></p>
<p><input type = 'submit' value = 'Login'/></p>
</form>
</body>
</html>
表单发布到 ‘/setcookie’ URL。相关联的视图函数设置 Cookie 名称 userID 并呈现另一个页面。
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('readcookie.html'))
resp.set_cookie('userID', user)
return resp
readcookie.html 包含指向另一个视图函数 getcookie() 的超链接,它读回并在浏览器中显示 Cookie 值。
readcookie.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/getcookie">getcookie</a>
</body>
</html>
getcookie()
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome '+name+'</h1>'
运行应用程序,并访问 http://localhost:5000/

输入 name 后点击 Login

点击 getcookie

可以在浏览器控制台中看到存储的 Cookie

删除 cookie 方法
@app.route('/delCookie', methods=['GET'])
def delCookie():
response = make_response('delCookie')
response.delete_cookie('id')
return response

浙公网安备 33010602011771号