最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Asynchronous database routing in Django and celery - Stack Overflow

programmeradmin3浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论