Asynchronously database routing in djago and celery

I am implementing subdomain-based database routing, and it is working fine. However, when a task is executed asynchronously, the database that has been dynamically routed gets overwritten by the default one. How to handle that in Django?

# middleware.py

from django.db import connections
from django.conf import settings
from django.http import HttpResponse

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

    def __call__(self, request):
        # Get subdomain from the request
        subdomain = request.META.get('HTTP_HOST', '').split('.')[0]
        subdomain = 'tenant'

        # Set the database connection based on subdomain
        if subdomain:
            request.subdomain = subdomain
            self.set_database(subdomain)
        else:
            request.subdomain = None

        response = self.get_response(request)
        return response

    def set_database(self, subdomain):
        # Dynamically set database for the subdomain
        database_alias = f'{subdomain}'
        if database_alias in settings.DATABASES:
            connections['default'] = connections[database_alias]
        else:
            # Default behavior if no database configured for subdomain
            pass

Вернуться на верх