Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable session creation in Django

Tags:

I'm looking to disable the automatic session creation in Django for certain URLs. I have /api/* and each client that hits that gets a new Django session. Is there a way to ignore certain urls?

like image 277
Mike Avatar asked Oct 29 '10 13:10

Mike


3 Answers

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'.

like image 165
Elf Sternberg Avatar answered Nov 07 '22 05:11

Elf Sternberg


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.

like image 42
vinod Avatar answered Nov 07 '22 05:11

vinod


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.

like image 38
Jan Janský Avatar answered Nov 07 '22 06:11

Jan Janský