5

好吧,我必须承认我是织物甚至 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()

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

4

1 回答 1

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"

结果:

# fab -l
>Available commands:
>
>    some_function

# fab some_function
>this function is decorated.
>this is function
>
>Done.
于 2013-07-19T03:35:58.257 回答