Multiple decorators

Hi!

Are there any limitation of giving a method multiple decorators?

Eg

@anvil.server.callable
@anvil.server.background_task
def ping():
   return “pong”

Could the method also be decorated with eg route and/or http_endpoint?

Thanks!

1 Like

As far as I know, no, there are no limitations.

But in some cases the order matters, as mentioned at the end of this paragraph: Anvil Docs | Transactions

5 Likes

And at least with some custom decorators, you need to sometimes manually apply the name of the anvil server callable.

As in

This can be useful with Uplink, e.g., if you have multiple instances of a “server program” (uplinked program) running simultaneously, and each one needs its own distinct function name. You can change the name (to identify the individual instance) without changing anything else about the code.

1 Like

Yes exactly that. I have some custom auth decorators and they don’t work unless I customize the name manually

Hi everyone,
If I use more than one decorator, like @anvil.server.callable and a custom one for authentication, how can I make sure they work together without needing to change the name manually?

As far as I know, you can’t. Changing the order doesn’t work. I always have to put the @anvil.server.callable decorator as the top decorator and give it the name argument for the name of the function.

I personally have a bunch of these and fought with the code for a while before coming to this conclusion.

here’s an example on the forum:

Notice the use of the @wraps decorator to ensure that the wrapped function keeps it’s name when it is wrapped.
This saves you having to declare the name explicitly

def custom_wrapper(fn):
    @wraps(fn)
    def wrapper(*args, **kws):
        ... #custom logic
        return fn(*args, **kws)

    return wrapper

And worth remembering the require_user argument which is often sufficient for authentication

3 Likes