Celery task function custom attributes

巧了我就是萌 提交于 2019-12-08 02:43:53

问题


I have a celery task function that looks like this-

@task(base=MyBaseTask)
@my_custom_decorator 
def my_task(*args, **kwargs):
    my_task.ltc.some_func() #fails - attribute ltc doesn't exist on the object

and my_custom_decorator looks like this

def my_custom_decorator (f):
    from functools import wraps
    ltc = SomeClass()
    @wraps(f)
    def _inner(*args, **kwargs):
        ret_obj = None
        try:
            f.task_cache = ltc
            ret_obj = f(*args, **kwargs)
        except Exception, e:
            raise
        return ret_obj
    _inner.ltc = ltc
    return _inner

I see that this is because the actual callable object that is invoked to execute the task is an object of type celery task class. How can I retain my attribute 'ltc' on this object so it can be accessed from within the task as show above i.e - my_task.ltc.some_func() ?

Thanks,


回答1:


I think one easy way to do that would be to introduce ltc as a keyword parameter..

@task(base=MyBaseTask)
@my_custom_decorator 
def my_task(*args, **kwargs):
    ltc = kwargs['ltc']
    ltc.some_func()

maybe this way:

def my_custom_decorator (f):
    from functools import wraps
    ltc = SomeClass()
    @wraps(f)
    def _inner(*args, **kwargs):
        ret_obj = None
        try:
            f.task_cache = ltc
            kwargs['ltc'] = ltc
            ret_obj = f(*args, **kwargs)
        except Exception, e:
            raise
        return ret_obj
    _inner.ltc = ltc
    return _inner

I don't know if there's a celery's task way to do this. Hope this helps you.



来源:https://stackoverflow.com/questions/17068283/celery-task-function-custom-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!