Good point Marek.
Great example. Here's a little more complex one
def authorize(role=None):
def validate(func, self, *args, **kwargs):
if role is None and is_logged_in or has_role(role):
return func(self, *args, **kwargs)
return {'success': False, 'msg': u'You cann't do it!'}
return decorator(validate)
And you can call it like @authorize('admin')
But for some reason it breaks when you call it without params.. like
@authorize (wanted to implement a check for being logged in at all)
<type 'exceptions.AssertionError'>:
On Feb 9, 1:02 pm, "Marek Stępniowski" <[EMAIL PROTECTED]> wrote:
> 2008/2/8, Chris <[EMAIL PROTECTED]>:
>
>
>
>
>
> > Hi,
> > It is probably something simple, but I'm having some difficulty
> > writing a decorator factory for a controller method.
>
> > # The decorator stuff
> > def factory(param):
> > def deco(func):
> > def newaction(self, *args, **kw):
> > return func(self, *args, **kw)
> > return newaction
> > return deco
>
> > # The controller method
> > @factory(param1)
> > def action(self):
> > return 'interesting stuff'
>
> > The error I'm getting is:
> > <type 'exceptions.TypeError'>: action() got an unexpected keyword
> > argument 'start_response'
>
> (cut!)
>
> > Any suggestions on how to correctly write a decorator factory for a
> > controller method?
>
> I'm using a decorator function from decorator module (afaik it is
> standard in Pylons world). Everything works fine. Just remember to
> take all *args and **kwargs and pass them (or not?) to decorated
> function.
>
> Here is a simple example:
>
> from decorator import decorator
>
> @decorator
> def authorize(func, *args, **kwargs):
> if not session['user'].is_admin:
> redirect_to('login_form')
> return func(*args, **kwargs)
>
> Cheers,
> --
> Marek Stępniowski
> email: [EMAIL PROTECTED] || [EMAIL PROTECTED]
> gg: 5354504
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---