Skip to content

Commit

Permalink
added db router with random algo for now
Browse files Browse the repository at this point in the history
  • Loading branch information
Amey Tendulkar committed Nov 1, 2023
1 parent fd98336 commit 285ed46
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 3 deletions.
33 changes: 33 additions & 0 deletions api/dbrouter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import random

class PrimaryReplicaRouter:
def db_for_read(self, model, **hints):
"""
Reads go to a randomly-chosen replica.
"""
db_to = random.choice(['replica1', 'replica2'])
print('****'*20)
print(db_to)
return db_to

def db_for_write(self, model, **hints):
"""
Writes always go to primary.
"""
return 'primary'

def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the primary/replica pool.
"""
db_set = {'primary', 'replica1', 'replica2'}
if obj1._state.db in db_set and obj2._state.db in db_set:
return True
return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
All non-auth models end up in this pool.
"""
return True
2 changes: 1 addition & 1 deletion api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def get(self, request, format=None):
category = Category.objects.get(id=category_id)
subcategories = SubCategory.objects.filter(category=category)
subcategories_prefetch = Prefetch('sub_category', queryset=subcategories)
products = Product.objects.filter(sub_category__in=subcategories).prefetch_related(subcategories_prefetch)
products = Product.objects.filter(sub_category__in=subcategories).prefetch_related(subcategories_prefetch).order_by('id') #to get uniform paginated results.
#products = Product.objects.filter(sub_category__in=subcategories)

paginator = Paginator(products, 10)
Expand Down
13 changes: 13 additions & 0 deletions dbroutertest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import requests

def callapi():
url = "http://localhost:8000/api/products-by-category?category=21&page=2"

payload = {}
headers = {}

response = requests.request("GET", url, headers=headers, data=payload)

for i in range(0,100):
callapi()

5 changes: 3 additions & 2 deletions globalmart/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
"default": {
'default': {},
"primary": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "globalmart",
"USER": "postgres",
Expand All @@ -131,7 +132,7 @@
}
}


DATABASE_ROUTERS = ['api.dbrouter.PrimaryReplicaRouter']

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
Expand Down

0 comments on commit 285ed46

Please sign in to comment.