当从request.session
获取会话密钥时遇到问题。
我使用Django1.8和Python2.7.10来设置RESTful服务。
以下是我的登录视图片段:
user = authenticate(username=userName, password=passWord)
if user is not None:
# the password verified for the user
if user.is_active:
# app_logger.debug("User is valid, active and authenticated")
if hasattr(user, 'parent') :
login(request, user)
request.session['ut'] = 4
# user type 1 means admin, 2 for teacher, 3 for student, 4 for parents
request.session['uid'] = user.id
description = request.POST.get('description','')
request.session['realname'] = user.parent.realname
request.session['pid'] = user.parent.id
devicemanage.update_user_device(devicetoken, user.id, ostype, description)
children = parentmanage.get_children_info(user.parent.id)
session_id = request.session.session_key
user.parent.login_status = True
user.parent.save()
return JsonResponse({'retcode': 0,'notify_setting':{'receive_notify':user.parent.receive_notify,'notify_with_sound':user.parent.notify_with_sound,'notify_sound':user.parent.notify_sound,'notify_shake':user.parent.notify_shake},'pid':user.parent.id,'children':children,'name':user.parent.realname,'sessionid':session_id,'avatar':user.parent.avatar,'coins':user.parent.coins})
现在,当调用这个函数时,我看到响应中有时session_id
是None
。
所以,在调试之后(我在return JsonResponse(...)
行设置断点),我看到当我到达断点时,request.session._session_key
是None
,但是request.session.session_key
是u'j4lhxe8lvk7j4v5cmkfzytyn5235chf1'
,并且session_id
也是None
。
有人知道怎么会这样吗?为什么在返回响应之前将session_key
的值分配给session_id
时没有设置?
根据约翰的建议。
我通过这个片段修复了这个问题:
如果request.session.session_key为None,则表示会话对象是全新的,尚未保存到数据库。调用request.session.save()应该填充该属性。–John Gordon 2016年8月27日15:36
根据documentation:
意味着使用
create()
而不是save()
更安全。所以你可以这样尝试:相关问题 更多 >
编程相关推荐