如何将自定义装饰器添加到结构任务

aak*_*aki 5 python decorator fabric

好吧,我必须承认我是织物甚至python的新手,但是我有兴趣以正确的方式做到这一点,所以......我想用一个prepare函数装饰我的一些任务,这个函数env根据那些已经添加了一些变量给出.看一看:

from fabric.api import *
import fabstork.project.base as base
import fabstork.utils.drupal as utils

def prepare(task):
    """ Decorator to set some additional environment variables """
    def prepared(*args, **kwargs):
        env.sites_folder = env.sites_folder if 'sites_folder' in env else 'default'
        env.settings_file = "%s/www/sites/%s/settings.php" % (env.build_path, env.sites_folder)
        # more to come
        return task(*args, **kwargs)

    return prepared


@task
@prepare
def push(ref='HEAD'):
    """
    Deploy a commit to a host
    """
    base.push(ref)
    utils.settings_php()
    utils.link_files()
    utils.set_perms()
Run Code Online (Sandbox Code Playgroud)

上面的示例失败,因为push它不再是任务,fab --list在命令行执行a时它不在可用任务列表中.省略装饰器可以完成任务.我究竟做错了什么?

Yui*_*iro 8

from fabric.decorators import task
from functools import wraps

def custom_decorator(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        print "this function is decorated."
        return func(*args, **kwargs)
    return decorated

@task
@custom_decorator
def some_function():
    print "this is function"
Run Code Online (Sandbox Code Playgroud)

结果:

# fab -l
>Available commands:
>
>    some_function

# fab some_function
>this function is decorated.
>this is function
>
>Done.
Run Code Online (Sandbox Code Playgroud)