Skip to content

Commit

Permalink
Add database router for read-only replica
Browse files Browse the repository at this point in the history
  • Loading branch information
davea committed Nov 23, 2023
1 parent 4536e48 commit 596f137
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
15 changes: 15 additions & 0 deletions labour_project/dbrouter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import random

class HotStandbyRouter:
def db_for_read(self, model, **hints):
return random.choice(["default", "replica"])

def db_for_write(self, model, **hints):
return "default"

def allow_relation(self, obj1, obj2, **hints):
# XXX do we need this?
db_set = {"default", "replica"}
if obj1._state.db in db_set and obj2._state.db in db_set:
return True
return None
12 changes: 12 additions & 0 deletions labour_project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@
}
}

if config.get('MAPIT_DB_RO_HOST'):
DATABASES['replica'] = {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': config.get('MAPIT_DB_NAME', 'mapit'),
'USER': config.get('MAPIT_DB_USER', 'mapit'),
'PASSWORD': config.get('MAPIT_DB_PASS', ''),
'HOST': config.get('MAPIT_DB_RO_HOST', ''),
'PORT': config.get('MAPIT_DB_RO_PORT', ''),
}
DATABASE_ROUTERS = [ "labour_project.dbrouter.HotStandbyRouter" ]


# Make this unique, and don't share it with anybody.
SECRET_KEY = config.get('DJANGO_SECRET_KEY', '')

Expand Down

0 comments on commit 596f137

Please sign in to comment.