有时request.session.session_key为None [英] Sometimes request.session.session_key is None

查看:457
本文介绍了有时request.session.session_key为None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

request.session 获取session_key时遇到问题。

I hit a problem when get session_key from request.session.

我正在使用Django1.8和Python2.7.10来建立RESTful服务。

I am using Django1.8 and Python2.7.10 to set up a RESTful service.

以下是我的登录视图的片段:

Here is snippet of my login view:

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

Now when this function is called, I see sometimes session_id is None within the response.

因此,在调试之后(我在 return JsonResponse(...)行中设置了断点),我看到当我在 request.session._session_key None ,但是 request.session.session_key u'j4lhxe8lvk7j4v5cmkfzytyn5235chf1' session_id 也是 None

So, after debugging (I set breakpoint at the return JsonResponse(...) line), I see that when I hit the breakpoint the request.session._session_key is None, but request.session.session_key is u'j4lhxe8lvk7j4v5cmkfzytyn5235chf1' and session_id is also None.

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

Does anyone know how can this happen? Why isn't the value of session_key set when assigning it to session_id before returning the response?

推荐答案

根据约翰的建议。

我通过以下代码片段解决了这个问题:

I fixed the problem by this snippet:

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

这篇关于有时request.session.session_key为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆