URL Based Database Routing

I set up URL-based database routing inspired by this to use the same application for different projects / databases. Projects do not need to share any data, access control is managed by each project on its own, and I need an admin site for each project. As in the original post, I use a database router and middleware that determines which database will be used from the query path, for example. /test/process/1will be redirected to the database testand /default/process/2to the database default.

import threading
from django.conf import settings

request_cfg = threading.local()

class RouterMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        path = request.path.lstrip('/').split('/')
        if path[0] in settings.DATABASES:
            request_cfg.db = path[0]

    def process_response(self, request, response):
        if hasattr(request_cfg, 'db'):
            del request_cfg.db
        return response

class DatabaseRouter(object):
    def _default_db(self):
        if hasattr(request_cfg, 'db') and request_cfg.db in settings.DATABASES:
            return request_cfg.db
        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()

url , , . URL- urls.py, :

urlpatterns = [
  url(r'^default/admin/', include(admin.site.urls)),  # does not work
  url(r'^test/admin/', include(admin.site.urls)),  # does not work
  url(r'^default/', include('logbook.urls', namespace='anything')),
  url(r'^test/', include('logbook.urls', namespace='anything else'))]

, , , . , , , . logbook, .

urls.py ( ):

app_name = 'logbook'

urlpatterns = [
    url(r'^$', views.redirect_index, name='index'),
    url(r'^(?P<date>[0-9]{4}[0-9]{2})/$', views.Index.as_view(), name='index'),
.....

current_app=request.resolver_match.namespace kwarg reverse(), django docs. URL- .

:

  • url admin urls.py
  • django.contrib.auth.middleware.AuthenticationMiddleware , , LOGIN LOGIN_REDIRECT .

, , . , ?

+6
1

, .

Django Multi DB

, , - . , db (, ) , , .

+2

Source: https://habr.com/ru/post/1016278/


All Articles