1024programmer Java How to use Session in the view of Python’s Django framework

How to use Session in the view of Python’s Django framework

After SessionMiddleware is activated, each “HttpRequest“ object passed as the first parameter to the view function has a session attribute, which is a lexicon object. You can use it like a normal dictionary. For example, in a view you can use:

 # 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:


Other mapping methods such as keys() and items() are also valid for request.session:

Here are some simple rules for using Django sessions effectively:

Access the dictionary request.session using normal strings as keys, not integers, objects, or anything else.

The key values ​​starting with an underscore in the Session dictionary are Django internal reserved key values. The framework will only use a few session variables starting with an underscore. Unless you know their specific meanings and are willing to keep up with Django changes, it is best not to use these variables starting with an underscore. They will make Django mess up your application.

For example, don’t use the “_fav_color“ session key like this:

 request.session['_fav_color'] = 'blue' # Don't do this!


Do not replace request.session with a new object, and do not access its properties. Can be used like a dictionary in Python. For example:

 request.session = some_other_object # Don't do this!

 request.session.foo = 'bar' # Don't do this!


Let’s look at a simple example. This is a simple example: set has_commented to True after the user posts a comment. This is a simple (but not very secure) way to prevent users from commenting multiple times.

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

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

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

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


The following is a very simple site login view:

 def login(request):
  if request.method != 'POST':
   raise Http404('Only POSTs are allowed')
   m = Member.objects.get(username=request.POST['username'])
   if m.password == request.POST['password']:
    request.session['member_id'] = m.id
    return HttpResponseRedirect('/you-are-logged-in/')
  except Member.DoesNotExist:
   return HttpResponse("Your username and password didn't match.")


The following example will log out a user who has logged in via “login()“ above:

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



In practice, this is a poor way to log in users, and the authentication framework discussed later will help you handle these problems in a more robust and advantageous way. These very simple examples are just to give you an idea of ​​how this all works. Keep these examples simple so you can more easily see what’s going on

As mentioned earlier, you cannot expect all browsers to accept COOKIES. Therefore, for ease of use, Django provides a simple method to test whether the user’s browser accepts COOKIE. You simply call request.session.set_test_COOKIE() in a view and check for request.session.test_COOKIE_worked() in subsequent views, not the current view.

Although it may seem awkward to separate set_test_COOKIE() and test_COOKIE_worked(), it is unavoidable due to the way COOKIE works. When setting a COOKIE, you can only know whether the browser accepts the COOKIE until the next time the browser accesses it.

After checking whether the COOKIE can work properly, you have to use delete_test_COOKIE() to clear it yourself. This is a good habit. Do this after you have verified that the test cookie is working.

This is a typical example:

 def login(request):

  # If we submitted the form...
  if request.method == 'POST':

   # Check that the test COOKIE worked (we set it below):
   if request.session.test_COOKIE_worked():

    # The test COOKIE worked, so delete it.

    # In practice, we'd need some logic to check username/password
    # here, but since this is an example...
    return HttpResponse("You're logged in.")

   # The test COOKIE failed, so display an error message. If this
   # were a real site, we'd want to display a friendlier message.
    return HttpResponse("Please enable COOKIES and try again.")

  # If we didn't post, send the test COOKIE along with the login form.
  return render_to_response('foo/login_form.html')



Again, the built-in authentication function will do the checking for you.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/787624

author: admin

Previous article
Next article

Leave a Reply

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

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top