Skip to content

Commit d4fba66

Browse files
authored
Adds ability to have multiple read replicas. (#116)
* Adds ability to have multiple read replicas. * Adds ability to have dynamic number of read replicas.
1 parent 5dcaead commit d4fba66

File tree

3 files changed

+15
-12
lines changed

3 files changed

+15
-12
lines changed

sensorsafrica/api/v2/serializers.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from rest_framework import serializers
22
from feinstaub.sensors.serializers import (
33
NestedSensorLocationSerializer,
4-
NestedSensorTypeSerializer,
54
)
65
from feinstaub.sensors.models import Node, Sensor, SensorType, SensorLocation
76
from feinstaub.sensors.serializers import (VerboseSensorDataSerializer, )

sensorsafrica/router.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1+
import random
2+
3+
from django.conf import settings
4+
15
class ReplicaRouter:
2-
route_app_labels = {'auth', 'sessions',}
6+
read_replica_app_labels = {'sensors', }
7+
read_replicas = list(settings.DATABASES.keys() - {'default', })
38

49
def db_for_read(self, model, **hints):
5-
if model._meta.app_label in self.route_app_labels:
6-
return 'default'
7-
return "read_replica"
10+
if model._meta.app_label in self.read_replica_app_labels:
11+
return random.choice(self.read_replicas)
12+
return 'default'
813

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

sensorsafrica/settings.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,13 @@
109109
"SENSORSAFRICA_DATABASE_URL",
110110
"postgres://sensorsafrica:sensorsafrica@localhost:5432/sensorsafrica",
111111
)
112-
READ_DATABASE_URL = os.getenv(
113-
"SENSORSAFRICA_READ_DATABASE_URL", DATABASE_URL
114-
)
115112

116-
DATABASES = {
117-
"default": dj_database_url.parse(DATABASE_URL),
118-
"read_replica": dj_database_url.parse(READ_DATABASE_URL),
119-
}
113+
READ_DATABASE_URLS = os.getenv("SENSORSAFRICA_READ_DATABASE_URLS", DATABASE_URL).split(" ")
114+
115+
DATABASES = {"default": dj_database_url.parse(DATABASE_URL), }
116+
117+
for index, read_database_url in enumerate(1, READ_DATABASE_URLS):
118+
DATABASES[f"read_replica_{index}"] = dj_database_url.parse(read_database_url)
120119

121120
DATABASE_ROUTERS = ["sensorsafrica.router.ReplicaRouter", ]
122121

0 commit comments

Comments
 (0)