decorator and the use of "self"

38 views
Skip to first unread message

xrfang

unread,
Nov 6, 2009, 11:29:16 AM11/6/09
to web.py
I want to use decorator to control access to some page, e.g.:

class listing:
@login_required
def GET(self):
return "You are allowed to see the listing..."

there are 2 versions of decorators: a function and a class, the
function does not work, while the class worked.

question #1: what's wrong with this function:

def login_required(f, *args):
def new_f(*args):
if session.uid == 0:
raise web.seeother("/tasks/")
else:
f(*args)
return new_f

its problem is that if session.uid is not 0, the f(*args) call does
not work (GET is not called, and webpy display a bare "None" on the
page)

question #2: the following decorator worked:

class login_required:
def __init__(self, function):
self.function = function
def _do_login(self):
raise web.seeother("/tasks/")
def __call__(self):
if session.uid == 0:
return self._do_login()
else:
return self.function(self)

but I am confused about the use of "self": why _do_login() and function
(self)? if I use either _do_login(self) or function() there will be
errors. In another word, when the "self" is expected, and when is it
"injected" to method calls?

Thanks.

xrfang

unread,
Nov 6, 2009, 11:42:11 AM11/6/09
to web.py
question #1 is solved, I must write return f(*args) instead of f
(*args) alone. But #2 is still not solved. Also, I would like some
comment about what's the difference of using function or class as
decorators? is there any pros and cons of them?

Thanks

Anand Chitipothu

unread,
Nov 6, 2009, 12:09:17 PM11/6/09
to we...@googlegroups.com
> question #1:  what's wrong with this function:
>
> def login_required(f, *args):
>    def new_f(*args):
>        if session.uid == 0:
>            raise web.seeother("/tasks/")
>        else:
>            f(*args)
>    return new_f
>
> its problem is that if session.uid is not 0, the f(*args) call does
> not work (GET is not called, and webpy display a bare "None" on the
> page)

because you are not returning anything from new_f. Change the else
part to "return f(*args)

Reply all
Reply to author
Forward
0 new messages