一、Session的概念

  • cookie是在浏览器端保存键值对数据,而session是在服务器端保存键值对数据
  • session 的使用依赖 cookie:在使用Session后,会在Cookie中存储一个sessionid的数据,每次请求时浏览器都会将这个数据发给服务器,服务器在接收到sessionid后,会根据这个值找出这个请求者的Session。

二、Django中session的使用

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
  • session键值对数据保存

Django下关于session的使用 Python 第1张

 

 

 

  • session数据默认保存在django项目的一张数据库表中(表名为:django_session),保存格式如下:

Django下关于session的使用 Python 第2张

 

 

 三、数据操作:

  • 以键值对的格式写session
request.session['键']=值
  • 根据键读取值
request.session.get('键',默认值)
# 或者
request.session['键']
  • 清除所有session,在存储中删除值的部分 
request.session.clear()
  • 清除session数据,在存储中删除session的整条数据
request.session.flush()
  • 删除session中的指定键及值,在存储中只删除某个键及对应的值
del request.session['键']
  • 设置session数据有效时间; 如果不设置,默认过期时间为两周
request.session.set_expiry(value)
  1. 如果value是一个整数,则 session数据 将在value秒没有活动后过期。
  2. 如果value为None,那么会话永不过期。
  3. 如果value为0,那么用户会话的Cookie将在用户的浏览器关闭时过期。

四、以下是使用例子:

# 发短信接口
def sms_send(request):
    # http://localhost:8000/duanxin/duanxin/sms_send/?phone=18434288349
    # 1 获取手机号
    phone = request.GET.get('phone')
    # 2 生成6位验证码
    code = aliyunsms.get_code(6, False)
    # 3 缓存到Redis
    #cache.set(phone,code,60) #60s有效期
    #print('判断缓存中是否有:',cache.has_key(phone))
    #print('获取Redis验证码:',cache.get(phone))

    #暂时用session处理
    request.session['phone'] = code
    request.session.set_expiry(300) #设置5分钟后过期
    print('判断缓存中是否有:', request.session.get('phone'))
    print('获取session验证码:',request.session.get('phone'))
    # 4 发短信
    result = aliyunsms.send_sms(phone, code)
    return HttpResponse(result)


# 短信验证码校验
def sms_check(request):
    # /duanxin/sms_check/?phone=xxx&code=xxx
    # 1. 电话和手动输入的验证码
    phone = request.GET.get('phone')
    code = request.GET.get('code')
    # 2. 获取redis中保存的code
    #print('缓存中是否包含:',cache.has_key(phone))
    #print('取值:',cache.get(phone))
    #cache_code = cache.get(phone)
    #获取session里的code
    print('取值:', request.session.get('phone'))
    cache_code = request.session.get('phone')

    # 3. 判断
    if code == cache_code:
        return HttpResponse(json.dumps({'result':'OK'}))
    else:
        return HttpResponse(json.dumps({'result':'False'}))

  

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄