简体   繁体   中英

Celery task function custom attributes

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 ie - my_task.ltc.some_func() ?

Thanks,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM