Skip to content

Commit

Permalink
Custom django-waffle middleware to store testing flags
Browse files Browse the repository at this point in the history
  • Loading branch information
madprime committed May 8, 2020
1 parent 4453cd4 commit 9b3fb07
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
28 changes: 28 additions & 0 deletions open_humans/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@
from django.conf import settings
from django.http import HttpResponseRedirect

from waffle import get_waffle_flag_model
from waffle.middleware import WaffleMiddleware
from waffle.utils import get_setting as get_waffle_setting

from .models import Member

logger = logging.getLogger(__name__)

WaffleFlag = get_waffle_flag_model()


class HttpResponseTemporaryRedirect(HttpResponseRedirect):
"""
Expand Down Expand Up @@ -93,6 +99,28 @@ def __call__(self, request):
return get_production_redirect(request)


class CustomWaffleMiddleware(WaffleMiddleware):
"""
Add testing flags to request.waffle_tests.
Parent middleware process_response saves waffles and waffle_tests to a
cookie in the response.
"""

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
for flag in WaffleFlag.objects.filter(testing=True):
tc = get_waffle_setting("TEST_COOKIE") % flag.name
if tc in request.GET:
on = request.GET[tc] == "1"
if not hasattr(request, "waffle_tests"):
request.waffle_tests = {}
request.waffle_tests[flag.name] = on
return self.process_response(request, self.get_response(request))


class AddMemberMiddleware(object):
"""
A convenience middleware that adds the Member to the request if the user is
Expand Down
2 changes: 1 addition & 1 deletion open_humans/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def to_bool(env, default="false"):
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"open_humans.middleware.AddMemberMiddleware",
"waffle.middleware.WaffleMiddleware",
"open_humans.middleware.CustomWaffleMiddleware",
"django.middleware.cache.FetchFromCacheMiddleware",
)

Expand Down

0 comments on commit 9b3fb07

Please sign in to comment.