Mike
Mike

Reputation: 7841

Disable session creation in Django

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?

Upvotes: 21

Views: 4747

Answers (3)

Jan Janský
Jan Janský

Reputation: 29

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.

Upvotes: 2

vinod
vinod

Reputation: 2368

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.

Upvotes: 4

Elf Sternberg
Elf Sternberg

Reputation: 16381

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

Upvotes: 23

Related Questions