application.rst 12 KB

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