Sometimes request.session.session_key is None

前端 未结 3 461
北恋
北恋 2021-01-04 09:56

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

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

Here is snippet of

相关标签:
3条回答
  • 2021-01-04 10:13

    According to John's suggestion.

    I fixed the problem by this snippet:

    if not request.session.session_key:
        request.session.save()
    session_id = request.session.session_key
    
    0 讨论(0)
  • 2021-01-04 10:17

    If request.session.session_key is None, that means the session object is brand-new and hasn't been saved to the db yet. Calling request.session.save() should populate that attribute. – John Gordon Aug 27 '16 at 15:36

    0 讨论(0)
  • 2021-01-04 10:22

    As per 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.

    Means it is safer to use create() instead of save(). So you can try like this:

    if not request.session.session_key:
        request.session.create()
    session_id = request.session.session_key
    
    0 讨论(0)
提交回复
热议问题