Sessions In Django-Free Django Tutorials

For anonymous sessions,django provides full support.On the per-site-visitor basis,django session framework will allow you to store and retrieve arbitrary data.The django session framework will stores the data on the server side and will abstracts the sending and receiving of cookies. Cookies will use the data itself,instead of a session ID.

Enabling sessions

In django with the help of middleware,sessions are implemented.To enable the session functionality in your project,you can follow the following steps:

  • Make sure that the MIDDLEWARE part in the settings.py of your project must contains  ‘djnago.contrib.sessions.middleware.SessionMiddleware‘ .The default settings.py created when you type django-admin startproject    will have SessionMiddleware activated.

You can remove the SessionMiddleware line from MIDDLEWARE and'django.contrib.sessions' from your INSTALLED_APPS if you don’t want to use sessions in your project.

Configuring the session engine

Django will store the sessions in our database by default,with the help of model django.contrib.sessions.models.Session. This storing the session with the help of models is a convenient,but in some situation’s it’s faster to store session data elsewhere.So Django can be configured for that to store the data in your file system.

Using database-backed sessions

By adding django.contrib.sessions in the INSTALLED_APPS settings, you can use a database-backed session.Once you are done with configuration of your installation’s,then you can run python manage.py runserver to install the single database that stores session data.

Using cached sessions

You can use cache-based session backend for better performance.You have to first configure your cache,to store session data using django’s cache system. Djnago will use the default cache,if you have defined multiple caches in CACHES.To use another cache in your django project you can set SESSION_CACHE_ALIAS to the name of that cache.

Using file-based sessions

By setting SESSION_ENGINE in the settings to ‘django.contrib.sessions.backends.file‘, you can use file-based sessions.

Using cookie-based sessions

By setting SESSION_ENGINE in the settings to ‘django.contrib.sessions.backends.signed_cookies‘, you can use cookies-based sessions.

Using sessions in views

Each HttpRequest object which is the first argument to any django view function will have a session attribute if SessionMiddleware is activated.

Session serialization

Django will handle the serialization of data using JSON by default.To customize the session serialization format you can use the SESSION_SERIALIZER

Session object guidelines

This are the few guidelines for session objects.

  • You can use the normal python strings as dictionary keys on request.session, which is more convenient.
  • In Django  session dictionary keys that begin with an underscore are reserved for internal use.

Examples

For example,in the below simple view,we are setting a has_commented to True after a user posts a comment.This view will not allow user to comment for more than one time.

def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

This view will allow member to login into system:

def login(request):
    m = Member.objects.get(username=request.POST['username'])
    if m.password == request.POST['password']:
        request.session['member_id'] = m.id
        return HttpResponse("You're logged in.")
    else:
        return HttpResponse("Your username and password didn't match.")

…And this one view will logout the user from system.

def logout(request):
    try:
        del request.session['member_id']
    except KeyError:
        pass
    return HttpResponse("You're logged out.")

This is all about  session in django.

Leave a Comment

Your email address will not be published. Required fields are marked *