Wednesday, December 19, 2012

Chapter 14 Sessions, Users, and Registration

Do not Use Cookie

Enabling Sessions



  1. Edit your MIDDLEWARE_CLASSES setting and make sure MIDDLEWARE_CLASSES contains'django.contrib.sessions.middleware.SessionMiddleware'.
  2. Make sure 'django.contrib.sessions' is in your INSTALLED_APPS setting (and run manage.py syncdb if you have to add it).
(by default, all are open)

Using Sessions in Views




each HttpRequest object – the first argument to any Django view function – will have a session attribute, which is a dictionary-like object.
View Function
# Set a session value:
request.session["fav_color"] = "blue"

# Get a session value -- this could be called in a different view,
# or many requests later (or both):
fav_color = request.session["fav_color"]

# Clear an item from the session:
del request.session["fav_color"]

# Check if the session has a given key:
if "fav_color" in request.session:
    ...

  • Use normal Python strings as dictionary keys on request.session (as opposed to integers, objects, etc.).
  • Session dictionary keys that begin with an underscore are reserved for internal use by Django. 


Easy but unsafe:

def post_comment(request):
    if request.method != 'POST':
        raise Http404('Only POSTs are allowed')

    if 'comment' not in request.POST: #key in dictionary
        raise Http404('Comment not submitted')

    if request.session.get('has_commented', False): #avoid KeyError
        return HttpResponse("You've already commented.")

    c = comments.Comment(comment=request.POST['comment'])
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')


Using Sessions Outside of Views




>>> from django.contrib.sessions.models import Session
>>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
>>> s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)


>>> s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
>>> s.get_decoded()
{'user_id': 42}

When Sessions Are Saved

# Session is modified.
request.session['foo'] = 'bar'

# Session is modified.
del request.session['foo']

# Session is modified.
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'

directly write in settings.py
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True

done


done

No comments:

Post a Comment