Created
December 7, 2011 16:07
-
-
Save manfre/1443360 to your computer and use it in GitHub Desktop.
Waffle flag view decorator
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
from django.http import HttpResponse | |
from django.template import RequestContext | |
from django.template.loader import render_to_string | |
from django.utils.decorators import available_attrs | |
import waffle | |
def waffled_view(function=None, flag=None, template='503-waffled.html', **kwargs): | |
""" | |
Check the decorated view to see if the flag is enabled for the current | |
request. Any kwargs will be made available to the template. | |
""" | |
ctx = {'flag': flag} | |
ctx.update(kwargs) | |
def view_decorator(view_func): | |
@functools.wraps(view_func, assigned=available_attrs(view_func)) | |
def wrapper(request, *args, **kwargs): | |
if waffle.flag_is_active(request, flag): | |
return view_func(request, *args, **kwargs) | |
logger.info('waffle blocked. flag={flag}, user={user}, url={url}'.format( | |
flag=flag, user=request.user, url=request.get_full_path(), | |
)) | |
msg = render_to_string(template, ctx, | |
context_instance=RequestContext(request)) | |
return HttpResponse(content=msg, status=503) | |
return wrapper | |
if function is None: | |
return view_decorator | |
return functools.update_wrapper(view_decorator, function) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the tip. I refactored it a bit and included your suggestion.