Django学习手册 - cookie / session

Posted anec

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django学习手册 - cookie / session相关的知识,希望对你有一定的参考价值。

cookie

"""
cookie属性:
obj.set_cookie(key,value,....)
obj.set_signed_cookie(key,value,salt="加密盐",....)
    参数:
        key                 键
        value=“”           值
        max_age=None        超时时间
        expires=None        超时日期
        path="/"            cookit生效的路径,/表示根路径,特殊的,跟路径的cookie可以被任何url被任何url的页面访问
        domain=None         cookie生效的域名
        secure=False        https传输
        httponly=False      只能http协议传输,无法javascript获取(不是绝对,底层抓包可以获取到)
        
获取cookie
request.COOKIES
request.COOKIES[‘username‘]
request.COOKIES.get("username")

设置cookie
response = render(request,‘index.html‘)
response = redirect("/index/")
response = set_cookie("key","value")
return response

加盐配置:
obj = HttpResponse("S")
获取加盐cookie
obj.set_signed_cookie("username","passwd",salt="jiayan")
设置加盐cookie
obj.get_signed_cookie("username",salt="jiayan")
获取与设置的加盐 一定要是相同的加盐字符

"""

前端:(login 页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <form action="/login/" method="post">
        <p>
           <span>用户名:</span> <input type="text" name="user">
            <span>密码:</span><input type="password" name="pwd">
            <input type="submit" value="提交">
        </p>
        </form>
    </div>
</body>
</html>

前端:(index页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>
        欢迎登录.........

    </h1>
</body>
</html>

URL:

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from app01 import views

urlpatterns = [
    path(admin/, admin.site.urls),
    url(^login/, views.login),
    url(^index/, views.index),
]

后端:

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

def login(request):
    print(request.COOKIES)
    print(request.session)
    if request.method == "POST":
        u = request.POST.get("user",None)
        p= request.POST.get("pwd",None)
        if u == "root" and p == "123":
            # cookie的方式:
            # ret = redirect("/index/")
            # #设置cookie数值
            # ret.set_cookie("name","123",10)
            # return ret

            #session方式
            request.session["info_login"]=True
            request.session["user"] = u
            return redirect("/index/")

        else:
            redirect("/login/")
    return render(request,"login.html")

def index(request):
    #cookie
    # if request.COOKIES.get("name",None):
    #     print("index")
    #     return render(request,"index.html")

    #session
    if request.session.get("info_login",None):
        name = request.session.get("user")
        return render(request,"index.html")
    #session 默认存放在数据库中。

    else:
        return redirect("/login/")

 --------------------------------------------------------------------------------------------------------------------------------------------------------

装饰器的方式:

from django.shortcuts import render,redirect,HttpResponse

# Create your views here.

def aut(fum):
    def log(request,*args,**kwargs):
        if request.COOKIES.get("user",None):
            return fum(request,*args,**kwargs)
        else:
            return redirect("/login/")
    return log


def login(request):
    if request.method == "POST":
        u = request.POST.get("user", None)
        p = request.POST.get("pwd", None)
        if u == "root" and p == "123":
            ret = redirect("/index/")
            # ret.set_cookie("user", u)
            ret.set_signed_cookie("user",u,salt="abcd")

            return ret
        else:
            return redirect("/login/")
    return render(request,"login.html")

@aut
def index(request):
    return HttpResponse("OK")

 

以上是关于Django学习手册 - cookie / session的主要内容,如果未能解决你的问题,请参考以下文章

8Django实战第8天:session和cookie自动登录机制

Flask 简单使用

Django学习手册 - 初识django

使用 django 和 AWS SES 签名 V4 发送电子邮件

Python学习---django下的cookie操作 180201

Django学习手册 - 创建Django工程项目以及APP