application.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. >>> app = Celery()
  17. >>> app
  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. >>> @app.task
  35. ... def add(x, y):
  36. ... return x + y
  37. >>> add
  38. <@task: __main__.add>
  39. >>> add.name
  40. __main__.add
  41. >>> app.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. app = Celery()
  54. @app.task
  55. def add(x, y): return x + y
  56. if __name__ == '__main__':
  57. app.worker_main()
  58. When this module is executed the tasks will be named starting with "``__main__``",
  59. but when 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. >>> app = Celery('tasks')
  67. >>> app.main
  68. 'tasks'
  69. >>> @app.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. >>> app.conf.CELERY_TIMEZONE
  82. 'Europe/London'
  83. where you can set configuration values directly::
  84. >>> app.conf.CELERY_ENABLE_UTC = True
  85. or you can update several keys at once by using the ``update`` method::
  86. >>> app.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. app = Celery()
  111. app.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. .. tip::
  120. Using the name of a module is recomended
  121. as this means that the module doesn't need to be serialized
  122. when the multiprocessing pool is used. If you're
  123. experiencing configuration pickle errors then please try using
  124. the name of a module instead.
  125. .. code-block:: python
  126. from celery import Celery
  127. app = Celery()
  128. import celeryconfig
  129. app.config_from_object(celeryconfig)
  130. Example 3: Using a configuration class/object
  131. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  132. .. code-block:: python
  133. from celery import Celery
  134. app = Celery()
  135. class Config:
  136. CELERY_ENABLE_UTC = True
  137. CELERY_TIMEZONE = 'Europe/London'
  138. app.config_from_object(Config)
  139. ``config_from_envvar``
  140. ----------------------
  141. The :meth:`@Celery.config_from_envvar` takes the configuration module name
  142. from an environment variable
  143. For example -- to load configuration from a module specified in the
  144. environment variable named :envvar:`CELERY_CONFIG_MODULE`:
  145. .. code-block:: python
  146. import os
  147. from celery import Celery
  148. #: Set default configuration module name
  149. os.environ.setdefault('CELERY_CONFIG_MODULE', 'celeryconfig')
  150. app = Celery()
  151. app.config_from_envvar('CELERY_CONFIG_MODULE')
  152. You can then specify the configuration module to use via the environment:
  153. .. code-block:: bash
  154. $ CELERY_CONFIG_MODULE="celeryconfig.prod" celery worker -l info
  155. Laziness
  156. ========
  157. The application instance is lazy, meaning that it will not be evaluated
  158. until something is actually needed.
  159. Creating a :class:`@Celery` instance will only do the following:
  160. #. Create a logical clock instance, used for events.
  161. #. Create the task registry.
  162. #. Set itself as the current app (but not if the ``set_as_current``
  163. argument was disabled)
  164. #. Call the :meth:`@Celery.on_init` callback (does nothing by default).
  165. The :meth:`~@Celery.task` decorator does not actually create the
  166. tasks at the point when it's called, instead it will defer the creation
  167. of the task to happen either when the task is used, or after the
  168. application has been *finalized*,
  169. This example shows how the task is not created until
  170. you use the task, or access an attribute (in this case :meth:`repr`):
  171. .. code-block:: python
  172. >>> @app.task
  173. >>> def add(x, y):
  174. ... return x + y
  175. >>> type(add)
  176. <class 'celery.local.PromiseProxy'>
  177. >>> add.__evaluated__()
  178. False
  179. >>> add # <-- causes repr(add) to happen
  180. <@task: __main__.add>
  181. >>> add.__evaluated__()
  182. True
  183. *Finalization* of the app happens either explicitly by calling
  184. :meth:`@Celery.finalize` -- or implicitly by accessing the :attr:`~@Celery.tasks`
  185. attribute.
  186. Finalizing the object will:
  187. #. Copy tasks that must be shared between apps
  188. Tasks are shared by default, but if the
  189. ``shared`` argument to the task decorator is disabled,
  190. then the task will be private to the app it's bound to.
  191. #. Evaluate all pending task decorators.
  192. #. Make sure all tasks are bound to the current app.
  193. Tasks are bound to apps so that it can read default
  194. values from the configuration.
  195. .. _default-app:
  196. .. topic:: The "default app".
  197. Celery did not always work this way, it used to be that
  198. there was only a module-based API, and for backwards compatibility
  199. the old API is still there.
  200. Celery always creates a special app that is the "default app",
  201. and this is used if no custom application has been instantiated.
  202. The :mod:`celery.task` module is there to accommodate the old API,
  203. and should not be used if you use a custom app. You should
  204. always use the methods on the app instance, not the module based API.
  205. For example, the old Task base class enables many compatibility
  206. features where some may be incompatible with newer features, such
  207. as task methods:
  208. .. code-block:: python
  209. from celery.task import Task # << OLD Task base class.
  210. from celery import Task # << NEW base class.
  211. The new base class is recommended even if you use the old
  212. module-based API.
  213. Breaking the chain
  214. ==================
  215. While it's possible to depend on the current app
  216. being set, the best practice is to always pass the app instance
  217. around to anything that needs it.
  218. I call this the "app chain", since it creates a chain
  219. of instances depending on the app being passed.
  220. The following example is considered bad practice:
  221. .. code-block:: python
  222. from celery import current_app
  223. class Scheduler(object):
  224. def run(self):
  225. app = current_app
  226. Instead it should take the ``app`` as an argument:
  227. .. code-block:: python
  228. class Scheduler(object):
  229. def __init__(self, app):
  230. self.app = app
  231. Internally Celery uses the :func:`celery.app.app_or_default` function
  232. so that everything also works in the module-based compatibility API
  233. .. code-block:: python
  234. from celery.app import app_or_default
  235. class Scheduler(object):
  236. def __init__(self, app=None):
  237. self.app = app_or_default(app)
  238. In development you can set the :envvar:`CELERY_TRACE_APP`
  239. environment variable to raise an exception if the app
  240. chain breaks:
  241. .. code-block:: bash
  242. $ CELERY_TRACE_APP=1 celery worker -l info
  243. .. topic:: Evolving the API
  244. Celery has changed a lot in the 3 years since it was initially
  245. created.
  246. For example, in the beginning it was possible to use any callable as
  247. a task:
  248. .. code-block:: python
  249. def hello(to):
  250. return 'hello {0}'.format(to)
  251. >>> from celery.execute import apply_async
  252. >>> apply_async(hello, ('world!', ))
  253. or you could also create a ``Task`` class to set
  254. certain options, or override other behavior
  255. .. code-block:: python
  256. from celery.task import Task
  257. from celery.registry import tasks
  258. class Hello(Task):
  259. send_error_emails = True
  260. def run(self, to):
  261. return 'hello {0}'.format(to)
  262. tasks.register(Hello)
  263. >>> Hello.delay('world!')
  264. Later, it was decided that passing arbitrary call-ables
  265. was an anti-pattern, since it makes it very hard to use
  266. serializers other than pickle, and the feature was removed
  267. in 2.0, replaced by task decorators:
  268. .. code-block:: python
  269. from celery.task import task
  270. @task(send_error_emails=True)
  271. def hello(x):
  272. return 'hello {0}'.format(to)
  273. Abstract Tasks
  274. ==============
  275. All tasks created using the :meth:`~@Celery.task` decorator
  276. will inherit from the applications base :attr:`~@Celery.Task` class.
  277. You can specify a different base class with the ``base`` argument:
  278. .. code-block:: python
  279. @app.task(base=OtherTask):
  280. def add(x, y):
  281. return x + y
  282. To create a custom task class you should inherit from the neutral base
  283. class: :class:`celery.Task`.
  284. .. code-block:: python
  285. from celery import Task
  286. class DebugTask(Task):
  287. abstract = True
  288. def __call__(self, *args, **kwargs):
  289. print('TASK STARTING: {0.name}[{0.request.id}]'.format(self))
  290. return self.run(*args, **kwargs)
  291. The neutral base class is special because it's not bound to any specific app
  292. yet. Concrete subclasses of this class will be bound, so you should
  293. always mark generic base classes as ``abstract``
  294. Once a task is bound to an app it will read configuration to set default values
  295. and so on.
  296. It's also possible to change the default base class for an application
  297. by changing its :meth:`@Celery.Task` attribute:
  298. .. code-block:: python
  299. >>> from celery import Celery, Task
  300. >>> app = Celery()
  301. >>> class MyBaseTask(Task):
  302. ... abstract = True
  303. ... send_error_emails = True
  304. >>> app.Task = MyBaseTask
  305. >>> app.Task
  306. <unbound MyBaseTask>
  307. >>> @x.task
  308. ... def add(x, y):
  309. ... return x + y
  310. >>> add
  311. <@task: __main__.add>
  312. >>> add.__class__.mro()
  313. [<class add of <Celery __main__:0x1012b4410>>,
  314. <unbound MyBaseTask>,
  315. <unbound Task>,
  316. <type 'object'>]