首页 > 其他分享 >Cookie session

Cookie session

时间:2023-11-23 21:12:41浏览次数:34  
标签:return request sign session Cookie home login

今日概要

【零】发展史

  • 一开始:只有一个页面,没有登录功能,大家看到东西都一样
    • 新闻
  • 时代发展,出现了需要登录注册的网站,要有一门技术存储我们的登录信息
    • 京东、天猫
    • cookie
      • 存储形式:k:v键值对
      • 存储位置:客户端
      • 不安全,信息可能会泄露
  • 时代发展,需要有一门新的安全的技术
    • session
    • 标识符,来表示我是当前用户加密出来的数据
    • 对敏感信息进行加密处理
      • 存储服务端:
      • 标识符配合上你的加密串
    • 把我的标识符+ 字符串全给客户端
      • 客户端存储格式
        • session_id:返回回来的表示符+加密串
  • token
    • 三段式加密

【一】Cookie

【1】设置cookie

HttpResponse
render
redriect

obj = HttpResponse("ok")
obj.set_cookie('k','v')
  • 设置cookie

    def login(request, *args, **kwargs):
    if request.method == 'POST':
    username = request.POST.get("username")
    password = request.POST.get("password")
    if username == "dream" and password == "521":
    obj = HttpResponse("ok")
    obj.set_cookie('sign', 'user')
    return obj
    else:
    return redirect('/login/')
    return render(request, 'login.html')

  • 取值cookie验证

    def home(request, *args, **kwargs):
    sign = request.COOKIES.get('sign')
    if sign and sign == 'user':
    return HttpResponse("这是home页面")
    else:
    return redirect('/login/')

【2】取值

request.COOKIES.get('k')
  • 完整版 cookie登录注册

    def login(request, *args, **kwargs):
    # next_url = request.get_full_path()
    # print(next_url) # /login/?next_url=/home/
    if request.method == 'POST':
    username = request.POST.get("username")
    password = request.POST.get("password")
    if username == "dream" and password == "521":
    next_url = request.GET.get('next_url')
    # print(next_url) # /home/
    obj = redirect(next_url)
    obj.set_cookie('sign', 'user')
    return obj
    else:
    return redirect('/login/')
    return render(request, 'login.html')

    def login_auth(func):
    def inner(request, *args, **kwargs):
    # print(request.path_info) # /home/
    # print(request.get_full_path()) # /home/?username=111
    next_url = request.get_full_path() # /home/
    # print(next_url)# /home/
    sign = request.COOKIES.get('sign')
    if sign and sign == 'user':
    res = func(request, *args, **kwargs)
    return res
    else:
    return redirect(f'/login/?next_url={next_url}')

      return inner
    

    @login_auth
    def home(request, *args, **kwargs):
    return HttpResponse("这是home页面")

    def home(request, *args, **kwargs):

    sign = request.COOKIES.get('sign')

    if sign and sign == 'user':

    return HttpResponse("这是home页面")

    else:

    return redirect('/login/')

    @login_auth
    def index(request, *args, **kwargs):
    return HttpResponse("这是index页面")

【3】设置过期时间

obj.set_cookie('sign', 'user', expires=3)
obj.set_cookie('sign', 'user', max_age=3)

【4】刪除cookie

def logout(request, *args, **kwargs):
    obj = redirect('/home/')
    # 设置超时时间 5s 到期
    obj.delete_cookie('sign')
    return obj

【二】Session

【1】设置session

request.session['sign'] = 'user'

【2】取值session

sign = request.session.get('sign')

def login(request, *args, **kwargs):
    # next_url = request.get_full_path()
    # print(next_url) # /login/?next_url=/home/
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        if username == "dream" and password == "521":
            # next_url = request.GET.get('next_url')
            # print(next_url) # /home/
            request.session['sign'] = 'user'
            obj = redirect('/home/')
            # 设置过期时间
            # obj.set_cookie('sign', 'user', expires=3)
            # obj.set_cookie('sign', 'user', max_age=3)
            return obj
        else:
            return redirect('/login/')
    return render(request, 'login.html')


def login_auth(func):
    def inner(request, *args, **kwargs):
        # print(request.path_info) #  /home/
        # print(request.get_full_path()) # /home/?username=111
        next_url = request.get_full_path()  # /home/
        # print(next_url)# /home/
        sign = request.session.get('sign')
        # print(sign) # user
        if sign and sign == 'user':
            res = func(request, *args, **kwargs)
            return res
        else:
            return redirect(f'/login/?next_url={next_url}')

    return inner


@login_auth
def home(request, *args, **kwargs):
    return HttpResponse("这是home页面")

【3】注意

  • session基于数据库表才能使用的
    • 必须先迁移数据库,生成 django_session 表
  • session只对当次登录有效
    • 主动清除浏览器中本地存在的session
    • 验签发现,没有sessionid就会自动生成新的session
  • django_sessoin表中的数据条数取决于浏览器
  • 同一个计算机(IP地址)上同一个浏览器只会有一条数据生效
  • 同一个计算机(IP地址)上多个浏览器会有多个数据生效
  • 当session过期的时候,可能会出现多条数据对应一个浏览器
    • 但是这些数据不会持久化存储,会被定时清理掉,可以手动清除也可以代码清除
  • 目的是为了节省服务器数据库资源

【4】session设置过期时间

            request.session['sign'] = 'user'
            # 如果是数字的话就是指定 s shu
            # request.session.set_expiry(3)
            # 0 就是关闭浏览器后自动清除浏览器的sessionid
            request.session.set_expiry(0)

【5】删除session

    # 删除session方式一
    # request.session.delete()
    # 把浏览器和数据库里面的session全部清除掉
    request.session.flush()

【三】Token

【四】CBV加装饰器的三种方法

from django.utils.decorators import method_decorator

# 方式二:放在类视图上面 (放的装饰器函数,name指定你的视图函数里面的方法)
# @method_decorator(login_auth, name='get')
# @method_decorator(login_auth, name='post')
class UserView(View):
    
    # 方式三 : dispactch 方法加装饰器 : 本视图函数内所有的视图都需要走装饰器
    @method_decorator(login_auth)
    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)
    
    # 方式一:加载视图函数上面
    # @method_decorator(login_auth)
    def get(self, request, *args, **kwargs):
        return HttpResponse("这是home页面")

    def post(self):
        ...

标签:return,request,sign,session,Cookie,home,login
From: https://www.cnblogs.com/zhangfanshixiaobai/p/17852510.html

相关文章

  • postman 出现Enable JavaScript and cookies to continue 如何反爬(js反爬)
    网页无法F12,禁止调试出现debug怎么办直接F8禁用,ctrl+F8开启调试断点网站禁止ip访问,并且关闭了icmp回包,调试最好禁用缓存,以便实时更新用postman单独访问首页的index的首页也是无法获取网页内容考虑网页使用js进行跳转实例:比如使用postman请求https://www.phind.com/简......
  • 【转载】Laravel10.x Session 储存到 Redis
    参考https://learnku.com/docs/laravel/10.x/session/14855#configurationhttps://blog.csdn.net/wen_3370/article/details/88072364注意经过测试Cache的内容默认存储到DB1经过测试Session配置为储存到Redis则默认存储到DB0环境软件/系统版本说明wi......
  • 微信小程序 在session失效时,自动重新登录
    调试程序的时候经常会碰到很长时间不去碰手机,这样小程序session失效了,但是数据还是存在。去检测一下是否失效,来决定是否需要重新登录:onCheckSessionValid(){setInterval(function(){wx.checkSession({success:function(){//session_key......
  • 请求扩展、蓝图、flask-session、数据库连接池、wtforms、flask-script、信号、flask-
    请求扩展#1before_request:请求来了会走,依次从上往下执行,但是如果其中一个返回了响应对象,后续的就不走了,视图函数也不走而来#2after_arequest:请求走了,会从下往上依次执行,它必须返回响应对象假设:写了3个before_request第二个返回了响应对象写了3个af......
  • Nginx实现Cookie的访问控制配置
    通过基于Cookie的访问控制配置,可以限制用户访问特定的页面或资源。本文将介绍如何使用Nginx来实现这样的访问控制,并给出具体的代码示例。开启Nginx的http_auth_request模块首先,需要确保Nginx已经启用了http_auth_request模块。如果没有启用,可以通过编辑Nginx配置文件添加该模块。......
  • 【Flask使用】全知识md文档,4大部分60页第3篇:状态cookie和session保持
    本文的主要内容:flask视图&路由、虚拟环境安装、路由各种定义、状态保持、cookie、session、模板基本使用、过滤器&自定义过滤器、模板代码复用:宏、继承/包含、模板中特有变量和函数、Flask-WTF表单、CSRF、数据库操作、ORM、Flask-SQLAlchemy、增删改查操作、案例、蓝图、单元测......
  • ISSCC2024 Computing-In-Memory Session 趋势整理
    ISSCC2024Computing-In-MemorySession趋势整理今天上午ISSCC2024远东区推介会,主要关注了一下Computing-In-MemorySession。CIM今年被放在了Session34,会上主持人透露CIM方向一共投稿了50篇,最后录用了9篇,算下来录用率不到20%,不得不感慨一句相当之卷。言归正题,以下是今年CIMS......
  • JavaWeb--SqlSessionFactory工具类抽取
    代码优化 Stringresource="mybatis-config.xml";InputStreaminputStream=Resources.getResourceAsStream(resource);SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(inputStream);//2.2获取SqlSession对象SqlSessionsqlSession=......
  • 请求扩展,蓝图 , flask-session,数据库连接池,wtforms ,flask-script,信号,flask-cache
    1请求扩展......
  • 通过api登录接口获得cookie,给selenium使用,绕开登录页面
    1、通过接口登录获得cookiedefget_token_cookie():test=SSO_EXAMPLE()token=test.get_session.json()['token']cookie=test.get_session.cookiesreturntoken,cookietoken,cookie=get_token_cookie()print(token)cookie_value=cookie.v......