I started writing an app with multi-tenancy, for which i had to set database connection on fly based on sub-domain's name.My code goes on like this for same:
import re
import threading
request_cfg = threading.local()
class RouterMiddleware(object):
def process_view( self, request, view_func, args, kwargs ):
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
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()
implying that user has not been authenticated and it redirects me back to login page. I printed self.request.user.is_authenticated() in AccountAuthView and it prints True.
If i set request_cfg.cfg = 'default' in my middleware it works fine.Have i broken/bypassed something in middleware or dbrouter? Whats the fix? Thanks