Login

Remember path decorator

Author:
robhudson
Posted:
December 9, 2009
Language:
Python
Version:
1.1
Tags:
session decorator
Score:
0 (after 0 ratings)

Decorator that stores the request.path URL in a session variable to be used later, e.g. in a "Continue Shopping" link on a cart page. Wrap and view that you want to be able to link back to easily. When those views are called, it updates the session with the current request.path value. This can be pulled back out of the session whenever you need to provide a link back from whence the user came.

 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
# decorators.py

try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.

def remember_path(view_func):
    """
    Decorator that stores the `request.path` URL in a session variable 
    to be used later, e.g. in a "Continue Shopping" link on a cart page.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        request.session['last_path'] = request.path
        return view_func(request, *args, **kwargs)
    return wraps(view_func)(_wrapped_view_func)

# views.py example to remember path

@remember_path
def shopping_view(request):
    # regular view code

# views.py example to use path

def cart_view(request):
    # view code
    return render_to_response('template.html', {
        'last_path': request.session.get('last_path', '/'),
        # other context
    })

More like this

  1. Cookieless Session Decorator by achimnol 5 years, 7 months ago
  2. Workaround Firefox bug 553888 by peroksid 4 years ago
  3. Simple Age Verification Middleware by eculver 5 years, 8 months ago
  4. Class-based view mixin for flatpages by schwuk 2 years, 1 month ago
  5. View Redirect Decorators by bryanpieper 4 years, 8 months ago

Comments

buriy (on December 9, 2009):

why it needs to be a decorator?

why not simple:

def shopping_view(request):
    remember_session(request)

#

carljm (on December 10, 2009):

I wrote something almost identical to this for one of my projects, but backed it out after only a week or so in use. It tends to really wreak havoc with any kind of multiple-tabs workflow someone might be using on your site. Embrace statelessness :-)

#

robhudson (on December 13, 2009):

@carljm: Someone did bring the multiple tabs problem to my attention, and it's a good caveat to put on this.

#

Please login first before commenting.