Create shared task (decorator). This can be used by library authors to create tasks that'll work for any app environment. Returns: ~celery.local.Proxy: A proxy that always takes the task from the current apps task registry. Example: >>> from celery import
(*args, **kwargs)
| 22 | |
| 23 | |
| 24 | def shared_task(*args, **kwargs): |
| 25 | """Create shared task (decorator). |
| 26 | |
| 27 | This can be used by library authors to create tasks that'll work |
| 28 | for any app environment. |
| 29 | |
| 30 | Returns: |
| 31 | ~celery.local.Proxy: A proxy that always takes the task from the |
| 32 | current apps task registry. |
| 33 | |
| 34 | Example: |
| 35 | |
| 36 | >>> from celery import Celery, shared_task |
| 37 | >>> @shared_task |
| 38 | ... def add(x, y): |
| 39 | ... return x + y |
| 40 | ... |
| 41 | >>> app1 = Celery(broker='amqp://') |
| 42 | >>> add.app is app1 |
| 43 | True |
| 44 | >>> app2 = Celery(broker='redis://') |
| 45 | >>> add.app is app2 |
| 46 | True |
| 47 | """ |
| 48 | def create_shared_task(**options): |
| 49 | |
| 50 | def __inner(fun): |
| 51 | if type(fun) is Proxy: |
| 52 | raise TypeError( |
| 53 | '@shared_task was applied more than once to the same ' |
| 54 | 'function. Remove the extra @shared_task decorator.' |
| 55 | ) |
| 56 | name = options.get('name') |
| 57 | # Set as shared task so that unfinalized apps, |
| 58 | # and future apps will register a copy of this task. |
| 59 | _state.connect_on_app_finalize( |
| 60 | lambda app: app._task_from_fun(fun, **options) |
| 61 | ) |
| 62 | |
| 63 | # Force all finalized apps to take this task as well. |
| 64 | for app in _state._get_active_apps(): |
| 65 | if app.finalized: |
| 66 | with app._finalize_mutex: |
| 67 | app._task_from_fun(fun, **options) |
| 68 | |
| 69 | # Return a proxy that always gets the task from the current |
| 70 | # apps task registry. |
| 71 | def task_by_cons(): |
| 72 | app = _state.get_current_app() |
| 73 | return app.tasks[ |
| 74 | name or app.gen_task_name(fun.__name__, fun.__module__) |
| 75 | ] |
| 76 | return Proxy(task_by_cons) |
| 77 | return __inner |
| 78 | |
| 79 | if len(args) == 1 and callable(args[0]): |
| 80 | return create_shared_task(**kwargs)(args[0]) |
| 81 | return create_shared_task(*args, **kwargs) |
no test coverage detected