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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.