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. Form field with fixed value by roam 2 weeks, 2 days ago
  2. New Snippet! by Antoliny0919 3 weeks, 1 day ago
  3. Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months, 1 week ago
  4. get_object_or_none by azwdevops 7 months ago
  5. Mask sensitive data from logger by agusmakmun 8 months, 4 weeks ago

Comments

Please login first before commenting.