Login

RequestStack middleware

Author:
simonbun
Posted:
April 27, 2007
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

This is some very simple middleware that keeps track of the last 3 succesful requests for each visitor. This can be useful if you want to redirect the visitor to a previous path without relying on a hidden field in a form, or if you simply want to check if a visitor has recently visited a certain path.

Note that this relies on the session framework and visitors actually accepting cookies.

This can be easily modified to hold more requests if you have a need for it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class RequestStackMiddleware(object):
    '''
    Keeps track of the last 3 succesful requests
    '''
    def process_response(self, request, response):
        if 'requeststack' not in request.session:
            request.session['requeststack'] = ['/', '/', request.path]
        else:
            if request.method == 'GET' and 'text/html' in response.headers['Content-Type']:
                stack = request.session['requeststack']
                stack = stack[1:] # remove the first item
                stack.append(request.path)
                request.session['requeststack'] = stack
        
        return response

In a view:
    return HttpResponseRedirect(request.session['requeststack'][-1]) # or -2 or -3

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.