0

I'd like to add a 'Last seen' url list to a project, so that last 5 articles requested by users can be displayed in the list to all users. I've read the middleware docs but could not figure out how to use it in my case. What I need is a simple working example of a middleware that captures the requests so that they can be saved and reused.

Jand
  • 2,527
  • 12
  • 36
  • 66
  • Why do you want to do this in middleware? I am not sure it is the best place. – albar Oct 13 '15 at 12:45
  • @albar I'm open to all suggestions to do the task. Actually I prefer a view, as I'm not familiar with middleware writing. – Jand Oct 13 '15 at 13:18

1 Answers1

1

Hmm, don't know if I would do it with middleware, or right a decorator. But as your question is about Middleware, here my example:

class ViewLoggerMiddleware(object):
    def process_response(self, request, response):
        # We only want to save successful responses
        if response.status_code not in [200, 302]:
            return response

        ViewLogger.objects.create(user_id=request.user.id, 
            view_url=request.get_full_path(), timestamp=timezone.now())

Showing Top 5 would be something like;

ViewLogger.objects.filter(user_id=request.user.id).order_by("-timestamp")[:5]

Note: Code is not tested, I'm not sure if status_code is a real attribute of response. Also, you could change your list of valid status codes.

Blackeagle52
  • 1,956
  • 17
  • 16
  • Thanks for your solution. However this one has the problem that logs all request, including request to urls that I don't want to save. I just want to limit to request to certain content (e.g.`/articles/*` and `/posts/*`). How would you do it without middleware? – Jand Oct 13 '15 at 13:22
  • 1
    As I said, you could right your own decorator function, and place it above fuctions you want to monitor. An other "simple" option is to add an extra if to the middleware `if "/articles/" in request.path`. – Blackeagle52 Oct 13 '15 at 14:04