有时候请求.session.session_key是非

2024-06-26 17:54:43 发布

您现在位置:Python中文网/ 问答频道 /正文

当从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_idNone

所以,在调试之后(我在return JsonResponse(...)行设置断点),我看到当我到达断点时,request.session._session_keyNone,但是request.session.session_keyu'j4lhxe8lvk7j4v5cmkfzytyn5235chf1',并且session_id也是None

有人知道怎么会这样吗?为什么在返回响应之前将session_key的值分配给session_id时没有设置?


Tags: keynoneidforifisrequestsession
3条回答

根据约翰的建议。

我通过这个片段修复了这个问题:

if not request.session.session_key:
    request.session.save()
session_id = request.session.session_key

如果request.session.session_key为None,则表示会话对象是全新的,尚未保存到数据库。调用request.session.save()应该填充该属性。–John Gordon 2016年8月27日15:36

根据documentation

SessionStore.create() is designed to create a new session (i.e. one not loaded from the session store and with session_key=None). save() is designed to save an existing session (i.e. one loaded from the session store). Calling save() on a new session may also work but has a small chance of generating a session_key that collides with an existing one. create() calls save() and loops until an unused session_key is generated.

意味着使用create()而不是save()更安全。所以你可以这样尝试:

if not request.session.session_key:
    request.session.create()
session_id = request.session.session_key

相关问题 更多 >