How do I write a decorator for my Django/Python view? -


here's view. basically, returns different responses based on whether it's logged in or not.

@check_login() def home(request):     if is_logged_in(request):          return x     else:         return y 

here's decorator code. want check if request has headers, , if so, log him in.

#decorator log user in if there headers def check_login():     def check_dec(func):         if request.meta['username'] == "blah":             login(request, user)      return check_dec 

the problem is..i don't know how write proper decorator in case!!! arguments? functions? how?

use @check_login instead of check_login() - otherwise decorator has return decorate doing home = check_login()(home)

here's example decorator:

def check_login(method):     @functools.wraps(method)     def wrapper(request, *args, **kwargs):         if request.meta['username'] == "blah"             login(request, user) # user come from?!         return method(request, *args, **kwargs)     return wrapper 

this decorator call execute login function if username field set "blah" , call original method.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -