zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    phpmyadmin设置密码,不用登录直接进入
    如何将本地文件复制到远程服务器听语音
    win7 64位wamp2.5无法启动MSVCR110.DLL丢失听语音
    最大连接数:60 iops:150 什么概念?
    北京可以备案什么域名
    远程桌面命令是什么 如何使用命令连接远程桌面
    如何知道电脑是几核?
    nohup命令与&区别,jobs,fg,bg,Ctrl-Z、Ctrl-C、Ctrl-D
    Shell 文件包含
    Shell 输入/输出重定向
  • 原文地址:https://www.cnblogs.com/CongZhang/p/5894729.html
Copyright © 2011-2022 走看看