-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for read-only database replica
Lifted from mysociety/mapit.mysociety.org#90
- Loading branch information
Showing
3 changed files
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
from .multidb import use_primary | ||
|
||
READ_METHODS = frozenset(['GET', 'HEAD', 'OPTIONS', 'TRACE']) | ||
|
||
|
||
def force_primary_middleware(get_response): | ||
"""On a non-read request (e.g. POST), always use the primary database, and | ||
set a short-lived cookie. Then on any request made including that cookie, | ||
also always use the primary database. This is so we don't need to worry | ||
about any replication lag for reads made immediately after writes, because | ||
we force those reads to go to the primary.""" | ||
def middleware(request): | ||
use_primary('primary_forced' in request.COOKIES or request.method not in READ_METHODS) | ||
|
||
response = get_response(request) | ||
|
||
if request.method not in READ_METHODS: | ||
response.set_cookie('primary_forced', value='y', max_age=10) | ||
|
||
return response | ||
|
||
return middleware |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
""" | ||
A getter/setter for a thread-local variable for using the primary database. | ||
""" | ||
|
||
import threading | ||
|
||
_locals = threading.local() | ||
|
||
|
||
def use_primary(val=None): | ||
"""If passed no argument, return the current value (or False if unset); | ||
if passed an argument, set the variable to that.""" | ||
if val is None: | ||
return getattr(_locals, 'primary', False) | ||
else: | ||
_locals.primary = val |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters