application.rst 12 KB

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