Database Routing by URL

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import threading

request_cfg = threading.local()

class RouterMiddleware (object):
    def process_view( self, request, view_func, args, kwargs ):
        # Here you could do something with request.path instead.
        if 'cfg' in kwargs:
            request_cfg.cfg = kwargs['cfg']
    def process_response( self, request, response ):
        if hasattr( request_cfg, 'cfg' ):
            del request_cfg.cfg
        return response

class DatabaseRouter (object):
    def _default_db( self ):
        from django.conf import settings
        if hasattr( request_cfg, 'cfg' ) and request_cfg.cfg in settings.DATABASES:
            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()

More like this

  1. router view by tokibito 3 years, 5 months ago
  2. Application Name DatabaseRouter by kraiz 8 months, 1 week ago
  3. Routing urls.py By Convention by doconix 1 year ago
  4. Format transition middleware by limodou 6 years, 3 months ago
  5. Middleware to detect visitors who arrived from a search engine by exogen 6 years, 1 month ago

Comments

(Forgotten your password?)