[Django]-Disable session creation in Django

23👍

A trivial solution to this is to have your webserver distinguish between API calls and regular calls, then have two different WSGI instances of your application: one with sessions enabled, the other with sessions disabled. (This is probably much easier with Nginx than with Apache.)

An alternative is to inherit SessionMiddleware and then edit the process functions to ignore all requests matching your criteria. Something like:

from django.contrib.sessions.middleware import SessionMiddleware

class MySessionMiddleware(SessionMiddleware):
    def process_request(self, request):
        if request.path_info[0:5] == '/api/':
            return
        super(MySessionMiddleware, self).process_request(request)

    def process_response(self, request, response):
        if request.path_info[0:5] == '/api/':
            return response
        return super(MySessionMiddleware, self).process_response(request, response)

And then edit your setting’s file so that MIDDLEWARE_CLASSES contains the path to “MySessionMiddleware” and not ‘django.contrib.sessions.middleware.SessionMiddleware’.

4👍

I upvoted the accepted answer, but note that you can also use the decorator_from_middleware method to selectively enable middleware on a per-view basis. See the StackOverflow answers to Non-global middleware in Django for more details.

👤vinod

2👍

It is also possible in custom middleware, or anywhere else for that matter, to just override request.session.save method before the response is processed in SessionMiddleware, where the method is called.

request.session.save = lambda: None

Trivial, does work.

The benefit of this approach, though it is de-facto a hack, is that the session object is still accessible and can be used the usual way without need for any further changes in the code.

Leave a comment