Skip to content

Instantly share code, notes, and snippets.

@yasmuru
Last active October 29, 2019 07:21
Show Gist options
  • Save yasmuru/a06eeef125805cd232b2f6ea9c9bfd4b to your computer and use it in GitHub Desktop.
Save yasmuru/a06eeef125805cd232b2f6ea9c9bfd4b to your computer and use it in GitHub Desktop.
Useful Django Decorators
# To pass optional arguments to decorator
def the_decorator(arg1, arg2):
def _method_wrapper(view_method):
def _arguments_wrapper(request, *args, **kwargs) :
"""
Wrapper with arguments to invoke the method
"""
#do something with arg1 and arg2
return view_method(request, *args, **kwargs)
return _arguments_wrapper
return _method_wrapper
# Example
@the_decorator("an_argument", "another_argument")
def event_dashboard(request, event_slug):
# To print time consumed by the function
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print('%r (%r, %r) %2.2f sec' % (method.__name__, args, kw, te - ts))
return result
return timed
# To create chain of decorators
from functools import wraps
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
@makebold
@makeitalic
def log(s):
return s
print hello() # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello') # returns "<b><i>hello</i></b>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment