I've been lucky enough to have spent this week attending Jacob Kaplan-Moss's Django Training. I can't say enough how useful this week has been! Especially useful have been the sections on unit tests, generic views, session management and caching. Jacob is very knowledgeable about real-world Django development, as he is one of the co-creators of the popular framework, but in the former sections he really shone as an instructor.
One of the topics we covered a bit later in the week was middleware, which in the Django usage is somewhat of a misnomer. Middleware in Django allows you to pre-process requests, post-process responses, and handle exceptions. My co-worker Eric has a great example of how to use exception middleware. To exemplify the use of middleware, Jacob showed a slide taken from Django snippets, showing a middleware class that stores the last page visited and the current page in the session. This can be useful for breadcrumbs / "back" links, as well as redirecting after performing action such as logging in / out.
The original code:
class LastVisitedMiddleware(object):
"""This middleware sets the last visited url as session field"""
def process_request(self, request):
"""Intercept the request and add the current path to it"""
request_path = request.get_full_path()
try:
request.session['last_visited'] = request.session['currently_visiting']
except KeyError:
# silence the exception - this is the users first request
pass
request.session['currently_visiting'] = request_path
Since I am running on a local machine and don't have a separate server for media files (.css, .js, images) I needed a way to make sure that these requests did not get stored in the session as the 'last visited' page. Here's how I blocked them:
import os
class LastVisitedMiddleware(object):
def process_request(self, request):
current_request = request.get_full_path()
if '.' not in os.path.split(current_request)[1]:
last = request.session.get("currently_visiting", None)
request.session['last_visited'] = last
request.session['currently_visiting'] = request.get_full_path()
Comments (0)
Commenting has been disabled for this entry
