Flask 学习-62.Cookies 设置与使用
前言
Cookie 是保存到客户端的,用户通过浏览器访问网站保存到本地,Flask 通过Response将cookie写到浏览器上,下一次访问,浏览器会根据网站域名(或IP_携带cookie过来.
Flask 中处理cookies
在Flask中对cookie的处理主要有3个方法
set_cookie设置cookie,默认有效期是临时cookie,浏览器关闭就失效可以通过 max_age 设置有效期, 单位是秒
resp = make_response("success") # 设置响应体
resp.set_cookie("username", "yoyo", max_age=24*60*60)
request.cookies获取cookie,通过reques.cookies的方式, 返回的是一个字典,可以获取字典里的相应的值
cookie_username = request.cookies.get("username")
delete_cookie 这里的删除只是让cookie过期,并不是直接删除cookie
resp = make_response("delete cookies") # 设置响应体
resp.delete_cookie("username")
set_cookie设置cookie
以下是set_cookie 用到的一些参数,使用key-value 键值对,max_age:是设置cookie的有效期, 单位是秒
默认有效期是临时cookie,浏览器关闭就失效。
def set_cookie(
self,
key: str,
value: str = "",
max_age: t.Optional[t.Union[timedelta, int]] = None,
expires: t.Optional[t.Union[str, datetime, int, float]] = None,
path: t.Optional[str] = "/",
domain: t.Optional[str] = None,
secure: bool = False,
httponly: bool = False,
samesite: t.Optional[str] = None,
) -> None:
"""Sets a cookie.
A warning is raised if the size of the cookie header exceeds
:attr:`max_cookie_size`, but the header will still be set.
:param key: the key (name) of the cookie to be set.
:param value: the value of the cookie.
:param max_age: should be a number of seconds, or `None` (default) if
the cookie should last only as long as the client's
browser session.
:param expires: should be a `datetime` object or UNIX timestamp.
:param path: limits the cookie to a given path, per default it will
span the whole domain.
:param domain: if you want to set a cross-domain cookie. For example,
``domain=".example.com"`` will set a cookie that is
readable by the domain ``www.example.com``,
``foo.example.com`` etc. Otherwise, a cookie will only
be readable by the domain that set it.
:param secure: If ``True``, the cookie will only be available
via HTTPS.
:param httponly: Disallow JavaScript access to the cookie.
:param samesite: Limit the scope of the cookie to only be
attached to requests that are "same-site".
"""
使用示例
from flask import Flask, make_response, request
app = Flask(__name__)
@app.route("/set")
def set_cookie():
resp = make_response({"msg": "success"})
'''
设置cookie,默认有效期是临时cookie,浏览器关闭就失效
可以通过 max_age 设置有效期, 单位是秒
'''
resp.set_cookie("username", "yoyo", max_age=24*60*60)
resp.set_cookie("admin", "yes", max_age=24*60*60)
return resp
@app.route("/get")
def get_cookie():
"""
获取cookie,通过request.cookies的方式,
返回的是一个字典,可以用get的方式
"""
cookie_1 = request.cookies.get("username") # 通过key 获取
return cookie_1
@app.route("/delete")
def delete_cookie():
"""
删除cookie,通过delete_cookie()的方式,里面是cookie的名字
这里的删除只是让cookie过期,并不是直接删除cookie
"""
resp = make_response({"msg": "success"})
resp.delete_cookie("username")
return resp
if __name__ == '__main__':
app.run(debug=True)
启动服务访问网站就可以看到
访问/get
可以获取cookie
访问/delete
让cookie过期
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-09-08 python测试开发django-120.bootstrap-table表格添加操作按钮(查看/修改/删除)
2021-09-08 python测试开发django-119.model_to_dict会漏掉DateTimeField字段
2021-09-08 python测试开发django-118.json 解析查询数据库 datetime 格式问题
2021-09-08 python测试开发django-117.bootstrapTable结合Paginator分页器查显示表格
2020-09-08 pytest文档54-Hooks函数terminal打印测试结果(pytest_report_teststatus)