Django – Middleware losing connection with database on multi-tenant app

On my Django app I use a multi-tenant approach with isolated databases. It works well but because it relies on subdomains for each tenant, which is not scalable, I’m trying to change that. To achieve this functionality I’m trying to use middlewares and sessions to retrieve the tenant from the username and use it to set a local variable for the database routers. The logic is this:

If the user is not logged, the BeforeLoginMiddleware activates and retrieves the tenant name from the user. So username@tenant1 will set tenant1 to the session. Here’s the code:

import threading
from users.forms import LoginForm

Thread_Local = threading.local()

class BeforeLoginMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        if request.path == '/login/':

            form = LoginForm(request.POST)

            if form.is_valid():

                complete_username = form.cleaned_data.get('username')
                current_db = complete_username.split('@')[1]
                request.session['current_db'] = current_db
                request.session.modified = True

        response = self.get_response(request)

        return response

If the user is already logged, a second middleware will retrieve the tenant data from the session and use it to define the Thread_Local variable that is called on a function used on the database routers:

class AppMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        current_db = request.session.get('current_db')
        setattr(Thread_Local, 'current_db', current_db)
        response = self.get_response(request)

        return response

def get_current_db_name():
    return getattr(Thread_Local, 'current_db', None)

Here’s the routers.py file:

class AppRouter:

    def db_for_read(self, model, **hints):
        return get_current_db_name()

    def db_for_write(self, model, **hints):
        return get_current_db_name()

    def allow_relation(self, *args, **kwargs):
        return True

    def allow_syncdb(self, *args, **kwargs):
        return None

    def allow_migrate(self, *args, **kwargs):
        return None

This is the middleware setting on my app:

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'myapp.middleware.BeforeLoginMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'myapp.middleware.AppMiddleware',
]

This works as expected but at random (or at least it appear to be at random) it loses connection with the database and I assume that, since it can’t retrieve the session data, redirects the user to the login page again (I’m also using the login_required decorator). This also occurs if the page is idle for about 1 minute, which makes no sense because my SESSION_COOKIE_AGE setting is 1200.

Thing is, I have no idea what is causing this because there are no errors. The only thing I’ve noticed that is consistent when this happens, it’s a 302 status registered in the network tab on the browser (which is the redirect to the login page) and the message Broken pipe from (‘127.0.0.1’, 61980) in the terminal with this random code at the end.

What I’ve tried so far, without any change in the behavior described above:

  • A LOT of different settings for the middleware. For example: at first I wrote a
    single middleware with all the logic and put it in the end of the
    middleware list. I thought that this could be causing the issue so I separated the logic. Another try was to use request.user.is_authenticated in the middleware instead of using the session data.
  • Based on this answer I’ve tried to disable every JS script on
    the app (there are just a few). Not really an option but I think it excludes the possibility of being the cause.
  • Clear the browser cache / cookies entirely.
  • Change the SESSION_SAVE_EVERY_REQUEST setting to True.
  • Change the SESSION_COOKIE_AGE setting to 120000 (I think it makes no sense to increase this number, but at this point, I’m willing to try anything).

I’m honestly running out of options, so I appreciate any help or advice.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật