- Argument checking
- Caching
- Proxy
- Context provider
Showing posts with label decorator. Show all posts
Showing posts with label decorator. Show all posts
Jun 20, 2012
The common patterns for decorators are:
Labels:
decorator
Jun 11, 2012
Naming conventions in decorators
def decorator_name(whatevs):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
pass # sweet decorator goodness
return wrapper
return decorator
http://stackoverflow.com/questions/10957409/python-naming-conventions-in-decorators
Labels:
decorator
May 16, 2012
Allowing only super user login decorator
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def foo_view(request):
....
Labels:
access,
decorator,
permisions,
user
Jul 14, 2011
Decorators ideas
def get_article_from_id(view):
"""
Retrieves a specific article, passing it to the view directly
"""
def wrapper(request, id, *args, **kwargs):
article = get_object_or_404(Article, id=int(id))
return view(request, article=article, *args, **kwargs)
return wraps(view)(wrapper)
def content_type(c_type):
"""
Overrides the Content-Type provided by the view.
Accepts a single argument, the new Content-Type
value to be written to the outgoing response.
"""
def decorator(view):
def wrapper(request, *args, **kwargs):
response = view(request, *args, **kwargs)
response['Content-Type'] = c_type
return wraps(view)(wrapper)
return decorator
def dual_format(template_name):
def decorator(view):
def wrapper(request, *args, **kwargs):
data = view(request, *args, **kwargs)
if request.is_ajax():
json = simplejson.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(json)
else:
context = RequestContext(request)
return render_to_response(template_name, data, context)
return wraps(view)(wrapper)
return decorator
def logged(view):
"""
Logs any errors that occurred during the view
in a special model design for app-specific errors
"""
def wrapper(request, *args, **kwargs):
try:
return view(request, *args, **kwargs)
except Exception, e:
# Log the entry using the application’s Entry model
Entry.objects.create(path=request.path, type='View exception', description=str(e))
# Re-raise it so standard error handling still applies
raise
return wraps(view)(wrapper)
Subscribe to:
Posts (Atom)