Session

Enabling Sessions

  • INSTALLED_APPS

    INSTALLED_APPS = [
        ...
        'django.contrib.sessions',
        ...
    ]
    
  • MIDDLEWARE_CLASSES

    MIDDLEWARE_CLASSES = [
        ...
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    ]
    

Usage

  • Get

    def xxx(request):
        request.session.get('key', 'default_value')
    
  • Set

    def xxx(request):
        request.session['key'] = 'value'
    
  • Delete

    def xxx(request):
        try:
            del request.session['key']
        except KeyError:
            pass
    
  • Exists

    def xxx(request):
        if 'key' in request.session:
            xxx
    
  • Clear Session Store

    # Can be run as a cron job or directly to clean out expired sessions.
    python manage.py clearsessions
    

Session Engine

# The module to store session data
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
  • Store in Table django_session

    mysql> select * from django_session order by expire_date desc limit 1\G;
    *************************** 1. row ***************************
     session_key: s5i6dgry7gcaprja6geltrkx24yqo5wq
    session_data: NzE3NDA5MmFlMDE4MjY5MGU0Yzc5M2UyODVmZmU0ZWVlM2E4ODk4Njp7ImFjY291bnRfaWQiOiJ2RmVmV1JyZVFINUZTellkUm1Rc21nIn0=
     expire_date: 2016-06-17 05:38:31.344553
    
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
  • Session Position in Chrome

SESSION_SAVE_EVERY_REQUEST

# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
  • If you want to realize function of modifying user not active when he doesn't request for a period of time. You can set SESSION_SAVE_EVERY_REQUEST to be True.
  • Source Code
    if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
    
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
  • The HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security.

  • SESSION_COOKIE_HTTPONLY = True

    > document.cookie
    < ""
    
  • SESSION_COOKIE_HTTPONLY = False

    > document.cookie
    < "sessionid=bsq81sh73ttp1bag3perofkyvsmrh29j"
    

Auth

from django.contrib.auth import authenticate, login, logout
  • To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework.
  • When you call logout(), the session data for the current request is completely cleaned out.

Global Settings

############
# SESSIONS #
############

# Cache to store session data if using the cache session backend.
SESSION_CACHE_ALIAS = 'default'
# Cookie name. This can be whatever you want.
SESSION_COOKIE_NAME = 'sessionid'
# Age of cookie, in seconds (default: 2 weeks).
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# A string like ".example.com", or None for standard domain cookie.
SESSION_COOKIE_DOMAIN = None
# Whether the session cookie should be secure (https:// only).
SESSION_COOKIE_SECURE = False
# The path of the session cookie.
SESSION_COOKIE_PATH = '/'
# Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
# Whether to save the session data on every request.
SESSION_SAVE_EVERY_REQUEST = False
# Whether a user's session cookie expires when the Web browser is closed.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# The module to store session data
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
# Directory to store session files if using the file session module. If None,
# the backend will use a sensible default.
SESSION_FILE_PATH = None
# class to serialize session data
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'

References

[1] Docs@DjangoProject, How to use sessions

[2] Docs@DjangoProject, Settings for django.contrib.sessions.

[3] Django@Github, Django Global Settings

[4] MDN, Document.cookie

results matching ""

    No results matching ""