I apologize if my question is very similar to this one , and my approach to solving the problem is 100% based on the answers to this question, but I think it is a little more involved and can target the part of Django that I do not quite understand.
I have a CMS system written in Django 1.5, with several APIs available by two desktop applications that cannot use cookies as a browser.
I noticed that every time an API call is made by one of the applications (once every 3 seconds), a new record is added to the django_session table. By carefully studying this table and code, I see that for all entries for a particular URL, the same session_data value is set, but a different session_key . This is probably due to the fact that Django determines that when one of these calls is made from an application without cookies, request.session._session_key is set to None .
The result of this is that thousands of records are created every day in the django_session table and just running ./manage clearsessions , using a daily cron, does not delete them from this table, making the entire database quite large, without obvious benefit. Note that I even tried set_expiry(1) for these queries, but ./manage clearsessions still doesn't get rid of them.
To overcome this problem with Django, I had to override 3 Django middlewares since I use SessionMiddleware, AuthenticationMiddleware and MessageMiddleware:
from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.messages.middleware import MessageMiddleware class MySessionMiddleware(SessionMiddleware): def process_request(self, request): if ignore_these_requests(request): return super(MySessionMiddleware, self).process_request(request) def process_response(self, request, response): if ignore_these_requests(request): return response return super(MySessionMiddleware, self).process_response(request, response) class MyAuthenticationMiddleware(AuthenticationMiddleware): def process_request(self, request): if ignore_these_requests(request): return super(MyAuthenticationMiddleware, self).process_request(request) class MyMessageMiddleware(MessageMiddleware): def process_request(self, request): if ignore_these_requests(request): return super(MyMessageMiddleware, self).process_request(request) def ignore_these_requests(request): if request.POST and request.path.startswith('/api/url1/'): return True elif request.path.startswith('/api/url2/'): return True return False
Although the above works, I canβt stop thinking that I may have made it more complicated, that it really is, and that this is not the most efficient approach, since 4 additional checks have been done for each individual request.
Are there any better ways to do this in Django? Any suggestions would be greatly appreciated.