Flask 简明教程
Flask – Cookies
Cookie 以文本文件形式存储在客户端计算机上。其目的是记住并跟踪与客户端使用相关的数据,以便提供更好的访问者体验和网站统计信息。
A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics.
一个 Request object 包含 Cookie 的属性。它是一个包含所有 Cookie 变量及其对应值的对象字典,这些变量及其对应值是由客户端传输的。此外,Cookie 还存储了它的过期时间、路径和网站的域名。
A Request object contains a cookie’s attribute. It is a dictionary object of all the cookie variables and their corresponding values, a client has transmitted. In addition to it, a cookie also stores its expiry time, path and domain name of the site.
在 Flask 中,Cookie 设置在响应对象上。使用 make_response() 函数从视图函数的返回值中获取响应对象。然后,使用响应对象的 set_cookie() 函数存储一个 Cookie。
In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie.
读回 Cookie 非常容易。 get() 属性的 request.cookies 方法用于读取 Cookie。
Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie.
在下面的 Flask 应用中,当您访问 ‘/’ URL 时,会弹出一个简单的表单。
In the following Flask application, a simple form opens up as you visit ‘/’ URL.
@app.route('/')
def index():
return render_template('index.html')
此 HTML 页面包含一个文本输入。
This HTML page contains one text input.
<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 并呈示另一个页面。
The Form is posted to ‘/setcookie’ URL. The associated view function sets a Cookie name userID and renders another page.
@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’ contains a hyperlink to another view function getcookie(), which reads back and displays the cookie value in browser.
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome '+name+'</h1>'
运行应用并访问 http://localhost:5000/
Run the application and visit http://localhost:5000/
设置一个 Cookie 的结果以这种方式显示 −
The result of setting a cookie is displayed like this −
读取回 Cookie 的输出显示如下。
The output of read back cookie is shown below.