dynamically set database based on request in django

后端 未结 2 1819
执念已碎
执念已碎 2020-12-07 19:36

I am writing a multi-tenant application with python-django.

I want to set database connection based on each request.I thought i could write a middleware where we set

相关标签:
2条回答
  • 2020-12-07 19:54

    Maybe you can use:

    https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset

    Entity.objects.using('context1').all()
    Entity.objects.using('context2').all()
    

    To select/use a database depending on the request. You can define multiple DBs in the configurartion:

    DATABASES = {
        'context1': {
            'NAME': 'context1',
            'ENGINE': 'db.engine.to.use',
            'USER': 'xxx',
            'PASSWORD': 'xxx'
        },
        'context2': {
            'NAME': 'context2',
            'ENGINE': 'db.engine.to.use',
            'USER': 'xxx',
            'PASSWORD': 'xxx'
        }
    }
    
    0 讨论(0)
  • 2020-12-07 20:12

    this is the answer, hope it helps someone in future:

    import re
    import threading 
    request_cfg = threading.local()
    
    
    class RouterMiddleware(object):
        def process_request( self, request):
            pattern = re.compile("\\b(http://|https://|www.|.com|8000|:|//)\\W\\d+", re.I)
            words = request.get_host()        
            db_name = [pattern.sub("", words)][0].split('.')[0]
            request_cfg.cfg = db_name
            return None
    
        def process_response( self, request, response ):
            if hasattr( request_cfg, 'cfg' ):
                del request_cfg.cfg
            return response
    
    
    class DatabaseRouter (object):
        def _default_db( self ):
            if hasattr( request_cfg, 'cfg' ):
                return request_cfg.cfg
            else:
                return 'default'
    
        def db_for_read( self, model, **hints ):
            return self._default_db()
    
        def db_for_write( self, model, **hints ):
            return self._default_db()
    

    Thanks

    0 讨论(0)
提交回复
热议问题