前言
Cookie 详解:https://www.cnblogs.com/poloyy/p/12513247.html
这一节来瞧一瞧如何用 Flask 操作 Cookie
接下来就是 实战栗子!!!
功能 list
提供操作 Cookie 的 3 项功能
页面路径 | 功能 |
---|---|
/set_cookie | 设置一个名称为 poloyy、值为 https://www.cnblogs.com/poloyy 的 Cookie |
/get_cooike | 在服务端获取名称为 ‘poloyy’ 的 Cookie,并将其值返回给客户 |
/del_cooike | 删除名称为 ‘poloyy’ 的 Cookie |
项目构成
程序有 3 个源文件构成
源文件 | 描述 |
---|---|
app.py | Flask 后端程序,提供操作 Cookie 的接口 |
templates/get_cookie.html | 在服务端获取 Cookie,显示 Cookie 的值 |
templates/js_cookie.html | 在客户端通过 Javascript 显示 Cookie 的值 |
模板文件 get_cookie.html
浏览器访问网站时,每次都会把 Cookie 发送给服务端,在服务端获取 Cookie 并返回给浏览器
<html>
<meta charset='UTF-8'>
<title>在服务端获取 cookie</title>
<body>
<h2>在服务端获取 cookie: <b>{{cookie}}<b/></h2>
</body>
</html>
模板文件 js_cookie.html
<html>
<meta charset='UTF-8'>
<title>在服务端设置 cookie</title>
<body>
<h2>在服务端设置 cookie</h2>
<h2>在客户端通过 Javascript 读取 cookie: <b id='cookie'><b/></h2>
</body>
<script>
cookie = document.getElementById('cookie');
cookie.innerHTML = document.cookie;
</script>
</html>
document.cookie 是浏览器端保存的 cookie 值,在 id=cookie 中显示 Cookie 值
Flask app.py 代码
引入模块
#!/usr/bin/python3
from flask import Flask, request, Response, render_template
app = Flask(__name__)
request 对象详解:https://www.cnblogs.com/poloyy/p/14995215.html
request.cookies 就是获取客户端发送的 Cookie
获取 Cookie
@app.route("/get_cookies")
def get_cookies():
cookie = request.cookies.get('poloyy')
return render_template('get_cookie.html', cookie = cookie)
设置 Cookie
@app.route("/set_cookie")
def set_cookie():
html = render_template("js_cookie.html")
response = Response(html)
response.set_cookie("poloyy", "https://www.cnblogs.com/poloyy")
return response
删除 Cookie
@app.route("/del_cookie")
def del_cookie():
html = render_template("js_cookie.html")
response = Response(html)
response.delete_cookie("poloyy")
return response
if __name__ == '__main__':
app.run(debug=True)
浏览器的运行效果
设置 cookie
![](https://i-blog.csdnimg.cn/blog_migrate/194882e9b4b30f7938bc6f4c44676b54.png)
获取 cookie
![](https://i-blog.csdnimg.cn/blog_migrate/5433088e45e23b91382ab668b624040e.png)
删除 cookie
![](https://i-blog.csdnimg.cn/blog_migrate/0fcb18bb6404d47f013a2183d091abcb.png)
总结
![](https://i-blog.csdnimg.cn/blog_migrate/2d53bd6806dd905040277f237b63ce28.png)