如何在Django中使用session?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
一、Session的概念
cookie是在浏览器端保存键值对数据,而session是在服务器端保存键值对数据
session 的使用依赖 cookie:在使用Session后,会在Cookie中存储一个sessionid的数据,每次请求时浏览器都会将这个数据发给服务器,服务器在接收到sessionid后,会根据这个值找出这个请求者的Session。
二、Django中session的使用
session键值对数据保存
session数据默认保存在django项目的一张数据库表中(表名为:django_session),保存格式如下:
三、数据操作:
以键值对的格式写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)
如果value是一个整数,则 session数据 将在value秒没有活动后过期。
如果value为None,那么会话永不过期。
如果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'}))
关于如何在Django中使用session问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。