1

I want to count visits on my website. My idea is to use cookies and set time out on it. If there is no request during an hour (for example) and then there is a request I will count it as a new visit. Is there a way to intercept every request in Django without repeating my code in each view function?

user8142488
  • 11
  • 1
  • 5
  • 1
    Yes, with middleware. But why reinvent the wheel, and not use something like *Google Analytics* instead? – Willem Van Onsem Jul 27 '18 at 14:47
  • I would not like to use neither google analytics nor django. Why not formatting appropriately the server logs, grep through them and save the results in the database? – raratiru Jul 27 '18 at 15:02
  • 1
    @WillemVanOnsem you are right but I want to create my own and as django newbie it will help me to learn something – user8142488 Jul 27 '18 at 15:21
  • @raratiru: because that was exactly why developers moved to *Google Analytics*, because grepping the log was cumbersome, and not that informative. – Willem Van Onsem Jul 27 '18 at 16:27
  • @WillemVanOnsem No problem with that, but GDPR has put another thought on enabling cookies if someone can get away with an easier way out. Of course, reinventing the wheel is not an option! – raratiru Jul 28 '18 at 20:45

1 Answers1

3

Yes you can use Django middleware
For instance: I would create a file named my_middleware.py in an app named my_app and create a function as defined in Django's website

def StatisticsMiddleware(get_response):
    def middleware(request):

        # Code to be executed for each request/response after
        # the view is called.

        return response #response should be defined before

    return middleware

And add the middleware in your settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ......
    ......
    'my_app.my_middleware.StatisticsMiddleware' #here your middleware
]

Do not forget to save the result in the database. You can create a model and use cookies. So if your condition is ok then save into database
To set cookies:

response = get_response(request)
response.set_cookie('name_of_cookie', 'info_inside_the_cookie', 
    max_age=age_of_the_cookie)

For more details https://docs.djangoproject.com/en/2.0/topics/http/middleware/

Wariored
  • 1,303
  • 14
  • 25