Skip to content

Commit

Permalink
Merge pull request #749 from JackiLin/read-write-separation
Browse files Browse the repository at this point in the history
Fix sentinel mode read-write separation
  • Loading branch information
WisdomPill authored Oct 20, 2024
2 parents 196544b + f23b06d commit f98dcce
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
1 change: 1 addition & 0 deletions changelog.d/749.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix is_master parsing error for write separation in sentinel mode
25 changes: 18 additions & 7 deletions django_redis/pool.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Dict
from urllib.parse import parse_qs, urlparse
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
Expand Down Expand Up @@ -163,16 +163,27 @@ def get_connection_pool(self, params):
# explicitly set service_name and sentinel_manager for the
# SentinelConnectionPool constructor since will be called by from_url
cp_params = dict(params)
cp_params.update(service_name=url.hostname, sentinel_manager=self._sentinel)
pool = super().get_connection_pool(cp_params)

# convert "is_master" to a boolean if set on the URL, otherwise if not
# provided it defaults to True.
is_master = parse_qs(url.query).get("is_master")
query_params = parse_qs(url.query)
is_master = query_params.get("is_master")
if is_master:
pool.is_master = to_bool(is_master[0])
cp_params["is_master"] = to_bool(is_master[0])
# then remove the "is_master" query string from the URL
# so it doesn't interfere with the SentinelConnectionPool constructor
if "is_master" in query_params:
del query_params["is_master"]
new_query = urlencode(query_params, doseq=True)

new_url = urlunparse(
(url.scheme, url.netloc, url.path, url.params, new_query, url.fragment)
)

return pool
cp_params.update(
service_name=url.hostname, sentinel_manager=self._sentinel, url=new_url
)

return super().get_connection_pool(cp_params)


def get_connection_factory(path=None, options=None):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_connection_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
[
"unix://tmp/foo.bar?db=1",
"redis://localhost/2",
"redis://redis-master/0?is_master=0",
"redis://redis-master/2?is_master=False",
"rediss://localhost:3333?db=2",
],
)
Expand Down

0 comments on commit f98dcce

Please sign in to comment.