• Django框架之Cookie和Session组件


    一、什么是 Cookie

      Cookie是服务器发送到用户浏览器并保存在本地的一小块数据,它会在浏览器下次向同一服务器再发起请求时被携带并发送到服务器上。通常,它用于告知服务端两个请求是否来自同一浏览器,如保持用户的登录状态。Cookie 使基于无状态的 HTTP 协议记录稳定的状态信息成为了可能。

    Cookie 主要用于以下三个方面:

    (1)会话状态管理(如用户登录状态、购物车、游戏分数或其它需要记录的信息)

    (2)个性化设置(如用户自定义设置、主题等)

    (3)浏览器行为跟踪(如跟踪分析用户行为等)

    Django操作Cookie

    def login(request):
        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            if username == 'jason' and password == '123':
                old_path = request.GET.get('next')
                if old_path:
                    #重定向上次访问的页面
                    obj = redirect(old_path)
                else:
                    obj = redirect('/home/')
                # 登录成功 浏览器设置cookie,
                # obj.set_cookie('name','jason',expires=7*24*3600)
                obj.set_cookie('name','jason',max_age=5)    
                return obj
        return render(request,'login.html')
    
    from functools import wraps
    def login_auth(func):        # 登录装饰器
        @wraps(func)
        def inner(request,*args,**kwargs):
            #获取当前访问路径
            old_path = request.get_full_path()
            # 校验cookie
            if request.COOKIES.get('name'):
                return func(request,*args,**kwargs)
            #在登录路径后拼接当前路径(在登录成功后可返回当前)
            return redirect('/login/?next=%s'%old_path)
        return inner
    
    
    @login_auth
    def index(request):
        # # print(request.COOKIES.get('name'))
        # if request.COOKIES.get('name'):
        return HttpResponse('我是index页面,只有登录了才能看')
    
    
    @login_auth
    def home(request):
        return HttpResponse('我是home页面,只有登录了才能看')

    二、什么是 Session

      Session 代表着服务器和客户端一次会话的过程。Session 对象存储特定用户会话所需的属性及配置信息。这样,当用户在应用程序的 Web 页之间跳转时,存储在 Session 对象中的变量将不会丢失,而是在整个用户会话中一直存在下去。当客户端关闭会话,或者 Session 超时失效时会话结束。

    Django操作Session

    获取、设置、删除Session中数据
    request.session['k1']
    request.session.get('k1',None)
    request.session['k1'] = 123
    request.session.setdefault('k1',123) # 存在则不设置
    del request.session['k1']
    删除当前会话的所有Session数据
    request.session.delete()
      
    删除当前的会话数据并删除会话的Cookie。
    request.session.flush() 
    设置会话Session和Cookie的超时时间
    request.session.set_expiry(value)
    from django.views import View
    from django.utils.decorators import method_decorator
    
    def login(request):
        if request.method =='POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            if username=='jason'and password=='123':
                            #设置session
                request.session['name'] = 'jason'
                return redirect('/home/')
        return render(request,'login.html')
    
    #基于session的登录装饰器
    from functools import wraps
    def login_auth(func):
        @wraps(func)
        def inner(request,*args,**kwargs):
            if request.session.get('name'):
                return func(request,*args,**kwargs)
            return redirect('/login/')
        return inner
    
    
    #给CBV加装饰器的三种方式
    
    # @method_decorator(login_auth,name='get')   (第一种)
    class MyCls(View):
        @method_decorator(login_auth)  (第三种)
        def dispatch(self, request, *args, **kwargs):
            super().dispatch(self, request, *args, **kwargs)
        # @method_decorator(login_auth)  (第二种)
        def get(self,request):
            return HttpResponse('get')
        def post(self,request):
            return HttpResponse('post')        
    基于session给CVB加装饰器
  • 相关阅读:
    快速了解微信小程序的使用,一个根据小程序的框架开发的 todos app
    剖析简易计算器带你入门微信小程序开发
    微信第一个“小程序”亮相:不是APP胜似APP!
    hello-weapp 微信小程序最简示例教程
    微信小程序剖析【下】:运行机制
    微信小程序「官方示例代码」浅析【上】
    微信小程序开发:Flex布局
    一个HTML5老兵坦言:我们真的需要“小程序”么?
    迅雷首席架构师刘智聪:微信小程序的架构与系统设计的几点观感
    微信小程序开发:http请求
  • 原文地址:https://www.cnblogs.com/yuanlianghong/p/11043004.html
Copyright © 2020-2023  润新知