Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Created July 30, 2014 13:16
Show Gist options
  • Save turtlemonvh/48d92d4153754aea4504 to your computer and use it in GitHub Desktop.
Save turtlemonvh/48d92d4153754aea4504 to your computer and use it in GitHub Desktop.
Middleware for running django on multiple ports
from django.conf import settings
class MultiPortMiddleware(object):
"""
Middleware changes the SESSION_COOKIE_NAME to use the current port in the name
"""
def process_request(self, request):
settings.SESSION_COOKIE_NAME = 'sessionid' + request.META['SERVER_PORT']
return None
@turtlemonvh
Copy link
Author

Add this as the first entry in your MIDDLEWARE_CLASSES, or at least before django.middleware.common.CommonMiddleware and django.contrib.sessions.middleware.SessionMiddleware.

@jjmontesl
Copy link

This is changing cookie name globally, not in a per-request basis. May be ok if the app accepts requests through a single port only.

@MonsieurV
Copy link

An alternative that only change the cookie name used in the middleware, without modifying any global setting (which may have side effects).

https://gist.github.com/MonsieurV/c2637d959ccd9d8e962a3ac453daed83

@turtlemonvh
Copy link
Author

Thanks @MonsieurV, that solution looks better. Updating a global setting in each request was clearly not a good idea!

@Nanthasekar
Copy link

Nanthasekar commented Jun 16, 2023

How to store the session in Django between two different ports and we are using IP not domain. here one server is Django and another server is angular.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment