application.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. .. _guide-app:
  2. =============
  3. Application
  4. =============
  5. .. contents::
  6. :local:
  7. :depth: 1
  8. The Celery library must be instantiated before use, this instance
  9. is called an application (or *app* for short).
  10. The application is thread-safe so that multiple Celery applications
  11. with different configuration, components and tasks can co-exist in the
  12. same process space.
  13. Let's create one now:
  14. .. code-block:: python
  15. >>> from celery import Celery
  16. >>> celery = Celery()
  17. >>> celery
  18. <Celery __main__:0x100469fd0>
  19. The last line shows the textual representation of the application,
  20. which includes the name of the celery class (``Celery``), the name of the
  21. current main module (``__main__``), and the memory address of the object
  22. (``0x100469fd0``).
  23. Main Name
  24. =========
  25. Only one of these is important, and that is the main module name,
  26. let's look at why that is.
  27. When you send a task message in Celery, that message will not contain
  28. any source code, but only the name of the task you want to execute.
  29. This works similarly to how host names works on the internet: every worker
  30. maintains a mapping of task names to their actual functions, called the *task
  31. registry*.
  32. Whenever you define a task, that task will also be added to the local registry:
  33. .. code-block:: python
  34. >>> @celery.task
  35. ... def add(x, y):
  36. ... return x + y
  37. >>> add
  38. <@task: __main__.add>
  39. >>> add.name
  40. __main__.add
  41. >>> celery.tasks['__main__.add']
  42. <@task: __main__.add>
  43. and there you see that ``__main__`` again; whenever Celery is not able
  44. to detect what module the function belongs to, it uses the main module
  45. name to generate the beginning of the task name.
  46. This is only a problem in a limited set of use cases:
  47. #. If the module that the task is defined in is run as a program.
  48. #. If the application is created in the Python shell (REPL).
  49. For example here, where the tasks module is also used to start a worker:
  50. :file:`tasks.py`:
  51. .. code-block:: python
  52. from celery import Celery
  53. celery = Celery()
  54. @celery.task
  55. def add(x, y): return x + y
  56. if __name__ == '__main__':
  57. celery.worker_main()
  58. When this module is executed the tasks will be named starting with "``__main__``",
  59. but when it the module is imported by another process, say to call a task,
  60. the tasks will be named starting with "``tasks``" (the real name of the module)::
  61. >>> from tasks import add
  62. >>> add.name
  63. tasks.add
  64. You can specify another name for the main module:
  65. .. code-block:: python
  66. >>> celery = Celery('tasks')
  67. >>> celery.main
  68. 'tasks'
  69. >>> @celery.task
  70. ... def add(x, y):
  71. ... return x + y
  72. >>> add.name
  73. tasks.add
  74. .. seealso:: :ref:`task-names`
  75. Configuration
  76. =============
  77. There are lots of different options you can set that will change how
  78. Celery work. These options can be set on the app instance directly,
  79. or you can use a dedicated configuration module.
  80. The configuration is available as :attr:`@Celery.conf`::
  81. >>> celery.conf.CELERY_TIMEZONE
  82. 'Europe/London'
  83. where you can set configuration values directly::
  84. >>> celery.conf.CELERY_ENABLE_UTC = True
  85. or you can update several keys at once by using the ``update`` method::
  86. >>> celery.conf.update(
  87. ... CELERY_ENABLE_UTC=True,
  88. ... CELERY_TIMEZONE='Europe/London',
  89. ...)
  90. The configuration object consists of multiple dictionaries
  91. that are consulted in order:
  92. #. Changes made at runtime.
  93. #. The configuration module (if any)
  94. #. The default configuration (:mod:`celery.app.defaults`).
  95. .. seealso::
  96. Go to the :ref:`Configuration reference <configuration>` for a complete
  97. listing of all the available settings, and their default values.
  98. ``config_from_object``
  99. ----------------------
  100. The :meth:`@Celery.config_from_object` method loads configuration
  101. from a configuration object.
  102. This can be a configuration module, or any object with configuration attributes.
  103. Note that any configuration that was previous set will be reset when
  104. :meth:`~@Celery.config_from_object` is called. If you want to set additional
  105. configuration you should do so after.
  106. Example 1: Using the name of a module
  107. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  108. .. code-block:: python
  109. from celery import Celery
  110. celery = Celery()
  111. celery.config_from_object('celeryconfig')
  112. The ``celeryconfig`` module may then look like this:
  113. :file:`celeryconfig.py`:
  114. .. code-block:: python
  115. CELERY_ENABLE_UTC = True
  116. CELERY_TIMEZONE = 'Europe/London'
  117. Example 2: Using a configuration module
  118. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  119. .. code-block:: python
  120. from celery import Celery
  121. celery = Celery()
  122. import celeryconfig
  123. celery.config_from_object(celeryconfig)
  124. Example 3: Using a configuration class/object
  125. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  126. .. code-block:: python
  127. from celery import Celery
  128. celery = Celery()
  129. class Config:
  130. CELERY_ENABLE_UTC = True
  131. CELERY_TIMEZONE = 'Europe/London'
  132. celery.config_from_object(Config)
  133. ``config_from_envvar``
  134. ----------------------
  135. The :meth:`@Celery.config_from_envvar` takes the configuration module name
  136. from an environment variable
  137. For example -- to load configuration from a module specified in the
  138. environment variable named :envvar:`CELERY_CONFIG_MODULE`:
  139. .. code-block:: python
  140. import os
  141. from celery import Celery
  142. #: Set default configuration module name
  143. os.environ.setdefault('CELERY_CONFIG_MODULE', 'celeryconfig')
  144. celery = Celery()
  145. celery.config_from_envvar('CELERY_CONFIG_MODULE')
  146. You can then specify the configuration module to use via the environment:
  147. .. code-block:: bash
  148. $ CELERY_CONFIG_MODULE="celeryconfig.prod" celery worker -l info
  149. Laziness
  150. ========
  151. The application instance is lazy, meaning that it will not be evaluated
  152. until something is actually needed.
  153. Creating a :class:`@Celery` instance will only do the following:
  154. #. Create a logical clock instance, used for events.
  155. #. Create the task registry.
  156. #. Set itself as the current app (but not if the ``set_as_current``
  157. argument was disabled)
  158. #. Call the :meth:`@Celery.on_init` callback (does nothing by default).
  159. The :meth:`~@Celery.task` decorator does not actually create the
  160. tasks at the point when it's called, instead it will defer the creation
  161. of the task to happen either when the task is used, or after the
  162. application has been *finalized*,
  163. This example shows how the task is not created until
  164. you use the task, or access an attribute (in this case :meth:`repr`):
  165. .. code-block:: python
  166. >>> @celery.task
  167. >>> def add(x, y):
  168. ... return x + y
  169. >>> type(add)
  170. <class 'celery.local.PromiseProxy'>
  171. >>> add.__evaluated__()
  172. False
  173. >>> add # <-- causes repr(add) to happen
  174. <@task: __main__.add>
  175. >>> add.__evaluated__()
  176. True
  177. *Finalization* of the app happens either explicitly by calling
  178. :meth:`@Celery.finalize` -- or implicitly by accessing the :attr:`~@Celery.tasks`
  179. attribute.
  180. Finalizing the object will:
  181. #. Copy tasks that must be shared between apps
  182. Tasks are shared by default, but if the
  183. ``shared`` argument to the task decorator is disabled,
  184. then the task will be private to the app it's bound to.
  185. #. Evaluate all pending task decorators.
  186. #. Make sure all tasks are bound to the current app.
  187. Tasks are bound to apps so that it can read default
  188. values from the configuration.
  189. .. _default-app:
  190. .. topic:: The "default app".
  191. Celery did not always work this way, it used to be that
  192. there was only a module-based API, and for backwards compatibility
  193. the old API is still there.
  194. Celery always creates a special app that is the "default app",
  195. and this is used if no custom application has been instantiated.
  196. The :mod:`celery.task` module is there to accommodate the old API,
  197. and should not be used if you use a custom app. You should
  198. always use the methods on the app instance, not the module based API.
  199. For example, the old Task base class enables many compatibility
  200. features where some may be incompatible with newer features, such
  201. as task methods:
  202. .. code-block:: python
  203. from celery.task import Task # << OLD Task base class.
  204. from celery import Task # << NEW base class.
  205. The new base class is recommended even if you use the old
  206. module-based API.
  207. Breaking the chain
  208. ==================
  209. While it's possible to depend on the current app
  210. being set, the best practice is to always pass the app instance
  211. around to anything that needs it.
  212. I call this the "app chain", since it creates a chain
  213. of instances depending on the app being passed.
  214. The following example is considered bad practice:
  215. .. code-block:: python
  216. from celery import current_app
  217. class Scheduler(object):
  218. def run(self):
  219. app = current_app
  220. Instead it should take the ``app`` as an argument:
  221. .. code-block:: python
  222. class Scheduler(object):
  223. def __init__(self, app):
  224. self.app = app
  225. Internally Celery uses the :func:`celery.app.app_or_default` function
  226. so that everything also works in the module-based compatibility API
  227. .. code-block:: python
  228. from celery.app import app_or_default
  229. class Scheduler(object):
  230. def __init__(self, app=None):
  231. self.app = app_or_default(app)
  232. In development you can set the :envvar:`CELERY_TRACE_APP`
  233. environment variable to raise an exception if the app
  234. chain breaks:
  235. .. code-block:: bash
  236. $ CELERY_TRACE_APP=1 celery worker -l info
  237. .. topic:: Evolving the API
  238. Celery has changed a lot in the 3 years since it was initially
  239. created.
  240. For example, in the beginning it was possible to use any callable as
  241. a task:
  242. .. code-block:: python
  243. def hello(to):
  244. return 'hello {0}'.format(to)
  245. >>> from celery.execute import apply_async
  246. >>> apply_async(hello, ('world!', ))
  247. or you could also create a ``Task`` class to set
  248. certain options, or override other behavior
  249. .. code-block:: python
  250. from celery.task import Task
  251. from celery.registry import tasks
  252. class Hello(Task):
  253. send_error_emails = True
  254. def run(self, to):
  255. return 'hello {0}'.format(to)
  256. tasks.register(Hello)
  257. >>> Hello.delay('world!')
  258. Later, it was decided that passing arbitrary call-ables
  259. was an anti-pattern, since it makes it very hard to use
  260. serializers other than pickle, and the feature was removed
  261. in 2.0, replaced by task decorators:
  262. .. code-block:: python
  263. from celery.task import task
  264. @task(send_error_emails=True)
  265. def hello(x):
  266. return 'hello {0}'.format(to)
  267. Abstract Tasks
  268. ==============
  269. All tasks created using the :meth:`~@Celery.task` decorator
  270. will inherit from the applications base :attr:`~@Celery.Task` class.
  271. You can specify a different base class with the ``base`` argument:
  272. .. code-block:: python
  273. @celery.task(base=OtherTask):
  274. def add(x, y):
  275. return x + y
  276. To create a custom task class you should inherit from the neutral base
  277. class: :class:`celery.Task`.
  278. .. code-block:: python
  279. from celery import Task
  280. class DebugTask(Task):
  281. abstract = True
  282. def __call__(self, *args, **kwargs):
  283. print('TASK STARTING: {0.name}[{0.request.id}].format(self))
  284. return self.run(*args, **kwargs)
  285. The neutral base class is special because it's not bound to any specific app
  286. yet. Concrete subclasses of this class will be bound, so you should
  287. always mark generic base classes as ``abstract``
  288. Once a task is bound to an app it will read configuration to set default values
  289. and so on.
  290. It's also possible to change the default base class for an application
  291. by changing its :meth:`@Celery.Task` attribute:
  292. .. code-block:: python
  293. >>> from celery import Celery, Task
  294. >>> celery = Celery()
  295. >>> class MyBaseTask(Task):
  296. ... abstract = True
  297. ... send_error_emails = True
  298. >>> celery.Task = MyBaseTask
  299. >>> celery.Task
  300. <unbound MyBaseTask>
  301. >>> @x.task
  302. ... def add(x, y):
  303. ... return x + y
  304. >>> add
  305. <@task: __main__.add>
  306. >>> add.__class__.mro()
  307. [<class add of <Celery __main__:0x1012b4410>>,
  308. <unbound MyBaseTask>,
  309. <unbound Task>,
  310. <type 'object'>]