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过期

posted @ 2022-09-08 15:28  上海-悠悠  阅读(407)  评论(0编辑  收藏  举报