gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:50:52 26 4
gpt4 key购买 nike

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

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

最佳答案

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.

关于python - 如何将自定义装饰器添加到结构任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com