Django之Cookie与Session

一、cookie

1、cookie使用

def cookie(request):

    print(request.COOKIES)    # 获取所有的COOKIES

    obj = render(request, "cookie.html")
    obj.set_cookie("k1", "v1")    # 设置COOKIES

    """
    def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False):
    max_age  多少秒之后过期
    expires  在几点过期
    path     设置访问哪个url才会生效,针对指定url生效,  path='/'  表示针对全站生效

    # 下面几个是针对安全方面的,默认不进行操作
    domain   设置允许那个域名访问,默认是当前域名生效
    secure   是否为https
    httponly 设置只能够通过http协议传输
    """

    return obj

2、 使用Cookie做登录认证

  • views.py
def login(request):
    # 登录
    if request.method == "POST":
        u = request.POST.get("user")
        p = request.POST.get("pwd")

        if u == "zhangcong" and p == "123":

            red = redirect('/index')        # 跳转到/index页面
            red.set_cookie('username', u)   # 设置cookie

            return red

    return render(request, 'login.html')


def index(request):
    # 登录成功之后显示该页面
    user = request.COOKIES.get("username")  # 获取cookies

    # 如果cookies存在,则返回index.html,否则跳转到登录页面
    if user:
        return render(request, "index.html", {"user": user})

    else:

        return redirect("/login/")
  • login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="POST">
        <div>
            <input type="text" name="user" />
        </div>
        <div>
            <input type="text" name="pwd" />
        </div>
        <div>
            <input type="submit" value="提交" >
        </div>
    </form>

</body>
</html>
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/s1.css">
</head>
<body>

    <h1>{{ user }}, 欢迎登录</h1>

</body>
</html>

二、session

原文地址:https://www.cnblogs.com/CongZhang/p/5894729.html