Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Sessions (Shopping Carts) in Django - the Python Web Framework

What are sessions?

When you're running a web application, you need to be able to enter data page by page on your way through, and have that data retained - on a shopping site, for example, you need to be able to add things into your basket page by page and have them stay there until you check out. But, alas, HTML / http are stateless protocols which don't retain your connection from page to page, and data will be lost unless you take specific action.

A cookie can be sent as part of the response when you call up a web page, and that will then subsequently be sent back to the server as part of subsequent responses from the same browser to the same server. In essence, the cookie sent back is like an ID card saying "It's me again". And from that information, the server can look up the history of what's gone before.

"Don't Repeat Yourself" ... DRY. So many requirements want to store data from page to page that the Django session classes and objects do all the hard work under the covers for you. The first time you visit a Django web site that uses this technology from your browser, a cookie is sent out with a unique value. That cookie is returned by the browser on each subsequent visit. And (the clever bit) anything that your view controller has stored within your request.session object is stored to a file or database at the end of each running of the controller script, and is read back at the start of the subsequent invocation. As there is a different session ID / database record / temporary file for each browser / user, this approach cleverly allows multple users to be running your application at the same time - with their data being cleanly passed on from page to page, but the data for the various different users being kept apart.

How do we turn on sessions in Django?

In Setting.py - check following (on 1.3.1 , they're turned on at installation by default)
* MIDDLEWARE to contain
* INSTALLED_APPS to contain

If either is new, you'll need to add the database:

  munchkin:training grahamellis$ python manage.py syncdb
  Creating tables ...
  Installing custom SQL ...
  Installing indexes ...
  No fixtures found.
  munchkin:training grahamellis$

To the form demonstration in the previous section ([here]), I've added a feature which stores the data that's been added by each user within their session. Here are the three extra lines of code which create a new member in the request.session 'dict' if necessary, and add the new information to it before storing it away again:
  adding = request.session.get("newroles","")
  adding += form.cleaned_data['role'] + " " + str(form.cleaned_data['count']) + "<br />"
  request.session["newroles"] = adding

In order to make use of those in my demonstration, I have added the entire session contents back into the status report on the output - very much a training example to teach you what's happening:
  myHistory = ""
  for retained_key in request.session.keys():
    myHistory += retained_key + " -> " + str(request.session[retained_key]) + "<br />"
  havesubmission += "<br /><br />History ...<br />" + myHistory

Since I've added HTML tags into the report string (rather than making a lot of template changes), I've added the |safe filter into the template:
  <b>{{ status|safe }}</b><br /><br />
but you should note that this is a demonstration only which could leave me open to HTML / JavaScript injections.

Testing with multiple sessions at the same time

A good way to test that your sessions are working is to run your test webserver on a network IP address, which you can do from within manage.py. Here is such a run:

  munchkin:training grahamellis$ python manage.py runserver
  Validating models...
  0 errors found
  Django version 1.3.1, using settings 'training.settings'
  Development server is running at
  Quit the server with CONTROL-C.
  [05/Mar/2012 09:44:28] "GET /team/ HTTP/1.1" 200 286
  [05/Mar/2012 09:44:44] "GET /team/formdemo.html HTTP/1.1" 200 571
  [05/Mar/2012 09:45:14] "POST /team/formdemo.html HTTP/1.1" 200 640
  [05/Mar/2012 09:45:31] "POST /team/formdemo.html HTTP/1.1" 200 663
  [05/Mar/2012 09:46:14] "GET /team/formdemo.html HTTP/1.1" 200 571
  [05/Mar/2012 09:46:42] "POST /team/formdemo.html HTTP/1.1" 200 634
  [05/Mar/2012 09:46:47] "POST /team/formdemo.html HTTP/1.1" 200 740

The illustration above shows one user session (which happens to be using Firefox). The illustrtation beside this paragraph shows a session that was live at the same time, and happens to be using Safari. You'll note that although it's the same application, the user data is completely different.

Sessions and cookies are very flexible - in this first example we used the default (database) storage medium, but we can also use plain text files and even memory based caching systems. The time that a session is to live when a user leaves the site is under configuration control, and you also need to ensure that you know what will happen in tidying up the database. Finally, you need to check that sessions are destroyed within the application where appropriate, to avoid users accidentally double ordering through incorrect use of the back button.

There's a complete set of files showing the above code and changes in context [here] on our web site.
(written 2012-03-05, updated 2012-03-10)

Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Y306 - Python - The Django web framework
  [1745] Moodle, Drupal, Django (and Rails) - (2008-08-08)
  [3136] A framework with python - Django - first steps - (2011-01-17)
  [3138] Django - adding your own views, and then templating your views. - (2011-01-18)
  [3139] Steering our Python courses towards wxPython, SQLite and Django - (2011-01-19)
  [3140] Django - separating the HTML from the view / model - (2011-01-20)
  [3624] Why do we need a Model, View, Controller architecture? - (2012-02-25)
  [3633] Nesting Templates in Django - (2012-03-02)
  [3634] Defining database relations in your Django model - (2012-03-02)
  [3639] Demonstration of a form using Django - (2012-03-04)
  [3698] How to stop forms on other sites submitting to your scripts - (2012-04-15)
  [3705] Django Training Courses - UK - (2012-04-23)
  [3919] What is a web framework? - (2012-11-10)
  [4013] Web Frameworks - nested templates - (2013-02-22)
  [4095] Django - first steps - Updated - (2013-05-19)

Back to
Demonstration of a form using Django
Previous and next
Horse's mouth home
Forward to
Swindon to Trowbridge - transport and travel options
Some other Articles
The way of the Prioress - Melksham history pictured today
Hotel food, Melksham - enjoy the variety of the American way
Wiltshire Travel Times - Chippenham, Trowbridge, Salisbury and other places too
Swindon to Trowbridge - transport and travel options
Sessions (Shopping Carts) in Django - the Python Web Framework
Sorting dicts and arrays in Tcl
April, May and June 2012 - Public Open Source Programming Courses
Best tenner I ever spent?
Parse error: parse error, unexpected T_STRING on brand new web site - why?
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page

This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3640_Ses ... ework.html • PAGE BUILT: Sun Oct 11 16:07:41 2020 • BUILD SYSTEM: JelliaJamb