Skip to content

Instantly share code, notes, and snippets.

@manfre
Created December 7, 2011 16:07
Show Gist options
  • Save manfre/1443360 to your computer and use it in GitHub Desktop.
Save manfre/1443360 to your computer and use it in GitHub Desktop.
Waffle flag view decorator
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)
@cyberdelia
Copy link

Tips :

from django.utils.functional import update_wrapper
return update_wrapper(view_decorator, function) 

@manfre
Copy link
Author

manfre commented Dec 7, 2011

Thanks for the tip. I refactored it a bit and included your suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment